Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use public and private key encryption technique in C#

I want to encrypt data using public/private key technique. I mean, encrypt with the public key of receiver and the receiver can decrypt with their own private key.

How can I do that? Do you have any suggestion or sample code ?

like image 333
cagin Avatar asked Aug 28 '13 10:08

cagin


People also ask

How are public and private keys used in encryption?

Public key cryptography is a method of encrypting or signing data with two different keys and making one of the keys, the public key, available for anyone to use. The other key is known as the private key. Data encrypted with the public key can only be decrypted with the private key.

Which algorithm is used for public key encryption?

The public key algorithms in use today are: Rivest-Shamir-Adleman (RSA) Elliptic Curve Digital Signature Algorithm (ECDSA) Digital Signature Algorithm (DSA)

Can public key be used for both encryption and decryption?

Public Key (or asymmetric encryption)In a public key system, two keys are used, one for encrypting and one for decrypting.


1 Answers

Code example:

private static string _privateKey; private static string _publicKey; private static UnicodeEncoding _encoder = new UnicodeEncoding();  private static void RSA() {   var rsa = new RSACryptoServiceProvider();   _privateKey = rsa.ToXmlString(true);   _publicKey = rsa.ToXmlString(false);    var text = "Test1";   Console.WriteLine("RSA // Text to encrypt: " + text);   var enc = Encrypt(text);   Console.WriteLine("RSA // Encrypted Text: " + enc);   var dec = Decrypt(enc);   Console.WriteLine("RSA // Decrypted Text: " + dec); }  public static string Decrypt(string data) {   var rsa = new RSACryptoServiceProvider();   var dataArray = data.Split(new char[] { ',' });   byte[] dataByte = new byte[dataArray.Length];   for (int i = 0; i < dataArray.Length; i++)   {     dataByte[i] = Convert.ToByte(dataArray[i]);   }    rsa.FromXmlString(_privateKey);   var decryptedByte = rsa.Decrypt(dataByte, false);   return _encoder.GetString(decryptedByte); }  public static string Encrypt(string data) {   var rsa = new RSACryptoServiceProvider();   rsa.FromXmlString(_publicKey);   var dataToEncrypt = _encoder.GetBytes(data);   var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();   var length = encryptedByteArray.Count();   var item = 0;   var sb = new StringBuilder();   foreach (var x in encryptedByteArray)   {     item++;     sb.Append(x);      if (item < length)       sb.Append(",");   }    return sb.ToString(); } 
like image 56
Erwin Avatar answered Sep 27 '22 20:09

Erwin