RSA 简介及 C# 和 js 实现【加密知多少系列_4】

〇、简介

谈及 RSA 加密算法,我们就需要先了解下这两个专业名词,对称加密和非对称加密。

  • 对称加密:在同一密钥的加持下,发送方将未加密的原文,通过算法加密成密文;相对的接收方通过算法将密文解密出来原文的过程,就是对称加密算法。

  

  • 非对称加密:发送发和接收方通过不同的密钥加解密的过程就是非对称加密。发送方通过公钥加密后的密文,接收方通过私钥解密密文成明文。公钥就是公开的,让全部发送方使用,私钥是保密的,不能公开,专门供接收方解密收到的密文,没有私钥的第三方就无法解密密文,从而保证了数据传输的安全性。

  

非对称加密的代表算法是 RSA 算法,其是目前最有影响力的公钥加密算法,并且被普遍认为是目前最优秀的公钥方案之一。本文也将做专门介绍。

RSA 公钥加密算法是 1977 年由 Ron Rivest、Adi Shamirh 和 Len Adleman 在美国麻省理工学院开发的,RSA 取名来自开发他们三者的名字。

RSA 是第一个能同时用于加密和数字签名的算法,它能够抵抗到目前为止已知的所有密码攻击,已被 ISO 推荐为公钥数据加密标准

RSA 公开密钥密码体制的原理是:根据数论,寻求两个大素数比较简单,而将它们的乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。

强大的加密算法也存在一些缺点:

  • 产生密钥很麻烦,受到素数产生技术的限制,因而难以做到一次一密(密钥只能使用一次,永远不对其它消息重复使用)。
  • 分组长度太大,为保证安全性,n 至少也要 600bits 以上,使运算代价很高,尤其是速度较慢,较对称密码算法慢几个数量级;且随着大数分解技术的发展,这个长度还在增加,不利于数据格式的标准化。目前,SET(Secure Electronic Transaction) 协议中要求 CA 采用 2048bits 长的密钥,其他实体使用 1024bits 的密钥。
  • RSA 密钥长度随着保密级别提高,增加很快。

同样的明文经 RSA 公钥加密后的结果,每次都不同。下面简单说明一下:

不管是使用RSA私钥进行签名还是公钥进行加密,操作中都需要对待处理的数据先进行填充,然后再对填充后的数据进行加密处理。

  EB = 00 || BT || PS || 00 || D

  • D: data (指待处理数据,即填充前的原始数据)
  • PS: padding string (填充字符串)
  • BT: block type (数据块类型)
  • EB: encryption block (待加密的数据块,经过填充后结果)
  • ||: 表示连接操作 (X||Y 表示将 X 和 Y 的内容连接到一起)

  "填充后数据" = "00" + "数据块类型" + "填充字符串" + "00" + "原始数据"

对私钥处理的数据,BT 取值为 00 或 01:

  • BT 取值为 00 时,PS 为全 00 的字符串;
  • BT 取值为 01 时,PS 为全 FF 的字符串,通过填充得到的整数会足够大,可以阻止某些攻击,因此也是推荐的填充方式。

针对公钥处理的数据,BT 取值为 02:

  • 使用伪随机的 16 进制字符串填充 PS,而且每次操作进行填充的伪随机书都是独立的。

可见,针对公钥处理的数据,其填充内容为伪随机(限制范围的随机数)的 16 进制字符串,每次操作的填充内容都不一样。因此每次使用公钥加密数据得到的结果就不一样了。

  参考:为什么RSA公钥每次加密得到的结果都不一样?通俗易懂的对称加密与非对称加密原理浅析

一、C# 语言实现

首先需要安装一个包: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);
    }
}

  参考:C#的秘钥跟JAVA的密钥区别

二、js 语言实现

 本示例采用引入开源的 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;
}
posted @ 2023-03-21 15:41  橙子家  阅读(585)  评论(0编辑  收藏  举报