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
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
Step 2
Now generate a public key and a private key using the command prompt.
CMD Run As Administotor,
Command : cd/
Command : set OPENSSL_CONF=C:\OpenSSL-Win64\bin\openssl.cfg
Command : OpenSSL-Win64\bin\openssl.exe version
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.
Command : OpenSSL-Win64\bin\openssl.exe rsa -in privatekey.pem -pubout -out publickey.pem
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.
All the commands are done, now go to your C Drive and in C Drive you are shown 4 Files
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:
- private static IWebHostEnvironment _hostEnvironment;
- public HomeController(IWebHostEnvironment environment)
- {
- _hostEnvironment = environment;
- }
For encryption:
- public static string EncryptUsingCertificate(string data) {
- try {
- byte[] byteData = Encoding.UTF8.GetBytes(data);
- string path = Path.Combine(_hostEnvironment.WebRootPath, "mycert.pem");
- var collection = new X509Certificate2Collection();
- collection.Import(path);
- var certificate = collection[0];
- var output = "";
- using(RSA csp = (RSA) certificate.PublicKey.Key) {
- byte[] bytesEncrypted = csp.Encrypt(byteData, RSAEncryptionPadding.OaepSHA1);
- output = Convert.ToBase64String(bytesEncrypted);
- }
- return output;
- } catch (Exception ex) {
- return "";
- }
- }
For decryption:
- public static string DecryptUsingCertificate(string data) {
- try {
- byte[] byteData = Convert.FromBase64String(data);
- string path = Path.Combine(_hostEnvironment.WebRootPath, "mycertprivatekey.pfx");
- var Password = "123";
- var collection = new X509Certificate2Collection();
- collection.Import(System.IO.File.ReadAllBytes(path), Password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
- X509Certificate2 certificate = new X509Certificate2();
- certificate = collection[0];
- foreach(var cert in collection) {
- if (cert.FriendlyName.Contains("my certificate")) {
- certificate = cert;
- }
- }
- if (certificate.HasPrivateKey) {
- RSA csp = (RSA) certificate.PrivateKey;
- var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
- var keys = Encoding.UTF8.GetString(csp.Decrypt(byteData, RSAEncryptionPadding.OaepSHA1));
- return keys;
- }
- } catch (Exception ex) {}
- return null;
- }
Now we have just used this method:
- public IActionResult Index() {
- var data = "Hello World";
- var encryptdat = EncryptUsingCertificate(data);
- var orginaldata = DecryptUsingCertificate(encryptdat);
- return View();
- }
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.