so if you your friend wanted to send you something securely you could send him the public key, he could use it to encrypt the data and send it to you. You then would use the private key to decrypt the message.
The main disadvantage of Asymmetric encryption is that because it is more complex it's also slower, but on the other hand you eliminate the secret key, greatly minimizing the odds of your encryption key becoming compromised.
using System;
using System.Security.Cryptography;
using System.Text;
namespace pc.AsymmetricEncryption01
{
class Program
{
static byte[]
Encrypt(string Data, out string publicKey, out string privateKey) {
using (var RSA = new RSACryptoServiceProvider())
try {
publicKey =
RSA.ToXmlString(false);
privateKey = RSA.ToXmlString(true);
var byteData = Encoding.Default.GetBytes(Data);
return RSA.Encrypt(byteData, false);
}
finally {
RSA.Clear();
}
}
static byte[]
Decrypt(byte[] EncryptedData, string privateKey)
{
using (var RSA = new RSACryptoServiceProvider())
try {
RSA.FromXmlString(privateKey);
return RSA.Decrypt(EncryptedData, false);
}
finally {
RSA.Clear();
}
}
static void Main(string[] args)
{
var data = "Hello world, this is my
secret data i want encrypted";
string publicKey;
string privateKey;
var encryptedData = Encrypt(data, out publicKey, out
privateKey);
Console.WriteLine($"Public Key\n{publicKey}");
Console.WriteLine($"PrivateKey\n{privateKey}");
var decyptedData = Decrypt(encryptedData, privateKey);
Console.WriteLine(Encoding.Default.GetString(decyptedData));
}
}
}
To Sum up
- Asymmetric Encryption is otherwise known as Public Key Encryption
- One key is used for encryption and the other for decryption
- Commonly used for signatures.
- Cryptography namespace includes 4 asymmetric algorithms:
- DSA
- ECDiffieHellman
- ECDsa
- RSA - the most popular