且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用RSA公共密钥配置到使用RSA私钥加密的字符串进行解密

更新时间:2023-01-31 19:09:30

已经看了一些关于RSA加密模式的信息,这样看来,PKCS#1 V1.5(你正在使用的,因为你调用解密(...,FALSE)

Having looked at some of the information on RSA encryption modes, it would appear that PKCS#1 v1.5 (which you're using, because you're calling Decrypt(..., false))

......可以在长度的消息的达至k操作 - 11个字节(k是字节长度的RSA模数)

"...can operate on messages of length up to k - 11 octets (k is the octet length of the RSA modulus)"

(RFC 3447,重点煤矿)。

(RFC 3447, emphasis mine).

根据错误信息,这表明你的关键是128个字节,这意味着你无法执行RSA(ZH | DE)使用PKCS#1 V1.5上的消息有超过128 cryption - 11 = 117个字节。

Based on the error message, which indicates that your key is 128 bytes, that means that you can't perform RSA (en|de)cryption using PKCS#1 v1.5 on a message with more than 128 - 11 = 117 bytes.

,你应该使用对称算法来对邮件正文加密,并且只加密使用RSA对称加密密钥。只有当你的信息是相当短的(即低于117字节的密钥大小),你应该考虑直接使用RSA加密邮件。

Instead of encrypting your message directly using RSA, you should be using a symmetric algorithm to encrypt the body of the message, and encrypt only the symmetric encryption key using RSA. Only if your message is reasonably short (i.e. below 117 bytes for your key size) should you consider encrypting the message directly with RSA.

我添加了下面,假设你输入的Base64 EN codeD,你在下面您的评论指出:

I have added the following, assuming that your input is Base64 encoded as you indicate in your comment below:

public string DecryptUsingPublic(string dataEncryptedBase64, string publicKey)
    {
        if (dataEncryptedBase64 == null) throw new ArgumentNullException("dataEncryptedBase64");
        if (publicKey == null) throw new ArgumentNullException("publicKey");
        try
        {
            RSAParameters _publicKey = LoadRsaPublicKey(publicKey, false);
            RSACryptoServiceProvider rsa = InitRSAProvider(_publicKey);

            byte[] bytes = Convert.FromBase64String(dataEncryptedBase64);
            byte[] decryptedBytes = rsa.Decrypt(bytes, false);

            // I assume here that the decrypted data is intended to be a
            // human-readable string, and that it was UTF8 encoded.
            return Encoding.UTF8.GetString(decryptedBytes);
        }
        catch
        {
            return null;
        }
    }