C# RSA 实现加密

@zgcwkj  2022年12月05日

分类:

代码 其它 

RSA 实现公钥私钥生成和加密

/// <summary>
/// RSA 工具
/// </summary>
public class RSATool
{
    /// <summary>
    /// 生成公钥与私钥方法
    /// </summary>
    /// <returns></returns>
    public static string[] CreateKey(KeyType keyType)
    {
        try
        {
            var sKeys = new string[2];
            var rsa = new RSACryptoServiceProvider();
            switch (keyType)
            {
                case KeyType.XML:
                    {
                        //私钥
                        sKeys[0] = rsa.ToXmlString(true);
                        //公钥
                        sKeys[1] = rsa.ToXmlString(false);
                    }
                    break;
                case KeyType.PKS8:
                    {
                        sKeys[0] = rsa.ToXmlString(true);
                        //公钥
                        sKeys[1] = rsa.ToXmlString(false);

                        //JAVA私钥
                        sKeys[0] = RSAPrivateKeyDotNet2Java(sKeys[0]);
                        //JAVA公钥
                        sKeys[1] = RSAPublicKeyDotNet2Java(sKeys[1]);
                    }
                    break;
                default:
                    break;
            }
            return sKeys;
        }
        catch (Exception ex)
        {
            var msg = ex.Message;
            return null;
        }
    }

    /// <summary>
    /// 密钥类型
    /// </summary>
    public enum KeyType
    {
        /// <summary>
        /// xml类型
        /// </summary>
        XML,

        /// <summary>
        /// pks8类型
        /// </summary>
        PKS8
    }

    /// <summary>
    /// RSA私钥格式转换,.net -> java
    /// </summary>
    /// <param name="privateKey">.net生成的私钥</param>
    /// <returns></returns>
    public static string RSAPrivateKeyDotNet2Java(string privateKey)
    {
        var doc = new XmlDocument();
        doc.LoadXml(privateKey);
        var m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
        var exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
        var d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
        var p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
        var q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
        var dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
        var dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
        var qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));

        var privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);

        var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
        var serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
        return Convert.ToBase64String(serializedPrivateBytes);

    }

    /// <summary>
    /// RSA公钥格式转换,.net -> java
    /// </summary>
    /// <param name="publicKey">.net生成的公钥</param>
    /// <returns></returns>
    public static string RSAPublicKeyDotNet2Java(string publicKey)
    {
        var doc = new XmlDocument();
        doc.LoadXml(publicKey);
        var m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
        var p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
        var pub = new RsaKeyParameters(false, m, p);

        var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
        var serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
        return Convert.ToBase64String(serializedPublicBytes);
    }

    /// <summary>
    /// RSA私钥格式转换,java -> .net
    /// </summary>
    /// <param name="privateKey">java生成的RSA私钥</param>
    /// <returns></returns>
    public static string RSAPrivateKeyJavaToDotNet(string privateKey)
    {
        var 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>
    /// RSA公钥格式转换,java -> .net
    /// </summary>
    /// <param name="publicKey">java生成的公钥</param>
    /// <returns></returns>
    public static string RSAPublicKeyJavaToDotNet(string publicKey)
    {
        var 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>
    /// 最大加密长度
    /// </summary>
    private const int MAX_ENCRYPT_BLOCK = 117;

    /// <summary>
    /// 最大解密长度
    /// </summary>
    private const int MAX_DECRYPT_BLOCK = 128;

    /// <summary>
    /// 用私钥给数据进行RSA加密
    /// </summary>
    /// <param name="xmlPrivateKey">私钥(XML格式字符串)</param>
    /// <param name="strEncryptString">要加密数据</param>
    /// <returns></returns>
    public static string PrivateKeyEncrypt(string xmlPrivateKey, string strEncryptString)
    {
        //加载私钥
        var privateRsa = new RSACryptoServiceProvider();
        privateRsa.FromXmlString(xmlPrivateKey);

        //转换密钥
        var keyPair = DotNetUtilities.GetKeyPair(privateRsa);
        var c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式
        c.Init(true, keyPair.Private);//第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
        var dataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);//获取字节

        byte[] cache;
        var time = 0;//次数
        var inputLen = dataToEncrypt.Length;
        var offSet = 0;

        var outStream = new MemoryStream();
        while (inputLen - offSet > 0)
        {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK)
            {
                cache = c.DoFinal(dataToEncrypt, offSet, MAX_ENCRYPT_BLOCK);
            }
            else
            {
                cache = c.DoFinal(dataToEncrypt, offSet, inputLen - offSet);
            }
            //写入
            outStream.Write(cache, 0, cache.Length);

            time++;
            offSet = time * MAX_ENCRYPT_BLOCK;
        }

        var resData = outStream.ToArray();

        var strBase64 = Convert.ToBase64String(resData);
        outStream.Close();
        return strBase64;
    }

    /// <summary>
    /// 用公钥给数据进行RSA解密 
    /// </summary>
    /// <param name="xmlPublicKey">公钥(XML格式字符串)</param>
    /// <param name="strDecryptString">要解密数据</param>
    /// <returns> 解密后的数据 </returns>
    public static string PublicKeyDecrypt(string xmlPublicKey, string strDecryptString)
    {
        //加载公钥
        var publicRsa = new RSACryptoServiceProvider();
        publicRsa.FromXmlString(xmlPublicKey);
        var rp = publicRsa.ExportParameters(false);

        //转换密钥
        var pbk = DotNetUtilities.GetRsaPublicKey(rp);

        var c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式
        c.Init(false, pbk);//第一个参数为true表示加密,为false表示解密;第二个参数表示密钥

        var DataToDecrypt = Convert.FromBase64String(strDecryptString);

        byte[] cache;
        var time = 0;//次数
        var inputLen = DataToDecrypt.Length;
        var offSet = 0;
        var outStream = new MemoryStream();
        while (inputLen - offSet > 0)
        {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK)
            {
                cache = c.DoFinal(DataToDecrypt, offSet, MAX_DECRYPT_BLOCK);
            }
            else
            {
                cache = c.DoFinal(DataToDecrypt, offSet, inputLen - offSet);
            }
            //写入
            outStream.Write(cache, 0, cache.Length);

            time++;
            offSet = time * MAX_DECRYPT_BLOCK;
        }
        var resData = outStream.ToArray();

        var strDec = Encoding.UTF8.GetString(resData);
        return strDec;
    }

    /// <summary>
    /// 签名
    /// </summary>
    /// <param name="str">需签名的数据</param>
    /// <param name="privateKey">私钥 Key</param>
    /// <param name="signAlgType">签名算法类型</param>
    /// <returns>签名后的值</returns>
    public static string Sign(string str, string privateKey, SignAlgType signAlgType)
    {
        //根据需要加签时的哈希算法转化成对应的hash字符节
        var bt = Encoding.GetEncoding("utf-8").GetBytes(str);
        byte[] rgbHash;
        switch (signAlgType)
        {
            case SignAlgType.SHA1:
                {
                    var csp = SHA1.Create();
                    rgbHash = csp.ComputeHash(bt);
                }
                break;
            case SignAlgType.SHA256:
                {
                    var csp = SHA256.Create();
                    rgbHash = csp.ComputeHash(bt);
                }
                break;
            case SignAlgType.MD5:
                {
                    var csp = MD5.Create();
                    rgbHash = csp.ComputeHash(bt);
                }
                break;
            default:
                throw new Exception("SignAlgType ???");
        }
        var key = new RSACryptoServiceProvider();
        key.FromXmlString(privateKey);
        var formatter = new RSAPKCS1SignatureFormatter(key);
        formatter.SetHashAlgorithm(signAlgType.ToString());//此处是你需要加签的hash算法,需要和上边你计算的hash值的算法一致,不然会报错
        var inArray = formatter.CreateSignature(rgbHash);
        return Convert.ToBase64String(inArray);
    }

    /// <summary>
    /// 签名验证
    /// </summary>
    /// <param name="str">待验证的字符串</param>
    /// <param name="sign">加签之后的字符串</param>
    /// <param name="publicKey">公钥 Key</param>
    /// <param name="signAlgType">签名算法类型</param>
    /// <returns>签名是否符合</returns>
    public static bool Verify(string str, string sign, string publicKey, SignAlgType signAlgType)
    {
        var bt = Encoding.GetEncoding("utf-8").GetBytes(str);
        byte[] rgbHash;
        switch (signAlgType)
        {
            case SignAlgType.SHA1:
                {
                    var csp = SHA1.Create();
                    rgbHash = csp.ComputeHash(bt);
                }
                break;
            case SignAlgType.SHA256:
                {
                    var csp = SHA256.Create();
                    rgbHash = csp.ComputeHash(bt);
                }
                break;
            case SignAlgType.MD5:
                {
                    var csp = MD5.Create();
                    rgbHash = csp.ComputeHash(bt);
                }
                break;
            default:
                throw new Exception("SignAlgType ???");
        }
        var key = new RSACryptoServiceProvider();
        key.FromXmlString(publicKey);
        var deformatter = new RSAPKCS1SignatureDeformatter(key);
        deformatter.SetHashAlgorithm(signAlgType.ToString());
        var rgbSignature = Convert.FromBase64String(sign);
        if (deformatter.VerifySignature(rgbHash, rgbSignature))
            return true;
        return false;
    }

    /// <summary>
    /// 签名算法类型
    /// </summary>
    public enum SignAlgType
    {
        /// <summary>
        /// SHA1
        /// </summary>
        SHA1,

        /// <summary>
        /// sha256
        /// </summary>
        SHA256,

        /// <summary>
        /// md5
        /// </summary>
        MD5
    }


评论已关闭

Top