1

I am working on an application where I need to encrypt plain text using the RSA algorithm. I encrypt the plain text but it is not working as it gives Error Decoding Text. Basically, I am calling third-party API which gives me the error. When I encrypt my text using this link reference link it works perfectly fine so I think I am doing something wrong. Here is my code

   public static string Encryption(string strText)
        {
            var publicKey = @"<RSAKeyValue><Modulus>MIIDSjCCAjKgAwIBAgIEWrJUKTANBgkqhkiG9w0BAQsFADBmMQswCQYDVQQGEwJE
RTEPMA0GA1UECAwGQmF5ZXJuMQ8wDQYDVQQHDAZNdW5pY2gxDzANBgNVBAoMBkxl
eGNvbTEkMCIGA1UEAwwbQWdyb3BhcnRzX0RNU19CYXNrZXRfVXBsb2FkMCAXDTE4
MDMyMTEyNDYzM1oY################################################
A1UECAwG########################################################
################################################################
WaOa0parvIrMk9/#################################################
NCIeGu+epwg8oUCr6Wd0BNATNjt8Tk64pgQvhdX9/KRDSC8V4QCJBiE3LQPHUVdN
nWRixrcOpucMo6m9PPegjnicn/rBKdFZLfJqLHHm+TrHrNCsEQIDAQABMA0GCSqG
SIb3DQEBCwUAA4IBAQBGwlNnDh2UaZphkEf70MPhySFVnTnLSxUFuwuWaDu8l7YP
zBMeJxcNk3HNiXPeba03GQBj+JqGAwDALJLityGeGEzlESfv/BsgQOONt+lAJUjs
b7+vr2e5REE/dpJZ1kQRQC##########################################
np+GstsdWjIWbL6L6VoqU18qLO5b0k8OoEMsP3akUTcj0w8JwD5V5iLqDhnv1aXK
kntkd/QmVCY6zlzH/dnTh8RNO2CfRtB1GEzNnkJB</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            var testData = Encoding.UTF8.GetBytes(strText);
            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    rsa.FromXmlString(publicKey);
                    byte[] data = Encoding.UTF8.GetBytes(strText);
                    byte[] cipherText = rsa.Encrypt(data,true);
                    var base64Encrypted = Convert.ToBase64String(cipherText);
                    return base64Encrypted;
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }
    }
}

Here is my public key. I am using an RSA certificate. I am passing the certificate key to the module tag here is my key. I think I might be using it wrong.

 -----BEGIN CERTIFICATE-----
    MIIDSjCCAjKgAwIBAgIEWrJUKTANBgkqhkiG9w0BAQsFADBmMQswCQYDVQQGEwJE
RTEPMA0GA1UECAwGQmF5ZXJuMQ8wDQYDVQQHDAZNdW5pY2gxDzANBgNVBAoMBkxl
eGNvbTEkMCIGA1UEAwwbQWdyb3BhcnRzX0RNU19CYXNrZXRfVXBsb2FkMCAXDTE4
MDMyMTEyNDYzM1oY################################################
A1UECAwG########################################################
################################################################
WaOa0parvIrMk9/#################################################
NCIeGu+epwg8oUCr6Wd0BNATNjt8Tk64pgQvhdX9/KRDSC8V4QCJBiE3LQPHUVdN
nWRixrcOpucMo6m9PPegjnicn/rBKdFZLfJqLHHm+TrHrNCsEQIDAQABMA0GCSqG
SIb3DQEBCwUAA4IBAQBGwlNnDh2UaZphkEf70MPhySFVnTnLSxUFuwuWaDu8l7YP
zBMeJxcNk3HNiXPeba03GQBj+JqGAwDALJLityGeGEzlESfv/BsgQOONt+lAJUjs
b7+vr2e5REE/dpJZ1kQRQC##########################################
np+GstsdWjIWbL6L6VoqU18qLO5b0k8OoEMsP3akUTcj0w8JwD5V5iLqDhnv1aXK
kntkd/QmVCY6zlzH/dnTh8RNO2CfRtB1GEzNnkJB
    -----END CERTIFICATE-----

Any help would be highly appreciated. The encryption through this code is not working. But when I used the mentioned link above and pass this key it worked fine.

Kamran Khan
  • 1,042
  • 10
  • 21
  • 1
    *...When I encrypt my text using this link reference link it works perfectly fine...* Doesn't help much unless you specify the selected algorithm. In case it is the default (RSA) or one of the first 3, then PKCS#1 v1.5 padding is applied, while in the C# code OAEP is used (2nd parameter of `Encrypt()` is `true`), i.e. both are incompatible. – Topaco Dec 28 '22 at 21:48
  • Apparently, it doesn't look that easy. I think you have to parse the public key. See this post: https://stackoverflow.com/questions/41808094/correctly-create-rsacryptoserviceprovider-from-public-key – Tim Jarosz Dec 28 '22 at 21:51
  • @Topaco so what do I change to achieve my requirement? I am looking into this issue – Kamran Khan Dec 29 '22 at 10:47
  • Load the certificate into an `X509Certificate2` instance and extract the key with `GetRSAPublicKey()`. Use a padding for the encryption that is agreed with the other side. Note that only short messages can be encrypted with RSA (maximum length = key size - space required by padding). For longer messages use hybrid encryption. – Topaco Dec 29 '22 at 11:34
  • My other requirement is not to install the certificate I need the key to encrypt the password so I don't think my text will be much larger. – Kamran Khan Dec 29 '22 at 11:38
  • @Topaco Thank you so much for the direction. What I found is certificate is different from the public key. For the certificate, you need to load the certificate and then get the public key and use it for encryption. On the other side, public keys can be used directly for encryption. Please make a correct if I am wrong. – Kamran Khan Dec 29 '22 at 12:13
  • That's exactly what @Topaco said to do in his comment. – President James K. Polk Dec 29 '22 at 16:40

1 Answers1

0

The answer to my question is here. I solved my problem and I am posting it because maybe someone in the future will have the same issue I am facing and what mistake I did to achieve my requirements.

Findings

I found during my research there is a difference between Public Key and Certificate. I miss understood the terminology I was passing a certificate instead of passing Public Key for encryption. So one of the community members @Topaco basically redirected me to the correct path which helps me to solve my problem. There are steps involved if you have a public key then you can achieve encryption but if you have a certificate then first you need to get the public key by using the method GetRSAPublicKey. When you got your public key in XML form then you pass it to encrypt method to get your result.

Here is the coding

Program.cs

var x509 = new X509Certificate2(File.ReadAllBytes(@"D:\xyz.cer"));
string xml = x509.GetRSAPublicKey().ToXmlString(false);

var result = EncryptUtil.Encryption("start01!", xml);

Utility Class

 public static string Encryption(string strText, string publicKey)
        {
            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    rsa.FromXmlString(publicKey);
                    byte[] data = Encoding.UTF8.GetBytes(strText);
                    byte[] cipherText = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
                    var base64Encrypted = Convert.ToBase64String(cipherText);
                    return base64Encrypted;
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

So you can achieve encryption using the above code you need to pass RSAEncryptionPadding.Pkcs1 for encryption.

#happycoding #keephelping

Kamran Khan
  • 1,042
  • 10
  • 21