views:

1498

answers:

2

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 symetric 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, 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 "symetricKey" 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);

EDIT In reply to rsa.ImportParameters answer:

I've tried with the rsa.ImportParameters(keyInfo) but it throws a CryptographicException ("Bad Data"). What about array sizes? Currently, modulus is 128 bytes and Exponent 64 bytes.

+2  A: 

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.

ShuggyCoUk
A: 

And how o decrypt the same. while decrypting it gives error as "Error occurred while decoding OAEP padding".

Meetu Choudhary