C# Pkcs8 1024位 加密 解密 签名 解签
部分代码来至 https://www.cnblogs.com/dj258/p/6049786.html
- 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(),
- new Org.BouncyCastle.Security.SecureRandom(),
- , //密钥长度
- );
- //用参数初始化密钥构造器
- 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 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 = ;
- byte[] cache;
- int i = ;
- // 对数据分段加密
- while (inputLen - offSet > )
- {
- if (inputLen - offSet > )
- {
- cache = engine.ProcessBlock(byteData, offSet, );
- }
- else
- {
- cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet);
- }
- ms.Write(cache, , cache.Length);
- i++;
- offSet = i * ;
- }
- 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("\r", "").Replace("\n", "").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 = ;
- byte[] cache;
- int i = ;
- // 对数据分段加密
- while (inputLen - offSet > )
- {
- if (inputLen - offSet > )
- {
- cache = engine.ProcessBlock(byteData, offSet, );
- }
- else
- {
- cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet);
- }
- ms.Write(cache, , cache.Length);
- i++;
- offSet = i * ;
- }
- 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, , 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, , plainBytes.Length);
- return verifier.VerifySignature(signBytes); //验签结果
- }
- }
- }
亲测可用
C# Pkcs8 1024位 加密 解密 签名 解签的更多相关文章
- RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密
原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptograph ...
- C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic
C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider DESCryptoS ...
- js rsa sign使用笔记(加密,解密,签名,验签)
你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...
- Java RSA 加密 解密 签名 验签
原文:http://gaofulai1988.iteye.com/blog/2262802 import java.io.FileInputStream; import java.io.FileOut ...
- iOS使用Security.framework进行RSA 加密解密签名和验证签名
iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...
- .NET Core 使用RSA算法 加密/解密/签名/验证签名
前言 前不久移植了支付宝官方的SDK,以适用ASP.NET Core使用支付宝支付,但是最近有好几位用户反应在Linux下使用会出错,调试发现是RSA加密的错误,下面具体讲一讲. RSA在.NET C ...
- 使用 GPG 对数据进行加密解密签名
一:使用 GPG 对数据进行加密解密签名 基本的工具使用 1. GPG 是GNUPG 免费开源的gpg加密工具,和同pgp兼容,pgp收费. 2. 在mac上使用https://gpgtools.or ...
- RSA加密解密与加签验签
RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.1987年7月首次在美国公布 ...
- 支付接口中常用的加密解密以及验签rsa,md5,sha
一.常用加密类型分类 1.对称加密:采用单钥对信息进行加密和解密,即同一个秘钥既可以对信息进行加密,也可以进行解密.此类型称之为对称加密.特点速度快,常用于对大量数据信息或文件加密时使用.常用例子:D ...
随机推荐
- Linux系统中nc工具那些不为人知的用法
Linux nc命令用法 参考地址:https://www.cnblogs.com/jjzd/p/6306273.html -g<网关>:设置路由器跃程通信网关,最多设置8个; -G< ...
- PHP导出成PDF你用哪个插件
准备工作 首先查询了相关的类库,有FPDF,zendPDF,TcPDF等等.首先看了下先选择了FPDF,可以说除了中文字符以外没有什么问题,中文乱码而且看了下最新版本没有很好的解决方案,所以只能放弃. ...
- poj 3281 Dining (Dinic)
Dining Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 22572 Accepted: 10015 Descript ...
- windows 10上源码编译libjpeg-turbo和使用教程 | compile and use libjpeg-turbo on windows 10
本文首发于个人博客https://kezunlin.me/post/83828674/,欢迎阅读! compile and use libjpeg-turbo on windows 10 Series ...
- Class文件结构全面解析(下)
接上回书 书接上一回,分享了Class文件的主要构成,同时也详细分析了魔数.次版本号.主版本号.常量池集合.访问标志的构造,接下来我们就继续学习. 欢迎关注微信公众号:万猫学社,每周一分享Java技术 ...
- Orleans 3.0 为我们带来了什么
原文:https://devblogs.microsoft.com/dotnet/orleans-3-0/ 作者:Reuben Bond,Orleans首席软件开发工程师 翻译:艾心 这是一篇来自Or ...
- jinjia2
ansible-playbook --become --become-method=su -K copy.yml - hosts: web remote_user: ansible tasks: - ...
- Redis 数据结构
一.Redis简介 Redis是一款基于key-value的高性能NoSQL数据库,开源免费,遵守BSD协议.支持string(字符串) . hash(哈希) .list(列表) . set(集合) ...
- Liunx 安装配置zsh和oh-my-zsh 替换 bash
一.前言 本文将基于 Liunx 环境安装配置zsh 和 oh-my-zsh 替换 bash oh my zsh Liunx默认shell是单调的bash,而zsh比较高大上,bash有的功能,zsh ...
- css优先级之important
css优先级之important