2009-06-04 93 views
1

我必须使用AES和RSA来实现数字信封,但是我在RSA算法的.NET实现方面遇到问题。使用模数和公开指数的C#RSA加密

我设法用随机对称密钥加密数据(AES),但现在我必须用RSA加密密钥。

关键是字节数组(byte[])和公钥我告诉我只有模数和公开指数,两个字节数组(byte[])。

仅使用这两个参数,我如何使用RSA加密AES生成的密钥?

以下代码从文件中检索消息并使用AES对其进行加密。 之后,公钥将从公钥文件中读取,并且模数和指数位于其适当的字节数组中。我将如何继续使用RSA加密symmetricKey

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.在回答提及rsa.ImportParameters: 答案我已经尝试过rsa.ImportParameters(keyInfo),但它会抛出CryptographicException"Bad Data")。数组大小呢? 目前,模数为128字节,指数为64字节。

+0

如果您使用rsa.ExportParameters(false);那么你会得到一个3字节的指数和一个128字节的模数 – ShuggyCoUk 2009-06-22 14:49:29

回答

5

使用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;  
} 

所以你需要什么是RSAParameters但所有你需要设置的弹性模量和指数进行加密。