首页 > 编程语言 >c# RSA相关 加密 签名 PEM - XML互相转换

c# RSA相关 加密 签名 PEM - XML互相转换

时间:2023-10-17 23:11:47浏览次数:36  
标签:XML Convert string c# BigInteger RSA FromBase64String offSet new

安装nuget Portable.BouncyCastle

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;

public class RSAHelper
{
    /// <summary>
    /// 生成公钥与私钥方法
    /// </summary>
    /// <returns></returns>
    public static string[] CreateKey(KeyType keyType, KeySize keySize)
    {
        try
        {
            string[] sKeys = new string[2];
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider((int)keySize);
            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)
        {
            return null;
        }
    }

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

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

    /// <summary>
    /// 密钥尺寸(一般都是1024位的)
    /// </summary>
    public enum KeySize
    {
        SMALL = 1024,
        BIG = 2048
    }


    /// <summary>
    /// RSA私钥格式转换,.net->java
    /// </summary>
    /// <param name="privateKey">.net生成的私钥</param>
    /// <returns></returns>
    public static string RSAPrivateKeyDotNet2Java(string privateKey)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(privateKey);
        BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
        BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
        BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
        BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
        BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
        BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
        BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
        BigInteger qinv = new 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>
    /// RSA公钥格式转换,.net->java
    /// </summary>
    /// <param name="publicKey">.net生成的公钥</param>
    /// <returns></returns>
    public static string RSAPublicKeyDotNet2Java(string publicKey)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(publicKey);
        BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
        BigInteger p = new 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>
    /// RSA私钥格式转换,java->.net
    /// </summary>
    /// <param name="privateKey">java生成的RSA私钥</param>
    /// <returns></returns>
    public static string RSAPrivateKeyJavaToDotNet(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>
    /// RSA公钥格式转换,java->.net
    /// </summary>
    /// <param name="publicKey">java生成的公钥</param>
    /// <returns></returns>
    public static string RSAPublicKeyJavaToDotNet(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>
    /// 最大加密长度
    /// </summary>
    private const int MAX_ENCRYPT_BLOCK = 245;

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


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

        //转换密钥
        AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);
        IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式

        c.Init(true, keyPair.Private);//第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
        byte[] dataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);//获取字节

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

        MemoryStream 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;
        }

        byte[] resData = outStream.ToArray();

        string 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)
    {
        //加载公钥
        RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();
        publicRsa.FromXmlString(xmlPublicKey);
        RSAParameters rp = publicRsa.ExportParameters(false);

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

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

        byte[] DataToDecrypt = Convert.FromBase64String(strDecryptString);

        byte[] cache;
        int time = 0;//次数
        int inputLen = DataToDecrypt.Length;
        int offSet = 0;
        MemoryStream 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;
        }
        byte[] resData = outStream.ToArray();

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

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

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

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

        /// <summary>
        /// md5
        /// </summary>
        MD5,

        /// <summary>
        /// sha1
        /// </summary>
        SHA1
    }
}

使用方式如下

 var pubkeyPEM = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMII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lh/VXbYnLtR6IIvKkOQfmn7HIfMTRDhazGfECgYEA+tfPX0yUr+8D+FTIyHDlqhKZ4lubGXY1+elyJXOfEZeCirLIM+9SyodSEiht1ci+14pawZl5Vf46IreErXkhB+7NbDVYKLrTKFAyOLncSsE/+qnoruwItqlnNntXd+fFrZ9jvc+ceX5n59q3v1npbgKqpytkWmsjKCPWbhP4DdkCgYEA4gnKpKqTk193+7Dcnecm8bHLp7brZJpfwFzxbt3uBVbNlWTci82wcp3+13fd9rgn28eCKm88/p4BBqfuuVBihas64qtBrdTU5d5CdYoOcB8qbuhEXlbeTq30k2fHjd0U4K0pRrWvTfMKKY0hrZJnuXtjcl1gZ/5F+lemU2kJN98CgYBPsUKTv0u5vVDgk2caryt35eL31CypYTHyzOTT2zDdMOprUDNktJLz/xvm4utKMTXYWn9M5Ip09IjZwL4pMsN4triSuTvh7MDrHNdnyDyhj1XZOCPRdvGpvpYo6/S1BnB6IZpZklzfCHbQZV9dLp6Hsdcvtwxx4XnQ5dnZLQTwuQKBgHqU3s2AJ/oTGwlmt632TltilVRF0dBEG8tBXDlIp61DjsgG48f5a0gtQKfvPHNxGUSKJKAIpWZbn6jRZ5gd7OAapRuJzluMAU0LxLTjgsLxU9zDn1gd+f9nPSy3ajQYAht6LNlI7GH0fL1d6TatIA0pyhuaYg7jiWWjJPM1Eie3AoGBANnRUrlV/ZJ5TYw7bd3rRcpFbyoT9sOrVI7PYF50GFKjNiVtKlUcTLynnuq7wTs/X9rys0rrYE6WUBUXQ1k//cXxbu6BO8NvgYLr0RJsvDHy+mUZfQxDrdG4zdtNB+bNEAH24FzLJlVn+ZYp9A2iXNVMSA9bgukqXJRgaXaqGSjr";

            var xmlPrivateKey = RSAHelper.RSAPrivateKeyJavaToDotNet(privatekeyPEM);
            var xmlPublicKey = RSAHelper.RSAPublicKeyJavaToDotNet(pubkeyPEM);

            var secret = RSAHelper.PrivateKeyEncrypt(xmlPrivateKey, "test");
            var raw = RSAHelper.PublicKeyDecrypt(xmlPublicKey, secret);

            var auth = RSAHelper.Sign(secret, xmlPrivateKey, RSAHelper.SignAlgType.MD5);
            var authRaw = RSAHelper.Verify(secret, auth, xmlPublicKey, RSAHelper.SignAlgType.MD5);

标签:XML,Convert,string,c#,BigInteger,RSA,FromBase64String,offSet,new
From: https://www.cnblogs.com/ives/p/17770977.html

相关文章

  • python报错解决-ValueError: Trusted host URL must include a host part: '#!
    删掉#后面的字符参考:pipinstall总是报错:ValueError:TrustedhostURLmustincludeahostpart:‘#‘-CSDN博客......
  • 【C语言】数组指针
    【C语言】数组指针顾名思义,数组指针是指向数组的指针。例如,p是一个指向含有3个int元素的一维数组的指针:int(*p)[3];//圆括号的优先级更高,让p先与*结合再与[]结合用法:#include<stdio.h>//voiddisplay1(intp[][3])//等价下行写法voiddisplay......
  • hackthebox agile medium
    信息收集portscanningsudonmap--sT--min-rate10000-p-10.10.11.203-oAnmap/agilesudonmap-sT-sC-sV-pxx10.10.11.203-oAnmap/detialbannertellsusit'sanubuntuserverwealsoaddthatdomainto/etc/hostsfile->10.10.11.203superp......
  • Docker下Redis安装
    Redis是一个开源的使用ansic语言编写、遵守bsd协议、支持网络、可基于内存、分布式、可选持久性的键值对(key-value)存储数据库准备工作安装源:DockerHub默认配置文件:配置文件示例创建文件目录C:\docker\redis\dataredis.conf#不限制IP访问,局域网能够访......
  • ModuleNotFoundError: No module named 'conda.auxlib'
    [~/software]$condaTraceback(mostrecentcalllast): File"/ppp/software/Anaconda3.8/bin/conda",line15,in<module>   sys.exit(main()) File"/ppp/software/Anaconda3.8/lib/python3.8/site-packages/conda/cli/main.py",line11......
  • m基于FPGA的GFDM调制解调系统verilog实现,包含testbench仿真测试文件
    1.算法仿真效果本系统进行了Vivado2019.2平台的开发,测试结果如下:   GFDM调制信号放大:   GFDM解调信号放大:   系统RTL结构图如下:   2.算法涉及理论知识概要        随着通信技术的不断发展,人们对数据传输速率和频谱效率的要求越来越高。......
  • Leetcode24. 两两交换链表中的节点
    题目描述给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。示例提交的代码classSolution{ListNodenextNode;publicListNodeswapPairs(ListNodehead){//特殊化处理......
  • Mac电脑80端口被占用的2种解决办法
    前提:确认占用80端口的程序(sudolsof-i:80)我研发用的是Mac电脑,查看80端口被占用的进程命令:sudolsof-i:80我Mac电脑80端口占用进程如下:httpd进程占用了80端口,httpd进程即为Apache服务,下面提供了2种解决办法。OXL-MacBook:~obullxl$sudolsof-i:80COMMANDPIDUSERF......
  • Codeforces Round 888 (Div. 3) C. Tiles Comeback
    有\(n\)块瓷砖和一个正整数\(k\),第\(i\)块瓷砖染色为\(c_i\)。一开始站在第\(1\)块瓷砖往,然后可以开始往右跳吗,到第\(n\)块瓷砖停止。你可以得到的路径长度\(p\)为你从\(1\)到\(n\)踩过瓷砖的数量。你需要确定是否存在一条长度为\(p\)的路径满足。\(k\mid......
  • asisctf 2023 pwn nightjs 复现记录
    关于赛题asisctf2023nightjs附件一道js引擎题目,基于serenityOS上做的改编。(感觉serenity作者很强迫症善良得写了很多注释,连一行赋值语句都有注释,读起来超级愉悦)。偷看了别人的wp来复现。给了patch文件之后,查看修改处的函数被什么函数引用,漏洞点就很明了了。攻击流......