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 ...
随机推荐
- Zabbix安装部署实践
操作系统: [root@mysql ~]# cat /etc/redhat-release CentOS Linux release 7.5.1804 (Core) Mysql : 版本5.7 ...
- MemoryStream相关知识分享
一.简单介绍一下MemoryStream MemoryStream是内存流,为系统内存提供读写操作,由于MemoryStream是通过无符号字节数组组成的,可以说MemoryStream的性能可以算比 ...
- 【Flume】Flume基础之安装与使用
1.Flume简介 (1) Flume提供一个分布式的,可靠的,对大数据量的日志进行高效收集.聚集.移动的服务,Flume只能在Unix环境下运行. (2) Flume基于流式架构,容错性强, ...
- ZeroC ICE的协议
- FPGA基础(verilog语言)——语法篇
verilog语言简介 verilog语言是一种语法类似于c的语言,但是与c语言也有不同之处,比如: 1.verilog语言是并行的,每个always块都是同时执行,而c语言是顺序执行的 2.veri ...
- 做为GPU服务器管理员,当其他用户需要执行某个要root权限的命令时,除了告诉他们root密码,还有没有别的办法?
通常一台GPU服务器(这里指linux系统)不可能只有一个帐号能用的,比如当其他用户想要在GPU服务器上安装一些软件的时候,会需要用到apt-get命令,但是apt-get命令需要root用户的操作权 ...
- [ch03-02] 交叉熵损失函数
系列博客,原文在笔者所维护的github上:https://aka.ms/beginnerAI, 点击star加星不要吝啬,星越多笔者越努力. 3.2 交叉熵损失函数 交叉熵(Cross Entrop ...
- Linux目录结构-中部
第1章 /proc目录下 1.1 /proc/cpuinfo 系统cpu信息 [root@nfsnobody ~]# cat /proc/cpuinfo 一般常用的是 ...
- Java package 包的命名规范。
Java的包名都有小写单词组成,类名首字母大写:包的路径符合所开发的 系统模块的 定义,比如生产对生产,物资对物资,基础类对基础类.以便看了包名就明白是哪个模块,从而直接到对应包里找相应的实现. 由于 ...
- rsync工具、rsync常用选项、以及rsync通过ssh同步 使用介绍
第8周5月14日任务 课程内容: 10.28 rsync工具介绍10.29/10.30 rsync常用选项10.31 rsync通过ssh同步 10.28 rsync工具介绍 rsync是一个同步的工 ...