1、产生密钥:

private static void CreateKey()
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
string publicKey = rsa.ToXmlString(false); // 公钥
string privateKey = rsa.ToXmlString(true); // 私钥
}
}

这里产生的密钥是xml格式的,这也是.net的rsa的密钥格式。但有时候在.net项目中,我们只有java格式的密钥,具体的来说密钥就是一个字符串,这时候需要将其转换为xml格式的。

//公钥格式的转换
public static string RsaPublicKeyToXml(string publicKey)
{
try
{
if (string.IsNullOrWhiteSpace(publicKey))
return "";
if (publicKey.Contains("<RSAKeyValue>"))
return publicKey;
RsaKeyParameters publicKeyParam;
//尝试进行java格式的密钥读取
try
{
publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
}
catch
{
publicKeyParam = null;
}
//非java格式密钥进行pem格式的密钥读取
if (publicKeyParam == null)
{
try
{
var pemKey = publicKey;
if (!pemKey.Contains("BEGIN RSA PRIVATE KEY"))
{
pemKey = @"-----BEGIN RSA PRIVATE KEY-----
" + publicKey + @"
-----END RSA PRIVATE KEY-----";
}
var array = Encoding.ASCII.GetBytes(pemKey);
var stream = new MemoryStream(array);
var reader = new StreamReader(stream);
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
publicKeyParam = (RsaKeyParameters)pemReader.ReadObject();
}
catch
{
publicKeyParam = null;
}
}
//如果都解析失败,则返回原串
if (publicKeyParam == null)
return publicKey;
//输出XML格式密钥
return string.Format(
"<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned())
);
}
catch (Exception)
{
return "error";
}
}
//私钥格式转换
public static string RsaPrivateKeyToXml(string privateKey)
{
try
{
if (string.IsNullOrWhiteSpace(privateKey))
return "";
if (privateKey.Contains("<RSAKeyValue>"))
return privateKey;
RsaPrivateCrtKeyParameters privateKeyParam;
//尝试进行java格式的密钥读取
try
{
privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
}
catch
{
privateKeyParam = null;
}
//非java格式密钥进行pem格式的密钥读取
if (privateKeyParam == null)
{
try
{
var pemKey = privateKey;
if (!pemKey.Contains("BEGIN RSA PRIVATE KEY"))
{
pemKey = @"-----BEGIN RSA PRIVATE KEY-----
" + privateKey + @"
-----END RSA PRIVATE KEY-----";
}
var array = Encoding.ASCII.GetBytes(pemKey);
var stream = new MemoryStream(array);
var reader = new StreamReader(stream);
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
var keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
privateKeyParam = (RsaPrivateCrtKeyParameters)keyPair.Private;
}
catch
{
privateKeyParam = null;
}
}
//如果都解析失败,则返回原串
if (privateKeyParam == null)
return privateKey;
//输出XML格式密钥
return string.Format(
"<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())
);
}
catch (Exception)
{
throw PayException.New("RSA私钥密钥格式转换失败");
}
}

2、公钥加密,私钥解密(包括超长字符串的分段加密解密)

public static string RsaEncrypt(string rawInput, string publicKey)
{
if (string.IsNullOrEmpty(rawInput))
{
return string.Empty;
} if (string.IsNullOrWhiteSpace(publicKey))
{
throw new ArgumentException("Invalid Public Key");
} using (var rsaProvider = new RSACryptoServiceProvider())
{
var inputBytes = Encoding.UTF8.GetBytes(rawInput);//有含义的字符串转化为字节流
rsaProvider.FromXmlString(publicKey);//载入公钥
int bufferSize = (rsaProvider.KeySize / ) - ;//单块最大长度
var buffer = new byte[bufferSize];
using (MemoryStream inputStream = new MemoryStream(inputBytes),
outputStream = new MemoryStream())
{
while (true)
{ //分段加密
int readSize = inputStream.Read(buffer, , bufferSize);
if (readSize <= )
{
break;
} var temp = new byte[readSize];
Array.Copy(buffer, , temp, , readSize);
var encryptedBytes = rsaProvider.Encrypt(temp, false);
outputStream.Write(encryptedBytes, , encryptedBytes.Length);
}
return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
}
}
} public static string RsaDecrypt(string encryptedInput, string privateKey)
{
if (string.IsNullOrEmpty(encryptedInput))
{
return string.Empty;
} if (string.IsNullOrWhiteSpace(privateKey))
{
throw new ArgumentException("Invalid Private Key");
} using (var rsaProvider = new RSACryptoServiceProvider())
{
var inputBytes = Convert.FromBase64String(encryptedInput);
rsaProvider.FromXmlString(privateKey);
int bufferSize = rsaProvider.KeySize / ;
var buffer = new byte[bufferSize];
using (MemoryStream inputStream = new MemoryStream(inputBytes),
outputStream = new MemoryStream())
{
while (true)
{
int readSize = inputStream.Read(buffer, , bufferSize);
if (readSize <= )
{
break;
} var temp = new byte[readSize];
Array.Copy(buffer, , temp, , readSize);
var rawBytes = rsaProvider.Decrypt(temp, false);
outputStream.Write(rawBytes, , rawBytes.Length);
}
return Encoding.UTF8.GetString(outputStream.ToArray());
}
}
}

3、私钥加密,公钥解密(包括超长字符串的分段加密解密)

/// <summary>
/// RSA加密 使用私钥加密
/// </summary>
/// <param name="byteData"></param>
/// <param name="key"></param>
/// <returns></returns>
private static string RSAEncrypt(string data, string key)
{
byte[] byteData = Encoding.UTF8.GetBytes(data);
var privateRsa = GetRsaCryptoFromXml(key);
//转换密钥 下面的DotNetUtilities来自Org.BouncyCastle.Security
var keyPair = DotNetUtilities.GetKeyPair(privateRsa); var c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); c.Init(true, keyPair.Private);//取私钥(true为加密) int bufferSize = (privateRsa.KeySize / ) - ;//单块最大长度
var buffer = new byte[bufferSize];
using (MemoryStream inputStream = new MemoryStream(byteData), outputStream = new MemoryStream())
{
while (true)
{ //分段加密
int readSize = inputStream.Read(buffer, , bufferSize);
if (readSize <= )
{
break;
} var temp = new byte[readSize];
Array.Copy(buffer, , temp, , readSize);
//var encryptedBytes = rsaProvider.Encrypt(temp, false);
var encryptedBytes = c.DoFinal(temp);
outputStream.Write(encryptedBytes, , encryptedBytes.Length);
}
return Convert.ToBase64String( outputStream.ToArray());//转化为字节流方便传输
} } /// <summary>
/// RSA解密 使用公钥解密
/// </summary>
/// <param name="byteData"></param>
/// <param name="key"></param>
/// <returns></returns>
private static string RSADecrypt(string data, string key)
{
byte[] byteData= Convert.FromBase64String(data);
var privateRsa = GetRsaCryptoFromXml(key);
//转换密钥
var keyPair = DotNetUtilities.GetRsaPublicKey(privateRsa); var c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); c.Init(false, keyPair);//取公钥(false为解密) using (MemoryStream inputStream = new MemoryStream(byteData), outputStream = new MemoryStream())
{
int restLength = byteData.Length;
while (restLength > )
{
int readLength = restLength < ? restLength : ;
restLength = restLength - readLength;
byte[] readBytes = new byte[readLength];
inputStream.Read(readBytes, , readLength);
byte[] append = c.DoFinal(readBytes);
outputStream.Write(append, , append.Length);
}
//注意,这里不一定就是用utf8的编码方式,这个主要看加密的时候用的什么编码方式
return Encoding.UTF8.GetString(outputStream.ToArray());
} }

.net中RSA加密解密的更多相关文章

  1. OpenSSL 中 RSA 加密解密实现源代码分析

    1.RSA 公钥和私钥的组成.以及加密和解密的公式: 2.模指数运算: 先做指数运算,再做模运算.如 5^3 mod 7 = 125 mod 7 = 6 3.RSA加密算法流程: 选择一对不同的.而且 ...

  2. 【转】C#中RSA加密解密和签名与验证的实现

    [转]C#中RSA加密解密和签名与验证的实现 RSA加密算法是一种非对称加密算法.在公钥加密标准和电子商业中RSA被广泛使用.RSA是1977年由罗纳德•李维斯特(Ron Rivest).阿迪•萨莫尔 ...

  3. C#中RSA加密解密和签名与验证的实现

    RSA加密算法是一种非对称加密算法.在公钥加密标准和电子商业中RSA被广泛使用.RSA是1977年由罗纳德•李维斯特(Ron Rivest).阿迪•萨莫尔(Adi Shamir)和伦纳德•阿德曼(Le ...

  4. php中rsa加密解密验证

    RSA非对称加密,对敏感的数据传输进行数据加密.验证等.测试环境:wamp.aliyun虚拟主机(lamp)一.加密解密的第一步是生成公钥.私钥对,私钥加密的内容能通过公钥解密(反过来亦可以).下载生 ...

  5. C# Java间进行RSA加密解密交互

    原文:C# Java间进行RSA加密解密交互 这里,讲一下RSA算法加解密在C#和Java之间交互的问题,这两天纠结了很久,也看了很多其他人写的文章,颇受裨益,但没能解决我的实际问题,终于,还是被我捣 ...

  6. RSA加密解密中pkcs1与pkcs8格式私钥互相转换

    net,ios中rsa加解密使用的是pkcs1,而java使用的是pkcs8 如果是按1024取模(通常都是1024),pkcs1格式的私钥长度应该是812.如果是pkcs8的格式的密钥长度为861. ...

  7. 兼容javascript和C#的RSA加密解密算法,对web提交的数据进行加密传输

    Web应用中往往涉及到敏感的数据,由于HTTP协议以明文的形式与服务器进行交互,因此可以通过截获请求的数据包进行分析来盗取有用的信息.虽然https可以对传输的数据进行加密,但是必须要申请证书(一般都 ...

  8. iOS使用Security.framework进行RSA 加密解密签名和验证签名

    iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...

  9. C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法

    因为C#的RSA加密解密只有公钥加密,私钥解密,没有私钥加密,公钥解密.在网上查了很久也没有很好的实现.BouncyCastle的文档少之又少.很多人可能会说,C#也是可以的,通过Biginteger ...

随机推荐

  1. SOJ 2749_The Fewest Coins

    [题意]:已知整个交易系统有N (1 ≤ N ≤ 100)种不同的货币,分别价值V1,V2,V3.......VN(1 ≤ Vi ≤ 120),FJ分别有C1,C2,C3.....CN(0 ≤ Ci ...

  2. POJ 3279 Fliptile【枚举】

    题意: 又是农夫和牛的故事...有m*n个黑白块,黑块的背面是白块,白块背面是黑块,一头牛踩一块,则这个块的上下左右的方块都会转动,问至少踩多少块,才会使所有块都变成白色? 分析: 还是开关问题,同样 ...

  3. sata express接口

    华硕z97主板的sata express接口目前没什么用,但随着电脑接口的发展,可能会占据一席之地. 1.顾名思义,SATA-Express是SATA接口 + PCI-Express的混合体,其理论带 ...

  4. Eclipse配色方案插件 真漂亮!

    原文:https://my.oschina.net/jean/blog/208263 最近发现了一个Eclipse配色方案插件,这回给Eclipse配色太方便了. 插件主页:http://eclips ...

  5. html中布局,让下一个子元素占据剩余的高度

    ---------------------------------------------------------------------- 原因是: height:100% 引起的, 这句话的意思是 ...

  6. activiti自己定义流程之Spring整合activiti-modeler5.16实例(四):部署流程定义

    注:(1)环境搭建:activiti自己定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建         (2)创建流程模型:activiti自己定义流程之Spr ...

  7. Android插屏动画效果

    公司研发SDK,须要类似有米插屏的动画效果,研究了下,写了一个DEMO,凝视非常具体了. <span style="font-size:24px;">package c ...

  8. 使用shell分页读取600万+的MySQL数据脚本

    shell-mysql 脚本背景 因为要在Linux上.远程读取mysql的表的数据,然后做一定清洗后.把数据上传至Hadoop集群中,使用Java写吧,感觉太麻烦了.得在Win上开发好,还得打成ja ...

  9. [Java][Android] 多线程同步-主线程等待全部子线程完毕案例

    有时候我们会遇到这种问题:做一个大的事情能够被分解为做一系列相似的小的事情,而小的事情无非就是參数上有可能不同样而已! 此时,假设不使用线程,我们势必会浪费许多的时间来完毕整个大的事情.而使用线程的话 ...

  10. 分布式数据库DDM Sidecar模式负载均衡

    简介 1.分布式数据库中间件 DDM 分布式数据库中间件(Distributed Database Middleware)是解决数据库容量.性能瓶颈和分布式扩展问题的中间件服务,提供分库分表.读写分离 ...