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 能够兼容绝大部 ...
- 搭建Nginx正向代理服务
需求背景: 前段时间公司因为业务需求需要部署一个正向代理,需要内网服务通过正向代理访问到外网移动端厂商域名通道等效果,之前一直用nginx做四层或者七层的反向代理,正向代理还是第一次配置,配置的过程也 ...
- Java描述设计模式(21):状态模式
本文源码:GitHub·点这里 || GitEE·点这里 一.生活场景 1.场景描述 变色龙是爬行动物,是非常奇特的动物,它有适于树栖生活的种种特征和行为,身体也会随着环境的变化而变化出适应环境的颜色 ...
- Redis的内存淘汰策略
Redis占用内存大小 我们知道Redis是基于内存的key-value数据库,因为系统的内存大小有限,所以我们在使用Redis的时候可以配置Redis能使用的最大的内存大小. 1.通过配置文件配置 ...
- Docker基础与实战,看这一篇就够了
docker 基础 什么是Docker Docker 使用 Google 公司推出的 Go 语言 进行开发实现,基于 Linux 内核的 cgroup,namespace,以及 AUFS 类的 Uni ...
- 万恶之源-与python的初识
1.计算机基础知识 1.cpu: 人类的大脑 运算和处理问题 2.内存: 临时存储数据 断电就消失了 3.硬盘: 永久 存储数据 4.操作系统:是一个软件 控制每个硬件之间数据交互 2 ...
- Netflix 开源 Polynote:对标 Jupyter,一个笔记本运行多种语言
谈到数据科学领域的开发工具,Jupyter 无疑是非常知名的一种.它具有灵活高效的特点,非常适合进行开发.调试.分享和教学.近日,Netflix(奈飞)居然也玩起了跨界,他们开源了一个名为 Polyn ...
- react create-react-app使用less 及关闭eslint
使用less和关闭eslint都需要先运行命令 npm run eject 来暴露配置文件,(不可逆的) 一.less使用 运行命令安装less npm install less less-load ...
- applicationContext-dao.xml 配置错误
https://www.captainbed.net/ 配置文件报错: 不允许有匹配 "[xX][mM][lL]" 的处理指令目标. 错误原因: 由于大部分都是搬砖,所以格式没注意 ...
- Java8 Stream中间操作使用详解
前面两篇简单的介绍了Stream以及如何创建Stream,本篇就给大家说说stream有哪些用途,以及具体怎样使用. 再次介绍Stream Stream 使用一种类似用于SQL 语句从数据库查询数据的 ...