談及 RSA 加密演演算法,我們就需要先了解下這兩個專業名詞,對稱加密和非對稱加密。
非對稱加密的代表演演算法是 RSA 演演算法,其是目前最有影響力的公鑰加密演演算法,並且被普遍認為是目前最優秀的公鑰方案之一。本文也將做專門介紹。
RSA 公鑰加密演演算法是 1977 年由 Ron Rivest、Adi Shamirh 和 Len Adleman 在美國麻省理工學院開發的,RSA 取名來自開發他們三者的名字。
RSA 是第一個能同時用於加密和數位簽章的演演算法,它能夠抵抗到目前為止已知的所有密碼攻擊,已被 ISO 推薦為公鑰資料加密標準。
RSA 公開金鑰密碼體制的原理是:根據數論,尋求兩個大素數比較簡單,而將它們的乘積進行因式分解卻極其困難,因此可以將乘積公開作為加密金鑰。
強大的加密演演算法也存在一些缺點:
同樣的明文經 RSA 公鑰加密後的結果,每次都不同。下面簡單說明一下:
不管是使用RSA私鑰進行簽名還是公鑰進行加密,操作中都需要對待處理的資料先進行填充,然後再對填充後的資料進行加密處理。
EB = 00 || BT || PS || 00 || D
"填充後資料" = "00" + "資料塊型別" + "填充字串" + "00" + "原始資料"
對私鑰處理的資料,BT 取值為 00 或 01:
針對公鑰處理的資料,BT 取值為 02:
可見,針對公鑰處理的資料,其填充內容為偽隨機(限制範圍的亂數)的 16 進位制字串,每次操作的填充內容都不一樣。因此每次使用公鑰加密資料得到的結果就不一樣了。
參考:為什麼RSA公鑰每次加密得到的結果都不一樣? 通俗易懂的對稱加密與非對稱加密原理淺析
首先需要安裝一個包:BouncyCastle.NetCore。
注意:檢驗密文是的選項可參考以下值,Hash:SHA-256;MGFHash:SHA-256;填充模式:ENCRYPTION_PKCS1。
// 測試
RsaSecretKey rSASecretKey = SecurityRSA.GenerateRsaSecretKey(1024);
// 金鑰範例:(每次結果都不同)
// MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAL8xl2yVjjt0DRzJMhq7WZrOP+8Vivuf+Ut3AxuhKoiD6yQGrgzLLQz7tQ30WuucDgzAIDnhFCyxkydMkrpGpd1sN/d8F2n8VE4zj9Tus2eFYQZeKSvw1fKDWiuy2j2yNOHjyKUtALeX4UNViizRRgK407v84orQk8607UfzfrGtAgMBAAECgYBBt0vy2JzgtozjPgxov8iWuxmilecFggDv/WImFwlFjwI9icY9Q4Cim8mpmDnADg2OOGNbQY/rpMWNlnZAbJQJo+TG/J2n3klWzC5KM5O289faw/EguSl3MChqvunvZZqMfSAcqpAxjj4aZHyWDBhsgJZtZNbKBdn5t2JnGdbVSQJBAP3/P6s/g83jhvahNML2sr+fKBMIq6++1UdX0ZI0GusoT/dLWdSGz0T8i4YvIsHC8a//OVBBUsZr9Vdj6C57EX8CQQDAs49RsDsk5zsj30GeVtPTYr1FJn50keqkrptp5dHd0xBZCaZqCUKCOD2txfl7srNJk0cQUX9bXhA36xTxJ7rTAkAwAeWj1X5xFNc2mGOjkgNZCpkFd/cTYatoL6YRzz1jQxxSLnDNJanZbS5l71TPcKxDyqanj6E4lcEqglypJGO7AkBsDUMzvumrC61xs+ILcwxb32XZvHfzzU4RAYdLnf5Lr+newzZ5BrAwbHDJW9VEszMs8lRKpigPh3L4p+yaPHjZAkACSoguX4h81aZWQz5jMxEWsGrydqz5H5+NCPI0uuaZBGLc9mFclhLgKfXC2eh24lKkvxWmjuM10lA+Bl/GDeWH
// MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/MZdslY47dA0cyTIau1mazj/vFYr7n/lLdwMboSqIg+skBq4Myy0M+7UN9FrrnA4MwCA54RQssZMnTJK6RqXdbDf3fBdp/FROM4/U7rNnhWEGXikr8NXyg1orsto9sjTh48ilLQC3l+FDVYos0UYCuNO7/OKK0JPOtO1H836xrQIDAQAB
string jiamih = SecurityRSA.RsaEncrypt(rSASecretKey.PublicKey, "TestString測試");
// 加密後 Base64 編碼結果範例:(每次結果都不同)
// Mync8QBZFLx30wYAOjsiO2+GYdI0pVABDPJ7S/eBSt6+PNVkmSGudEXIDUWBWu4kWwpbTeKpolQCOR+O060eZWD6bFCRovX4AHQAodqGyT/9Q1b0u2YgWhyV1NeaJebm+3QZp9HjMHFzRjoBiGv/v3CEF2I/1SiKz0yfpLGwlwg=
string jiemih = SecurityRSA.RsaDecrypt(rSASecretKey.PrivateKey, jiamih);
/// <summary>
/// RSA 金鑰生成及加解密
/// </summary>
public class SecurityRSA
{
/// <summary>
/// RSA 加密
/// </summary>
/// <param name="xmlpublickey"></param>
/// <param name="content"></param>
/// <returns></returns>
public static string RsaEncrypt(string xmlpublickey, string content)
{
string encryptedcontent = string.Empty;
using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider())
{
rSACryptoServiceProvider.FromXmlString(RSAPublicKeyBase64ToXml(xmlpublickey));
byte[] encrypteddata = rSACryptoServiceProvider.Encrypt(Encoding.Default.GetBytes(content), false);
encryptedcontent = Convert.ToBase64String(encrypteddata);
}
return encryptedcontent;
}
/// <summary>
/// RSA 解密
/// </summary>
/// <param name="xmlprivatekey"></param>
/// <param name="content"></param>
/// <returns></returns>
public static string RsaDecrypt(string xmlprivatekey, string content)
{
string decryptedcontent = string.Empty;
using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider())
{
rSACryptoServiceProvider.FromXmlString(RSAPrivateKeyBase64ToXml(xmlprivatekey));
byte[] decryptedData = rSACryptoServiceProvider.Decrypt(Convert.FromBase64String(content), false);
decryptedcontent = Encoding.GetEncoding("UTF-8").GetString(decryptedData);
}
return decryptedcontent;
}
/// <summary>
/// 生成 RSA 公鑰和私鑰
/// </summary>
/// <param name="keysize">目前 SET(Secure Electronic Transaction)協定中要求 CA 採用 2048bits 長的金鑰,其他實體使用 1024bits 的金鑰</param>
/// <returns></returns>
public static RsaSecretKey GenerateRsaSecretKey(int keysize)
{
RsaSecretKey rSASecretKey = new RsaSecretKey();
using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(keysize))
{
rSASecretKey.PrivateKey = RSAPrivateKeyXmlToBase64(rSACryptoServiceProvider.ToXmlString(true));
rSASecretKey.PublicKey = RSAPublicKeyXmlToBase64(rSACryptoServiceProvider.ToXmlString(false));
}
return rSASecretKey;
}
/// <summary>
/// XML 字串轉 Base64 編碼的字串(公鑰)
/// </summary>
/// <param name="publicKey"></param>
/// <returns></returns>
public static string RSAPublicKeyXmlToBase64(string publicKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(publicKey);
Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
return Convert.ToBase64String(serializedPublicBytes);
}
/// <summary>
/// XML 字串轉 Base64 編碼的字串(私鑰)
/// </summary>
/// <param name="privateKey"></param>
/// <returns></returns>
public static string RSAPrivateKeyXmlToBase64(string privateKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(privateKey);
Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
Org.BouncyCastle.Math.BigInteger exp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
Org.BouncyCastle.Math.BigInteger q = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
Org.BouncyCastle.Math.BigInteger dp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
Org.BouncyCastle.Math.BigInteger dq = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
Org.BouncyCastle.Math.BigInteger qinv = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
return Convert.ToBase64String(serializedPrivateBytes);
}
/// <summary>
/// Base64 編碼字串轉 XML 字串(私鑰)
/// </summary>
/// <param name="privateKey"></param>
/// <returns></returns>
public static string RSAPrivateKeyBase64ToXml(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
}
/// <summary>
/// Base64 編碼字串轉 XML 字串(公鑰)
/// </summary>
/// <param name="publicKey"></param>
/// <returns></returns>
public static string RSAPublicKeyBase64ToXml(string publicKey)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
}
}
/// <summary>
/// RSA 金鑰類
/// </summary>
public class RsaSecretKey
{
public RsaSecretKey(string privatekey = "", string publickey = "")
{
PrivateKey = privatekey;
PublicKey = publickey;
}
public string PublicKey { get; set; }
public string PrivateKey { get; set; }
public override string ToString()
{
return string.Format(
"PrivateKey: {0}\r\nPublicKey: {1}", PrivateKey, PublicKey);
}
}
本範例採用引入開源的 js 庫:JSEncrypt,來實現 RSA 的加解密。另外暫不建議在前端生成金鑰,本範例也無範例。
// 先引入 js 庫
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.3.2/jsencrypt.min.js"></script>
// npm 方式引入
npm install encryptjs --save-dev
// 呼叫方法 message() 檢視測試結果
function message() {
var publickey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/MZdslY47dA0cyTIau1mazj/vFYr7n/lLdwMboSqIg+skBq4Myy0M+7UN9FrrnA4MwCA54RQssZMnTJK6RqXdbDf3fBdp/FROM4/U7rNnhWEGXikr8NXyg1orsto9sjTh48ilLQC3l+FDVYos0UYCuNO7/OKK0JPOtO1H836xrQIDAQAB';//這個是公鑰,建議後端生成
var data_en = RsaEncrypt(publickey, "TestString測試");
console.log(data_en); // 輸出結果:elHQslM7RM9aewSZHetgAJ4X7VNGcpCa9/xFiKv33+QTXy6Utc6Ca4B502ZO2J3zmmSYzk+YOkh8I8NgQFu+s8rYIy1hQjnCaCJI1xWC47vdEfZN79AbX/bmYb0eyjpCaIptIlrIKRPyPDl/H3D/FtNsqVhIEr7mG9a8u+odnus=
var privatekey = 'MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAL8xl2yVjjt0DRzJMhq7WZrOP+8Vivuf+Ut3AxuhKoiD6yQGrgzLLQz7tQ30WuucDgzAIDnhFCyxkydMkrpGpd1sN/d8F2n8VE4zj9Tus2eFYQZeKSvw1fKDWiuy2j2yNOHjyKUtALeX4UNViizRRgK407v84orQk8607UfzfrGtAgMBAAECgYBBt0vy2JzgtozjPgxov8iWuxmilecFggDv/WImFwlFjwI9icY9Q4Cim8mpmDnADg2OOGNbQY/rpMWNlnZAbJQJo+TG/J2n3klWzC5KM5O289faw/EguSl3MChqvunvZZqMfSAcqpAxjj4aZHyWDBhsgJZtZNbKBdn5t2JnGdbVSQJBAP3/P6s/g83jhvahNML2sr+fKBMIq6++1UdX0ZI0GusoT/dLWdSGz0T8i4YvIsHC8a//OVBBUsZr9Vdj6C57EX8CQQDAs49RsDsk5zsj30GeVtPTYr1FJn50keqkrptp5dHd0xBZCaZqCUKCOD2txfl7srNJk0cQUX9bXhA36xTxJ7rTAkAwAeWj1X5xFNc2mGOjkgNZCpkFd/cTYatoL6YRzz1jQxxSLnDNJanZbS5l71TPcKxDyqanj6E4lcEqglypJGO7AkBsDUMzvumrC61xs+ILcwxb32XZvHfzzU4RAYdLnf5Lr+newzZ5BrAwbHDJW9VEszMs8lRKpigPh3L4p+yaPHjZAkACSoguX4h81aZWQz5jMxEWsGrydqz5H5+NCPI0uuaZBGLc9mFclhLgKfXC2eh24lKkvxWmjuM10lA+Bl/GDeWH';//這個是私鑰,建議後端生成
var data_de = RsaDecrypt(privatekey, data_en);
console.log(data_de);
}
// 加密
function RsaEncrypt(publickey, encrypt_content) {
var encryptpk = new JSEncrypt();
encryptpk.setPublicKey(publickey);
let result = encryptpk.encrypt(encrypt_content)
console.log("RsaEncrypt:", result)
return result;
}
// 解密
function RsaDecrypt(privatekey, decrypt_content) {
var encryptpk = new JSEncrypt();
encryptpk.setPrivateKey(privatekey);
let result = encryptpk.decrypt(decrypt_content)
console.log("RsaDecrypt:", result)
return result;
}
本文來自部落格園,作者:橙子家,微訊號:zfy1070491745,有任何疑問歡迎溝通,一起成長。
轉載本文請註明原文連結:https://www.cnblogs.com/czzj/p/JMZDS_RSA.html