ASP.NET Core - Encrypt And Decrypt Public Key And Private Key

Introduction

 
In this article, we will learn how to encrypt and decrypt using a public key and a private key using ASP.NET Core. 
 
Now we will start.
 
Step 1
 
First, we need to download the OpenSSL. To download it, go to the below URL.
 
https://slproweb.com/products/Win32OpenSSL.html
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key 
 
Download and install this .exe 
 
Note, when you install, you have to change the path and install the C Drive (remove \Program Files in the path)
 
The current path is C:\OpenSSL-Win64
 
Asp.net Core Encrypt And Decrypt Public Key And Private KeyAsp.net Core Encrypt And Decrypt Public Key And Private Key
 
Step 2
 
Now generate a public key and a private key using the command prompt.
 
CMD Run As Administotor,
 
Command : cd/
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key 
 
Command : set OPENSSL_CONF=C:\OpenSSL-Win64\bin\openssl.cfg
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key 
 
Command : OpenSSL-Win64\bin\openssl.exe version
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key 
 
Command - OpenSSL-Win64\bin\openssl.exe req -x509 -nodes -days 3650 -newkey rsa:1024 -keyout privatekey.pem -out mycert.pem
 
In the output, you just hit the enter again and again when the next command is not shown.
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key
 
Command : OpenSSL-Win64\bin\openssl.exe rsa -in privatekey.pem -pubout -out publickey.pem
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key 
 
Command - OpenSSL-Win64\bin\openssl.exe pkcs12 -export -out mycertprivatekey.pfx -in mycert.pem -inkey privatekey.pem -name "my certificate"
 
In this command, it asks to enter the password. You just enter the password and again need to enter the same password. 
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key 
 
All the commands are done, now go to your C Drive and in C Drive you are shown 4 Files
 
Asp.net Core Encrypt And Decrypt Public Key And Private Key 
 
In these files, mycert.pem file is the Public Key.
 
And mycertprivatekey is Private Key.
 
Now your ASP.NET project.
 
Just copy these two files and paste them to the wwwroot folder.
 
Now start with the code.
 
Goes to controller:
  1. private static IWebHostEnvironment _hostEnvironment;  
  2. public HomeController(IWebHostEnvironment environment)  
  3. {  
  4. _hostEnvironment = environment;  
  5. }  
For encryption:
  1. public static string EncryptUsingCertificate(string data) {  
  2.     try {  
  3.         byte[] byteData = Encoding.UTF8.GetBytes(data);  
  4.         string path = Path.Combine(_hostEnvironment.WebRootPath, "mycert.pem");  
  5.         var collection = new X509Certificate2Collection();  
  6.         collection.Import(path);  
  7.         var certificate = collection[0];  
  8.         var output = "";  
  9.         using(RSA csp = (RSA) certificate.PublicKey.Key) {  
  10.             byte[] bytesEncrypted = csp.Encrypt(byteData, RSAEncryptionPadding.OaepSHA1);  
  11.             output = Convert.ToBase64String(bytesEncrypted);  
  12.         }  
  13.         return output;  
  14.     } catch (Exception ex) {  
  15.         return "";  
  16.     }  
  17. }  
For decryption:
  1. public static string DecryptUsingCertificate(string data) {  
  2.     try {  
  3.         byte[] byteData = Convert.FromBase64String(data);  
  4.         string path = Path.Combine(_hostEnvironment.WebRootPath, "mycertprivatekey.pfx");  
  5.         var Password = "123"//Note This Password is That Password That We Have Put On Generate Keys  
  6.         var collection = new X509Certificate2Collection();  
  7.         collection.Import(System.IO.File.ReadAllBytes(path), Password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);  
  8.         X509Certificate2 certificate = new X509Certificate2();  
  9.         certificate = collection[0];  
  10.         foreach(var cert in collection) {  
  11.             if (cert.FriendlyName.Contains("my certificate")) {  
  12.                 certificate = cert;  
  13.             }  
  14.         }  
  15.         if (certificate.HasPrivateKey) {  
  16.             RSA csp = (RSA) certificate.PrivateKey;  
  17.             var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;  
  18.             var keys = Encoding.UTF8.GetString(csp.Decrypt(byteData, RSAEncryptionPadding.OaepSHA1));  
  19.             return keys;  
  20.         }  
  21.     } catch (Exception ex) {}  
  22.     return null;  
  23. }  
Now we have just used this method:
  1. public IActionResult Index() {  
  2.     var data = "Hello World";  
  3.     var encryptdat = EncryptUsingCertificate(data);  
  4.     var orginaldata = DecryptUsingCertificate(encryptdat);  
  5.     return View();  
  6. }  

Summary

 
In this article, we learned about Encryption And Decryption with the help of public and private keys using ASP.NET Core.
 
This article gives you a basic understanding of how we can generate a Public and Private Key with the help of Open SSL.