簡體   English   中英

使用模數和公共指數的C#RSA加密

[英]C# RSA encryption using modulus and public exponent

我必須使用AES和RSA實現數字信封,但是RSA算法的.NET實現存在問題。

我已經設法使用隨機對稱密鑰對數據(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);

PS在回答提到rsa.ImportParameters的答案時,我已經嘗試過rsa.ImportParameters(keyInfo)但是它拋出CryptographicException"Bad Data" )。 數組大小呢? 當前,模數為128字節,指數為64字節。

使用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,但您需要設置的只是要加密的Modulus和Expnent。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM