使用模数和公共(public)指数的 C# RSA 加密

标签 c# encryption rsa

我必须使用 AES 和 RSA 实现数字信封,但我在 RSA 算法的 .NET 实现方面遇到问题。

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

key 是一个字节数组(byte[]),我的公钥只告诉我模数和公共(public)指数,两个字节数组(byte[])。

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

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

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(“错误数据”)。数组大小怎么样? 目前模数为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但您需要设置的只是要加密的模数和指数。

关于使用模数和公共(public)指数的 C# RSA 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/949543/

相关文章:

RSA签名验证参数说明

go - 如何在golang中使用N=和E=解析公钥?

PowerShell RSA 解密

c# - 带有修改其他插件的插件的基于插件的应用程序

c++ - OpenSSL 内存 BIO 和部分密码 block

encryption - 使用多个密码解密

c# - 如何加密一串文本,即使值相同,每次加密的字符串都不同

c# - 单例和竞争条件

c# - 在 C# 中重命名外部方法参数是否安全?

c# - 在 WPF .NET Framework 中使用自定义任务管理器时,如何防止进程重复?