Using an RSA Public Key to decrypt a string that was encrypted using RSA Private Key

后端 未结 3 1478
借酒劲吻你
借酒劲吻你 2020-12-13 16:30

I know the main answer I am likely to get is why the hell would you want to do that?!

Unfortunately despite my protests I have to do it, even though I know it makes

3条回答
  •  攒了一身酷
    2020-12-13 16:46

    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))

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

    (RFC 3447, emphasis mine).

    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.

    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.

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

提交回复
热议问题