1

We can encrypt AES key using RSAPKCS1KeyExchangeFormatter.CreateKeyExchange and RSACryptoServiceProvider.encrypt methods.

Approach 1:

RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(_publicKey);
byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());

Appraoch 2:

var aKey = aesManaged.Key;
var b64aKey = Convert.ToBase64String(aKey);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.ImportParameters(_publicKey.ExportParameters(false));
var bytesaKey = System.Text.Encoding.UTF8.GetBytes(b64aKey);
var aKeyEncrypted = csp.Encrypt(bytesaKey, false);

Here _publicKey is object of RSACryptoServiceProvider.

Can anyone help me to understand, what is the difference between these two ways?

Boss
  • 445
  • 2
  • 8
  • 24
  • 1
    Both codes encrypt with RSA and PKCS#1 v1.5 padding. However, in the first code `aesManaged.Key` is encrypted _directly_, in the second snippet _Base64 encoded_. The Base64 encoding is actually not necessary, unless the recipient cannot decrypt arbitrary binary data, but e.g. only UTF8 compliant data, see your old post: [JSEncrypt decrypts to some garbage value](https://stackoverflow.com/q/68162559/16317602). – Topaco Jul 01 '21 at 09:14
  • Not sure if there any algorithmic differences. But the first approach could be used to handle AES keys that are stored in hardware, while the second approach always requires the AES key to be encoded to bytes (not strings, avoid strings in cryptographic code!). There are HSM's that would allow key wrapping using an RSA public key, for instance. – Maarten Bodewes Jul 01 '21 at 10:10

0 Answers0