Decrypt string with RSA public key
Using an RSA public key to decrypt an RSA private key encrypted string is an uncommon scenario since the public key is more commonly used to encrypt and the private key is used to decrypt, but sometimes a client is unable to accommodate best practices and adaption is needed.
Here’s a C# code snippet that was helpful:
public static X509Certificate2 GetCertificate()
{
return new X509Certificate2(CertPath, CertPassword, X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable);
}
public static string Decrypt(string base64Encrypted)
{
var outBytes = Convert.FromBase64String(base64Encrypted); // in this scenario, the string is passed in with base64 encryption
var cert = GetCertificate();
var rsaPublicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(cert.GetRSAPublicKey());
var pkcs1Encoding = new Pkcs1Encoding(new RsaEngine()); pkcs1Encoding.Init(false, rsaPublicKey);
var decrypted = Encoding.UTF8.GetString(pkcs1Encoding.ProcessBlock(outBytes, 0, outBytes.Length));
return decrypted;
}
Comments
Comments are closed