【问题标题】:C# RSA encryption using modulus and public exponent使用模数和公共指数的 C# RSA 加密
【发布时间】:2010-10-31 06:37:57
【问题描述】:

我必须使用 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);

附:回复提到rsa.ImportParameters的答案: 我试过rsa.ImportParameters(keyInfo),但它会抛出CryptographicException"Bad Data")。数组大小呢? 目前,模数为 128 字节,指数为 64 字节。

【问题讨论】:

  • 如果你使用 rsa.ExportParameters(false);然后你得到一个 3 字节的指数和一个 128 字节的模

标签: c# encryption rsa


【解决方案1】:

使用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,但您需要设置的只是要加密的模数和指数。

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 2015-10-13
    • 2014-04-16
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2017-11-03
    相关资源
    最近更新 更多