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 ...
随机推荐
- 详细讲解 Redis 的两种安装部署方式
Redis 是一款比较常用的 NoSQL 数据库,我们通常使用 Redis 来做缓存,这是一篇关于 Redis 安装的文章,所以不会涉及到 Redis 的高级特性和使用场景,Redis 能够兼容绝大部 ...
- 网站搭建-windows 系统 本地 网站搭建 - IIS
上一章有提到IIS安装,现在打开它: 点击浏览,如果没有启动的话,先点击启动. ip先选好,第一个吧,本机的(IIS自己提供了初始网页的东西). 然后可以自己去https://www.freemoba ...
- thinkphp volist标签中加if判断的写法
<if condition="$vo['devstatus'] eq 1">在线<else /> 离线</if> IF标签用法 <if c ...
- suseoj The wheat of the prime minister
1202: 2018四川理工学院大学生ACM程序设计:The wheat of the prime minister 时间限制: 1 Sec 内存限制: 128 MB提交: 4 解决: 3[提交] ...
- nyoj 108-士兵杀敌(一)(数学)
108-士兵杀敌(一) 内存限制:64MB 时间限制:1000ms 特判: No 通过数:60 提交数:221 难度:3 题目描述: 南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的. ...
- 利用tomcat搭建图片服务器
今天来教大家如何使用 tomcat 来搭建一个图片的服务器 1.先将tomcat解压一份并改名 2.此时apache-tomcat-8.5.43-windows-x64-file为图片服务器 依次打开 ...
- Python 并发总结,多线程,多进程,异步IO
1 测量函数运行时间 import time def profile(func): def wrapper(*args, **kwargs): import time start = time.tim ...
- odoo12 修行基础篇之 添加明细字段 (二)
前一篇介绍了如何在视图和表单中添加字段.本节内容,我们讨论下如何在明细中加字段. 我想在销售页面明细中增加税额字段,这在表sale.order.line中已经存在,在此仅用来演示. odoo的明细一般 ...
- 【Luogu P5490】扫描线
Luogu P5490 作为一道模板题让我卡了一个月…… 对于线段树+离散化新手而言这实在是太难了…… 有关离散化: 可以查看这一篇文章:https://www.jianshu.com/p/93476 ...
- 开始你的api:NetApiStarter
在此之前,写过一篇 给新手的WebAPI实践 ,获得了很多新人的认可,那时还是基于.net mvc,文档生成还是自己闹洞大开写出来的,经过这两年的时间,netcore的发展已经势不可挡,自己也在不断的 ...