How to Decrypt data using RSA algorithm in C#?

In this article, we have sample code for decrypting encrypted data with the help of the RSA Decryption algorithm and .pfx file, which contains a private key for decryption.

RSA Decryption using private key, i.e .pfx file in C#

For decrypting data coming from the client in an encrypted format with the help of a .pfx file, which contains the private key.

Here we require X509Certificate2 and .pfx file.

  • X509Certificate2 is a subclass of x509Certificate which gives access to all the properties, such as an Authority Key Identifier.
  • So with the help of this x509Certificate class and protected Password for .pfx file, we can get the private key of the certificate, which is stored at the physical path or on the server machine in the form .pfx extension.

So let's see practically...

Note: Here encryptedData is Encrypted data or string from the client, which is encrypted by using Public Key.

public string DecryptData()
{
    string decryptedData= "";
    string encryptedData= "Encrypted data string is here...";
    if (encryptedData!= "")
    {
        byte[] encryptedBytes;
        byte[] decryptedBytes;
        encryptedBytes = Convert.FromBase64String(encryptedData);
        X509Certificate2 cert = PrivateKeyFromCert();
        RSACryptoServiceProvider rsaProv = cert.PrivateKey as RSACryptoServiceProvider;
        decryptedBytes = rsaProv.Decrypt(encryptedBytes, false);
        ASCIIEncoding byteConverter = new ASCIIEncoding();
        decryptedData= byteConverter.GetString(decryptedBytes);
    }
    else
    {
        decryptedData= "Error While Receiving Data.";
    }
    return decryptedData;
}

public static X509Certificate2 PrivateKeyFromCert()
{
    return new X509Certificate2(@"C:\cert_name.pfx",Password",X509KeyStorageFlags.Exportable);            
}


Recommended Free Ebook
Similar Articles