• C#使用BouncyCastle来实现私钥加密公钥解密的方法与java互通的RSA加解密和签名(转)


    因为C#的RSA加密解密只有公钥加密,私钥解密,没有私钥加密,公钥解密。在网上查了很久也没有很好的实现。BouncyCastle的文档少之又少。很多人可能会说,C#也是可以的,通过Biginteger开源类来实现,不过那个是有一个文章,不过他加密出来的是16进制结果的。根本不能和JAVA互通。连加密出来的都不和C#原生的加密出来的结果格式一样。所以还是没有好的解决方法。

    接下来还是不断的找资料,找方法。找朋友找同事。个个都找。问题是有的,方法也是有的,所以总结各路大神之后写了这个类。实现了私钥加密,公钥解密。并通过在线的校验之后,发布上来。大家可以做一个DEMO,然后进去在线RSA加密解密校验。

    在线RSA,DES等加密解密地址:
    https://the-x.cn/cryptography/Rsa.aspx

    http://tool.chacuo.net/cryptrsapubkey

    可以直接nuget搜索BouncyCastle,安装即可

    下面是代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using Org.BouncyCastle.Asn1.Pkcs;
    using Org.BouncyCastle.Asn1.X509;
    using Org.BouncyCastle.Crypto.Generators;
    using Org.BouncyCastle.Crypto.Parameters;
    using Org.BouncyCastle.Math;
    using Org.BouncyCastle.Pkcs;
    using Org.BouncyCastle.Security;
    using Org.BouncyCastle.Crypto.Engines;
    using Org.BouncyCastle.X509;
    using Org.BouncyCastle.Crypto;
    using Org.BouncyCastle.Asn1;
    using Org.BouncyCastle.Crypto.Encodings;
    using System.IO;
    namespace Tool
    {
        public class RSATool
        {
    
            public RSATool()
            {
    
            }
            /// <summary>
            /// KEY 结构体
            /// </summary>
            public struct RSAKEY
            {
                /// <summary>
                /// 公钥
                /// </summary>
                public string PublicKey
                {
                    get;
                    set;
                }
                /// <summary>
                /// 私钥
                /// </summary>
                public string PrivateKey
                {
                    get;
                    set;
                }
            }
            public RSAKEY GetKey()
            {
                //RSA密钥对的构造器  
                RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
    
                //RSA密钥构造器的参数  
                RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                    Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                    new Org.BouncyCastle.Security.SecureRandom(),
                    1024,   //密钥长度  
                    25);
                //用参数初始化密钥构造器  
                keyGenerator.Init(param);
                //产生密钥对  
                AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
                //获取公钥和密钥  
                AsymmetricKeyParameter publicKey = keyPair.Public;
                AsymmetricKeyParameter privateKey = keyPair.Private;
    
                SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
                PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
    
    
                Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
    
                byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
                Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
                byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");
    
                RSAKEY item = new RSAKEY()
                {
                    PublicKey = Convert.ToBase64String(publicInfoByte),
                    PrivateKey = Convert.ToBase64String(privateInfoByte)
                };
                return item;
            }
            private AsymmetricKeyParameter GetPublicKeyParameter(string s)
            {
                s = s.Replace("
    ", "").Replace("
    ", "").Replace(" ", "");
                byte[] publicInfoByte = Convert.FromBase64String(s);
                Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入   
                AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
                return pubKey;
            }
            private AsymmetricKeyParameter GetPrivateKeyParameter(string s)
            {
                s = s.Replace("
    ", "").Replace("
    ", "").Replace(" ", "");
                byte[] privateInfoByte = Convert.FromBase64String(s);
                // Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入   
                // PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
                AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
                return priKey;
            }
            public string EncryptByKey(string s, string key, bool isPublic)
            {
                //非对称加密算法,加解密用  
                IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
                //加密  
                try
                {
                    engine.Init(true, isPublic ? GetPublicKeyParameter(key) : GetPrivateKeyParameter(key));
                    byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);
    
                    int inputLen = byteData.Length;
                    MemoryStream ms = new MemoryStream();
                    int offSet = 0;
                    byte[] cache;
                    int i = 0;
                    // 对数据分段加密
                    while (inputLen - offSet > 0)
                    {
                        if (inputLen - offSet > 117)
                        {
                            cache = engine.ProcessBlock(byteData, offSet, 117);
                        }
                        else
                        {
                            cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet);
                        }
                        ms.Write(cache, 0, cache.Length);
                        i++;
                        offSet = i * 117;
                    }
                    byte[] encryptedData = ms.ToArray();
    
                    //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                    return Convert.ToBase64String(encryptedData);
                    //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
                }
                catch (Exception ex)
                {
                    return ex.Message;
    
                }
            }
            /// <summary>
            /// 解密
            /// </summary>
            /// <param name="s"></param>
            /// <param name="key"></param>
            /// <param name="isPublic"></param>
            /// <returns></returns>
            public string DecryptByPublicKey(string s, string key, bool isPublic)
            {
                s = s.Replace("
    ", "").Replace("
    ", "").Replace(" ", "");
                //非对称加密算法,加解密用  
                IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
    
    
                //加密  
    
                try
                {
                    engine.Init(false, isPublic ? GetPublicKeyParameter(key) : GetPrivateKeyParameter(key));
                    byte[] byteData = Convert.FromBase64String(s);
    
                    int inputLen = byteData.Length;
                    MemoryStream ms = new MemoryStream();
                    int offSet = 0;
                    byte[] cache;
                    int i = 0;
                    // 对数据分段加密
                    while (inputLen - offSet > 0)
                    {
                        if (inputLen - offSet > 128)
                        {
                            cache = engine.ProcessBlock(byteData, offSet, 128);
                        }
                        else
                        {
                            cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet);
                        }
                        ms.Write(cache, 0, cache.Length);
                        i++;
                        offSet = i * 128;
                    }
                    byte[] encryptedData = ms.ToArray();
    
                    //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                    return Encoding.UTF8.GetString(ms.ToArray());
                    //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
                }
                catch (Exception ex)
                {
                    return ex.Message;
    
                }
            }
            /// <summary>
            /// 签名
            /// </summary>
            /// <param name="data">数据</param>
            /// <param name="key">密匙</param>
            /// <returns></returns>
            public string SignByPrivateKey(string data, string key)
            {
                AsymmetricKeyParameter priKey = GetPrivateKeyParameter(key);
                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(data);
    
                ISigner normalSig = SignerUtilities.GetSigner("SHA1WithRSA");
                normalSig.Init(true, priKey);
                normalSig.BlockUpdate(byteData, 0, data.Length);
                byte[] normalResult = normalSig.GenerateSignature(); //签名结果
                return Convert.ToBase64String(normalResult);
                //return System.Text.Encoding.UTF8.GetString(normalResult);
            }
    
            /// <summary>
            /// 验签
            /// </summary>
            /// <param name="plainData">验证数据</param>
            /// <param name="sign">签名</param>
            /// <param name="key">公匙</param>
            /// <returns></returns>
            public bool ValidationPublicKey(string plainData, string sign, string key)
            {
                AsymmetricKeyParameter priKey = GetPublicKeyParameter(key);
    
                byte[] signBytes = Convert.FromBase64String(sign);
                byte[] plainBytes = Encoding.UTF8.GetBytes(plainData);
    
    
                ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA");
                verifier.Init(false, priKey);
                verifier.BlockUpdate(plainBytes, 0, plainBytes.Length);
    
                return verifier.VerifySignature(signBytes); //验签结果
            }
        }
    }

    转https://www.cnblogs.com/AnAng/p/10396296.html

  • 相关阅读:
    算法时间测试
    HDU1164
    git 中 HEAD detached from 802e836
    mysql中的substring()截取字符函数
    git分支/标签操作
    git简介、基本命令和仓库操作
    markdown编辑器学习
    数据库的三范式
    switch语句能否作用在byte,long,string上
    Spring的优缺点
  • 原文地址:https://www.cnblogs.com/DoNetCShap/p/14301985.html
Copyright © 2020-2023  润新知