首页 > 编程语言 >C# Rsa加密(私钥加密、公钥解密、密钥格式转换、支持超大长度分段加密)

C# Rsa加密(私钥加密、公钥解密、密钥格式转换、支持超大长度分段加密)

时间:2024-08-16 11:48:31浏览次数:11  
标签:Convert 公钥 私钥 string offSet BigInteger FromBase64String new 加密

 

    此为工具类,这个和java版本的加密对比过了,结果是一样的,代码赋值黏贴直接用,不多比比,直接上代码(需要在nuget上寻找"Portable.BouncyCastle"包安装):

  (java端有个和c#端不一样的地方,base64编码有好几套,有时候对不上大概率是base64那边的问题)

 

    

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 RSAUtil
{
    /// <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
    }
}

 

标签:Convert,公钥,私钥,string,offSet,BigInteger,FromBase64String,new,加密
From: https://www.cnblogs.com/xuxiaoshuan/p/18362583

相关文章

  • 如何对加密后的数据进行模糊查询(面试题)
    目录前言1.基本知识2.国内做法前言这道题在面试比较常见,但是在算法逻辑层面中,直接对加密数据进行模糊查询是不可行的,因为加密算法会使数据变成不可读的形式需要在加密过程中采取特殊的策略来支持模糊查询以下只是结合网上现有的资料提供一个思路(通过自定义一些......
  • [开题报告]FLASK框架文件加密系统的设计与实现tp835(源码+论文)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着信息技术的飞速发展,文件作为信息交换的重要载体,在日常生活和工作中扮演着不可或缺的角色。然而,这些文件往往包含大量的敏感信息,如个人......
  • 产品说:“用户登陆要使用RSA加密才行”
    问题引入项目上线前夕,产品说:“咱们现在这个登陆是明文传输,客户的安全检测可过不了哦,你得把用户名密码加密一下!加密方案客户要求为RSA2048”。什么是RSA简介RSA算法是一种非对称的加密算法(即:加密、解密的密钥不同),通常是生成两把密钥,分别是私钥和公钥,其中私钥保密,公钥对......
  • Android-代码混淆及字符串加密
    代码混淆使用ProGuard&R8一些参考链接Android混淆,新引入的D8、R8改变了什么?sdk打包必备,proguard混淆规则如何配置开启混淆app/build.gradle.android.buildTypesrelease{minifyEnabledtrue//开启混淆proguardFilesgetDefaultProguardFile('proguard-and......
  • 25.python模块(加密,os,re,json)
    一.加密讲解加密算法:md5\rsa\AES\des\base(一)base64加解密importbase64a=base64.b64encode(b"123456")print(a)#加密#b'MTIzNDU2'b=base64.b64decode(b'MTIzNDU2')print(b)#b'123456'http://encode.chahuo.com/在线加解密hashlib......
  • 一个基于 Java 接口参数加密框架,让接口参数加密变得简单、优雅!
    SecurityApiv1.0.1一个基于Java接口参数加密框架,让接口参数加密变得简单、优雅!文章目录一、SecurityApi介绍二、SecurityApi依赖三、使用1.RSA加密(非对称加密)1.1简单示例1.2生成RSA密钥1.3加签名说明「第一个场景」B要给A传递一条加密消息「第二个场景」B......
  • 数据加密存储:重要文件怎么加密?一文全搞懂!
    数据已成为企业和个人最宝贵的资产之一。然而,随着网络攻击和数据泄露事件的频发,如何保护数据安全成为了每个人都需要面对的重要问题。数据加密存储作为保障数据安全的重要手段之一,其重要性不言而喻。本文将详细介绍数据加密存储的基本概念、常见的加密方式以及如何对重要文......
  • 文件保护软件有哪些?8大文件安全加密管理软件大盘点(合集篇)
    文件安全已成为企业和个人不可忽视的重要问题。为了保护敏感数据不被非法访问、泄露或篡改,各种文件保护软件应运而生。本文将为您盘点八款备受推崇的文件安全加密管理软件,帮助您更好地保护数据安全。1.域智盾软件该软件是一款功能强大的文件保护软件,通过先进的加密技术,对......
  • Windows出现出现身份验证错误。要求的函数不受支持 远程计算机: 10.17.1.2 这可能是由
    Windows出现出现身份验证错误。要求的函数不受支持远程计算机:10.17.1.2这可能是由于CredsSP加密数据库修正。若要了解详细信息,请访问https://go.microsoft.com/fwlink/?linkid=866660解决方案解决方法第一步点开控制面板选择系统与安全第二步选择“允许远程访问......
  • js逆向md5加密算法获取大学排行榜,页码时间戳影响响sign
    importjsonimportrequestsfromhashlibimportmd5defget_md5(s):m=md5()m.update(s.encode())returnm.hexdigest()n="{app_id=98357f659cf8fb6001cff80f7c6b85f2&diploma_id=7&page=4&page_len=20&platform=desktop&ts=1......