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 ?
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.
The public key algorithms in use today are: Rivest-Shamir-Adleman (RSA) Elliptic Curve Digital Signature Algorithm (ECDSA) Digital Signature Algorithm (DSA)
Public Key (or asymmetric encryption)In a public key system, two keys are used, one for encrypting and one for decrypting.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With