2
votes

I have to implement a digital envelope using AES and RSA, but I am having problems with the .NET implementation of the RSA algorithm.

I have managed to encrypt the data (AES) with the random symmetric key, but now I have to encrypt the key with RSA.

The key is an array of bytes (byte[]) and the public key I have tells me only the modulus and the public exponent, both arrays of bytes (byte[]).

Using only those two parameters, how can I encrypt my AES generated key with RSA?

The following code retrieves the message from file and encrypts it with AES. Afterwards, the public key is read from the public key file and the modulus and the exponent are in their appropriate byte arrays. How would I continue to encrypt the symmetricKey with RSA?

String msgString = Systematic.GetFileContents(messagePath);
Byte[] initVector = new byte[] { 50, 60, 70, 80, 90, 40, 50, 60, 70, 80, 90, 40, 60, 80, 70, 90 };
Byte[] symetricKey = AesCrypt.GenerateRandomKey();
Byte[] encryptedMessage = AesCrypt.Encrypt(msgString, symetricKey, initVector, mode);
Byte[] modulus = null;
Byte[] publicExp = null; 
DataFormatHelper.ReadPublicKey(publicKeyPath, "RSA", ref modulus, ref publicExp);

P.S. In reply to the answer mentioning rsa.ImportParameters: I've tried with the rsa.ImportParameters(keyInfo) but it throws a CryptographicException ("Bad Data"). What about array sizes? Currently, the modulus is 128 bytes and the exponent 64 bytes.

1
If you use rsa.ExportParameters(false); then you get a 3 byte exponent and a 128 byte modulousShuggyCoUk

1 Answers

5
votes

Using RSACryptoServiceProvider

static public byte[] RSAEncrypt(byte[] data,
    RSAParameters keyInfo, 
    bool doOAEPPadding)
{
    byte[] encryptedData;
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        //Import the RSA Key information. This only needs
        //toinclude the public key information.
        rsa.ImportParameters(keyInfo);

        //Encrypt the passed byte array and specify OAEP padding.  
        //OAEP padding is only available on Microsoft Windows XP or later.  
        encryptedData = rsa.Encrypt(data, doOAEPPadding);
    }
    return encryptedData;       
}

So what you need are the RSAParameters but all you need to set are the Modulus and the Exponent to encrypt.