博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法...
阅读量:4313 次
发布时间:2019-06-06

本文共 5450 字,大约阅读时间需要 18 分钟。

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

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

在线RSA,DES等加密解密地址:

http://tool.chacuo.net/cryptrsapubkey

下面直接粘贴代码,不多说:

BouncyCastle相关DLL,估计不用我多说,大家可以百度下载。然后引用就可以了!
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;namespace CryptionUtils{    public class RSAForJava    {        public RSAForJava()        {                     }        ///         /// KEY 结构体        ///         public struct RSAKEY        {            ///             /// 公钥            ///             public string PublicKey            {                get;                set;            }            ///             /// 私钥            ///             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("\r", "").Replace("\n", "").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("\r", "").Replace("\n", "").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 EncryptByPrivateKey(string s,string key)        {            //非对称加密算法,加解密用              IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());                                //加密                          try            {                engine.Init(true, GetPrivateKeyParameter(key));                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);                return Convert.ToBase64String(ResultData);                //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);            }            catch (Exception ex)            {                return ex.Message;                            }          }        public string DecryptByPublicKey(string s,string key)        {            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");            //非对称加密算法,加解密用              IAsymmetricBlockCipher engine = new Pkcs1Encoding( new RsaEngine());                          //解密                          try            {                engine.Init(false, GetPublicKeyParameter(key));                byte[] byteData = Convert.FromBase64String(s);                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);                return System.Text.Encoding.UTF8.GetString(ResultData);                            }            catch (Exception ex)            {                return ex.Message;                             }          }    }}

 

转载于:https://www.cnblogs.com/lhxsoft/p/10801158.html

你可能感兴趣的文章
第五天站立会议内容
查看>>
CentOs7安装rabbitmq
查看>>
(转))iOS App上架AppStore 会遇到的坑
查看>>
解决vmware与主机无法连通的问题
查看>>
做好产品
查看>>
项目管理经验
查看>>
笔记:Hadoop权威指南 第8章 MapReduce 的特性
查看>>
JMeter响应数据出现乱码的处理-三种解决方式
查看>>
获取设备实际宽度
查看>>
Notes on <High Performance MySQL> -- Ch3: Schema Optimization and Indexing
查看>>
Alpha冲刺(10/10)
查看>>
数组Array的API2
查看>>
为什么 Redis 重启后没有正确恢复之前的内存数据
查看>>
No qualifying bean of type available问题修复
查看>>
第四周助教心得体会
查看>>
spfile
查看>>
Team Foundation Service更新:改善了导航和项目状态速查功能
查看>>
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>