How to convert raw EC key to PKCS8 without node:crypto export function - react-native

I need to convert raw EC key to pkcs8 and vice versa. I am using react-native-quick-crypto as a replacement for node:crypto. sadly, it does not include node's crypto.createPrivateKey(...).export(...) function so I am unable to use it co convert my keys properly.
This is how am I generating the key:
const ecdh = crypto.createECDH(CURVE)
ecdh.generateKeys()
const privateKey = ecdh.getPrivateKey().toString('base64')
const publicKey = ecdh.getPublicKey().toString('base64')
console.log(privateKey, publicKey)
Running following code gives me a key pair. Private key: xLIGpg9Tb5QN/8nP6AuzMoOlEqL7big8Ikiv and public key: BK432IBI+ZQrEUaL2AMI0I7qt5FmOvj6g7Taech4u0C4FHNyuVfx/gG1U1ORSw+B80zHUcFMsTF4.
Now, I am unable to convert them into pkcs8.
I see, that I can use ec-key library to do that, sadly, it does not accept raw key. But it accepts key in JWK format. So I was thinking I can derive coordinates X, Y, and D (for private key) from generated keys and use the library to transform them (and do the opposite when need to convert them back).
But I am unable to find a way, how can I derive coordinates from raw keys.
Also, if there is an easier way how to do that, I will gladly do it.

Related

How can I verify with mbedtls, that a cert validates a key?

Mbedtls can validate an x509 cert with its mbedtls_x509_crt_verify(...) function (link).
However, what I have:
A public/private key pair (saved in an mbedtls_pk_context).
A certificate I've got from a different source (thus, there is no guarantee that it does not contain any, possible intelligent modifications).
There is no problem with the validation of the certificate.
However, what if that certificate validates a different key? (What can be the result of a software problem and also a crack attempt.) Of course, such a key/cert pair will be unable for a tls handshake, but I don't think that I would need to build up a tcp connection for that.
This source (although it is for openssl scripting) makes likely, that certificate-key matching validation can happen with simply a modulus match.
There is also an mbedtls_pk_verify(...) function (ref), but it seems to me that it plays mostly with signatures. But I have no signatures, I have a cert (got in a pem format), and my key (I have also that in a pem format). Processing them into internal mbedtls data structures (mbedtls_x509_crt and mbedtls_pk_context) is not a problem, but how could I verify that they match?
As this security.SE answer says, for the validation is it enough, if the pubkey in the certificate and in the private key file are the same. It is because it is the only shared information common in them.
Thus, we need to dig out the public key from the mbedtls_pk_content and from the mbedtls_x509_cert and compare them.
The mbedtls has no general API call for this task, but it can be done by algorithm-specific solutions. The steps are the following. Assume that we have
mbedtls_x509_cert crt;
mbedtls_pk_context pk;
Where crt has the certificate and pk is our public-private key pair.
We get the keypair from both. In the case of elliptic curve ciphers, it is being done by the mbedtls_pk_ec(...) macro. In the case of rsa, mbedtls_rsa_context(...) is needed:
mbedtls_ecp_keypair* crt_pair = mbedtls_pk_ec(crt->pk);
mbedtls_ecp_keypair* pk_pair = mbedtls_pk_ec(*pk);
Note, although crt_pair is now a keypair, only its public part will be non-zero, because the certificate has obviously no private key part. mbedtls_pk_ec(...) looks to be some macro-like thing to me, because it doesn't use a pointer to the structs, instead it uses directly a struct.
Then, we compare the public keys in the keypairs:
mbedtls_mpi *pk_pub_X = &pk_pair->Q.X;
mbedtls_mpi *pk_pub_Y = &pk_pair->Q.Y;
mbedtls_mpi *crt_pub_X = &crt_pair->Q.X;
mbedtls_mpi *crt_pub_Y = &crt_pair->Q.Y;
In the case of other algorithms (RSA), these parts might differ, however we always need to have a set of big numbers (mbedtls_mpi), and compare these big numbers.
Then, we use the mbedtls big number functionality to compare them:
bool does_it_differ = mbedtls_mpi_cmp_mpi(pk_pub_X, crt_pub_X) || mbedtls_mpi_cmp_mpi(pk_pub_Y, crt_pub_Y);
Note: verifying the cert match is not enough to verify the cert validity, it is only required for that. The verification of the certificate can be done with the already much more pleasant and simpler mbedtls_x509_crt_verify(...) function.
I know this is an older question, but perhaps mbedtls_pk_check_pair is what you are looking for. Pass it your private/public key pair and the certificates public key.
/**
* \brief Check if a public-private pair of keys matches.
*
* \param pub Context holding a public key.
* \param prv Context holding a private (and public) key.
*
* \return \c 0 on success (keys were checked and match each other).
* \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the keys could not
* be checked - in that case they may or may not match.
* \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA if a context is invalid.
* \return Another non-zero value if the keys do not match.
*/
int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv );

How to decrypt data using RSACng that is previously encrypted with RSACryptoServiceProvider

I am migrating on RSACng for new version release from RSACryptoServiceProvider. However, as RSACryptoserviceProvider that is CAPI uses Little Endian Architecture and RSACng that is CNG API is using Big Endian Architecture, question is how can i decrypt the data using CNG Api that is previously encrypted using RSACryptoService provider (CAPI)?
I have already tried Array.reverse(cypherText) and tried to decrypt using CNG Api, but it is throwing the error, 'The parameter is incorrect'.
I have also tried the approach of decrypting half the cypher text because CNG API is using RSAEncryptionPadding.OaepSHA512 padding whereas CAPI uses OAEP padding.
My RSACryptoServiceProvider class is as below:-
public static void EncryptWithSystemKeyRSACryptoService(byte[]
plainBytes, bool representsUnicodeString, out string cypherText)
{
CspParameters cp = new CspParameters();
cp.KeyContainerName = regValue.ToString();
cp.Flags = CspProviderFlags.UseMachineKeyStore;
cp.KeyNumber = (int)KeyNumber.Exchange;
byte[] encBlockData=null;
using (RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider(cp))
{
res = CryptResult.GeneralError;
int keysize = rsaCSP.KeySize;
//This encrypts data and uses FOAEP padding
encBlockData = rsaCSP.Encrypt(plainBytes, true);
}
//Should i have to reverse the Byte order?
// I am doing Array.reverse for encrypted data as it follows little endian architecture and CNG Api follows Big Endian architecture
Array.Reverse(encBlockData);
cypherText = BitConverter.ToString(encBlockData );
cypherText = cypherText.Replace("-", "");
cypherText = cypherText.ToLower();
}
This is how i encrypt data with RSACryptoservice Provider (CAPI)
My RSACng class is as below :-
//I am calling this to use RSACng API to get private keys
private static byte[] SetPrivateAndPublicKeysAndDecrypt(byte[] cyphertext)
{
cp.KeyContainerName = regValue.ToString();
cp.Flags = CspProviderFlags.UseMachineKeyStore;
cp.KeyNumber = (int)KeyNumber.Exchange;
using (RSACryptoServiceProvider rsaCSP = new
RSACryptoServiceProvider(cp))
{
res = CryptResult.GeneralError;
keysize = rsaCSP.KeySize;
q = rsaCSP.ExportCspBlob(false);
RSAp = rsaCSP.ExportParameters(true);
}
//created cngKey
cngKey = CngKey.Import(q, CngKeyBlobFormat.GenericPublicBlob);
//created RSACng instance
RSACng rsacng = new RSACng(cngKey)
{
KeySize = keysize
};
rsacng.ImportParameters(RSAp);
//Decrypt using RSACng API using OAEPSHA512 padding
var plainText= crypto.Decrypt(cyphertext, RSAEncryptionPadding.OaepSHA512);
return plainText;
}
Expected result should be-> plainText successfully decrypted
Actual Resul-> Exception caught-> 'The parameter is incorrect'.
RSA ciphertext is defined to use statically sized, unsigned, big endian encoding in PKCS#1 (which specifies PKCS#1 v1.5 RSA encryption and OAEP encryption as implemented by most libraries). The function is called I2OSP within that standard, and the ciphertext should have the same size (in full bytes) as the key size. If it isn't big endian, then it does not conform to RSA / OAEP, in other words.
The same goes for normal ASN.1 encoded keys: they use dynamically sized, signed, big endian encoding according to DER (distinguished encoding rules). Those keys are defined in PKCS#1, PKCS#8 and X.509 standards, although they may also be embedded in a PKCS#12 compatible key store - for instance. Sometimes the keys are then PEM encoded as well to make them compatible with protocols that require text rather than binary.
So you should never have to reverse ciphertext or keys that use one of the standard encodings. That the calculations are performed internally on little endian (or not) is of no concern. This is true for about every modern cipher or other cryptographic primitive; the input / output is simply defined in bytes with a specific order, not numbers. Only very low level functions may possibly operate on e.g. words, which muddles the problem (but you won't find that in the MS API's).
Only Microsofts own proprietary (lame) key encodings may use little endian.
bartonjs is of course correct in the comments; you need to match the padding methods, and the default hash to be used for OAEP (or rather, the mask generation function MGF1 within OAEP) is SHA-1. There are plenty of other pitfalls to avoid, such as performing correct encoding / decoding of plaintext / ciphertext.

How to create symmetric encryption key with Google Tink?

I have a key (say) "thisist0psecret" that I want to use as a symmetric encryption/decryption key with the Google Tink library. I am baffled that I am unable to do this simple thing. I can generate new keys (using various templates AES128_GCM, etc.), serialize them and then read them back with KeysetReader. But, for the life of me, I cannot figure out how to create a symmetric key with the specific key bytes that I specify.
I am able to do the following, for example, with Tink:
KeysetHandle ksh = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
Aead aead = AeadFactory.getPrimitive(ksh);
String pt = "hello, world!";
byte[] encbytes = aead.encrypt(pt.getBytes(), null);
byte[] decbytes = aead.decrypt(encbytes, null);
String orig = new String(decbytes);
assert(pt.equals(orig));
But I want to set the symmetric key string to be a set of bytes that I specify such as "thisist0psecret" and then encrypt this key with the public key of the user who will do the decryption.
Any Google Tink experts here that can shed some light?
I'm the lead developer for Tink.
If your key is randomly generated, you can use the subtle API directly, see: https://github.com/google/tink/blob/master/java_src/src/main/java/com/google/crypto/tink/subtle/AesGcmJce.java.
This is not recommended because the subtle layer might change without notice (thought it's been relatively stable in the history of Tink).
If your key is a password you want to derive a key from it using something like Scrypt or PBKDF2. We haven't yet support native password-based encryption in Tink, please file a feature request and we'll see how we can help.

CryptoAPI wrapped keys

With CryptoAPI, is there a way to decrypt (using CryptDecrypt) a key written into a SYMMETRICWRAPKEYBLOB?
In my c++ program, i wrap a symmetric key k1 with another symmetric key k2 into a symmetric key blob. I have a third key, k3, equal to k2 but with a different handle. My goal is to decrypt the blob with this key. I have already did it using a SIMPLEBLOB and a public key.
Thanks in advance for your attention.
Documentation here
As the documentation you link to says, the format used for SYMMETRICWRAPKEYBLOB follows RFC 3217. It is a weird format in which the data is encrypted, then reversed (last byte becomes first, and so on), and then encrypted again. Both encryptions use CBC. If you want to do it by hand, instead of using CryptImportKey(), then you will have to follow RFC 3217, with two calls to CryptDecrypt(), and your code will also have to do the byte reversal and the rest of the packaging.
Alternatively, import the key blob with CryptImportKey(), then export it again by encrypting with an asymmetric (RSA) key of your own, which you can then decrypt. At some point, Microsoft themselves were documenting that, in order to export a symmetric key "as is", the best way was to call CryptExportKey() with a handcrafted RSA public key with a public exponent equal to 1, i.e. not really a correct RSA key -- with such a public exponent, RSA encryption is mostly a no-operation.

OpenSSL RSA Keypair with X509 and PKCS#8 encoding in C or Obj-C

I've been struggling for multiple days now and cannot find any accurate example/tutorial on internet so now i'm here for help.
I have a Java application that creates an RSA Keypair. This Keypair is used to encrypt and decrypt a symmetric key. (but first to test i want to use a simple text string). After generating the keypair, the keys are encoded.
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(pbKey));
and
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(pvBytes);
Now i'm creating an application on iOS. And i would like to do the same in thing in iOS (C or Objective-C) using OpenSSL.
Can somebody help me with this?
I'm creating the keys like this
RSA_generate_key_ex(rsa, modulus, e, NULL);
Basically what you have there is a PKCS#8 encoding of the private key (ks). I.e. raw ASN.1.
I'll assume you write this out raw, encoded (Java asymmetric encryption: preferred way to store public/private keys, Decrypted string not the same as pre encrypted string).
So assumining that rsa is populated; and 'enc' is
const EVP_CIPHER *enc=NULL;
or more likely
const EVP_CIPHER *enc=EVP_aes_XXX_cbc();
where XXX is something like 128 bits you'd then call PEM_write_bio_RSAPrivateKey with something like:
PW_CB_DATA cb_data;
cb_data.password = passout;
cb_data.prompt_info = outfile;
BIO_set_fp(out,stdout,BIO_NOCLOSE);
if (!PEM_write_bio_RSAPrivateKey(out,rsa,enc,NULL,0,
(pem_password_cb *)password_callback,&cb_data))
goto err;
and that should be roughly it. Code can be lifted from apps/genrsa.c in any openssl source distribuition.