In explicable error with RSA encrypt (with RSAEncryptionPadding.OaepSHA256) based on the input bytes

2

I am using C# with .net core 3.1 on windows 10.

The option 1 in the following code successfully encrypts the plane bytes but the option 2 throw an error on Encrypt method. The only difference is the input bytes.

private byte[] TestCode()
{
    var cert = new X509Certificate2("<PEM-FILE-WITH-CERTIFICATE>");
    var publicKey = cert.GetRSAPublicKey();

    var plainConnectionInfo1 = new PlainConnectionInfo()
    {
        ConnectionStringWithoutPath = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
        Path = "222222222222"
    };

    byte[] encryptedBytes = null;
    byte[] plainBytes = null;
    var option = 1;

    if (option == 1)
    {
        //Option 1
        plainBytes = UTF8Encoding.UTF8.GetBytes(plainConnectionInfo1.ConnectionStringWithoutPath);
        encryptedBytes = publicKey.Encrypt(plainBytes, RSAEncryptionPadding.OaepSHA256);
    }
    else
    {
        //Option 2
        var plainConnectionInfo1Json = JsonConvert.SerializeObject(plainConnectionInfo1);
        plainBytes = UTF8Encoding.UTF8.GetBytes(plainConnectionInfo1Json);
        encryptedBytes = publicKey.Encrypt(plainBytes, RSAEncryptionPadding.OaepSHA256);
    }

    return encryptedBytes;
}

The only difference between option 1 and 2 is that there is a bit more text in the option 2 (compared to option 1). The option 2 is a json string where as it is just a string in option 1. Both strings were converted into UTF8 encoded bytes prior to encryption.

The option 2 throws following error at me:

Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException
  HResult=0x80090027
  Message=The parameter is incorrect.
  Source=System.Security.Cryptography.Cng
  StackTrace:
   at System.Security.Cryptography.RSACng.EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan`1 input, AsymmetricPaddingMode paddingMode, Void* paddingInfo, Boolean encrypt)
   at System.Security.Cryptography.RSACng.EncryptOrDecrypt(Byte[] data, RSAEncryptionPadding padding, Boolean encrypt)
   at System.Security.Cryptography.RSACng.Encrypt(Byte[] data, RSAEncryptionPadding padding)

Based on the error, I could not decipher as to what I am doing wrong. Can someone please explain?

c#
.net-core
cryptography
rsa
public-key-encryption
asked on Stack Overflow Oct 22, 2020 by Raghu

1 Answer

1

I was using RSA public key with key size of 2048. With this key size, one could only encrypt 190 bytes at any time. This is explained fully here: https://crypto.stackexchange.com/questions/42097/what-is-the-maximum-size-of-the-plaintext-message-for-rsa-oaep

answered on Stack Overflow Oct 23, 2020 by Raghu

User contributions licensed under CC BY-SA 3.0