非对称加密RSA
说到非对称加密就不得不说对称加密
对称加密:简单来说就是加密和解密是用的同一个密钥(也就是规则),所以说密钥+原文=密文,阿么密文-秘钥=原文,所以描述如其名称,是对称的。
非对称加密:加密和解密的密钥不是同一把,会生成一对密钥,一把叫公钥,一把叫私钥,可以用公钥加密,然后用私钥解密;也可以用私钥加密,用公钥解密,正是因为加密和解密不是同一把,所以是不对称的;一般来讲,公钥是公开给多个外部系统使用的,私钥自己保存。
加密要求不是很高并且数据量大的情况下可以用对称加密,因为其加密和解密速度快。
加密要求高、数据量不大、对速度要求不高的话可以用非对称加密,因为其安全,但是解密速度慢,数据越多,解密速度就越慢。
常见的非对称加密方式RSA的使用步骤(C#):
1.使用RSA生成公钥和私钥
private void CreateRSA_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(content.Text)) { MessageBox.Show("加密内容不能为空!"); return; } using var rsa = new RSACryptoServiceProvider(); var publicKey = rsa.ToXmlString(false); var privateKey = rsa.ToXmlString(true); PrivateKeyText.Text = privateKey; RSAContent.Text = RSAEncrypt(publicKey, content.Text); Console.WriteLine($"publicKey:{publicKey}"); Console.WriteLine($"privateKey:{privateKey}"); }
2.使用公钥对原文进行加密返回密文
private string RSAEncrypt(string publicKey,string content) { using var rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(publicKey); cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherbytes); }
3.使用私钥对密文进行解密返回原文
public static string RSADecrypt(string privateKey,string ciphertext) { using var rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privateKey); cipherbytes = rsa.Decrypt(Convert.FromBase64String(ciphertext), false); return Encoding.UTF8.GetString(cipherbytes); }