0

I'm trying to encode a phrase using a public key. RSA encryption strategy with mode ECB, padding PKCS1Padding and KeyLength 1024 is used to encrypt data at client side.

The key is stored in the path : C:\ALFABETA\Documents\GAMMA

The key has the following format:

-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkq3XbDI1s8Lu7.......xjg+7fF0tB4O3Ic9Gxuv4pFkbQIDAQAB -----END PUBLIC KEY-----

The code is the following :

    public static string EncryptFromPublicKey(string kwypath, string data)
    {
        try
        {
            var publicKey = File.ReadAllBytes(kwypath);
            var rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(publicKey);
            var dataToEncrypt = Encoding.ASCII.GetBytes(data);
            var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
            var length = encryptedByteArray.Count();
            var item = 0;
            var sb = new StringBuilder();
            foreach (var x in encryptedByteArray)
            {
                item++;
                sb.Append(x);

                if (item < length)
                    sb.Append(",");
            }

            return sb.ToString();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        } 
    }

When I'm trying to execute rsa.ImportCspBlob(publicKey) I got the following exception :

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Bad Version of provider.

Also with rsa.ImportRSAPublicKey(new ReadOnlySpan(publicKey), out _); I get a exception.

How can I solve it? Thanks

  • Your key may not be CSP compatible. See eg [this question](https://stackoverflow.com/questions/56373628/failed-to-import-rsa-private-key-bad-version-of-provider) – stuartd Jul 29 '22 at 16:11

1 Answers1

0

I solved my problem changing the code as follows below :

    public static string EncryptFromPublicKey(string keyPath, string data)
    {
        try
        {
            var keyString = File.ReadAllText(keyPath);
            var rsa = new RSACryptoServiceProvider();
            rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(keyString), out _);
            var dataToEncrypt = Encoding.ASCII.GetBytes(data);
            var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
            return Convert.ToBase64String(encryptedByteArray);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }