C# RSA 加密
class Sign_verifySign
{
#region prepare string to sign.
//example format: a=123&b=xxx&c (with sort)
private static string encrypt<T>(T body)
{
var mType = body.GetType();
var props = mType.GetProperties().OrderBy(x => x.Name).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in props)
{
if (p.Name != "sign" && p.Name != "signType" && p.GetValue(body, null) != null && p.GetValue(body, null).ToString() != "")
{
sb.Append(string.Format("{0}={1}&", p.Name, p.GetValue(body, null)));
}
}
var tmp = sb.ToString();
return tmp.Substring(, tmp.Length - );
}
#endregion #region sign
public static string sign(string content, string privateKey, string input_charset)
{
byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
SHA1 sh = new SHA1CryptoServiceProvider();
byte[] signData = rsa.SignData(Data, sh);
//get base64string -> ASCII byte[]
var base64ToByte = Encoding.ASCII.GetBytes(Convert.ToBase64String(signData));
string signresult = BitConverter.ToString(base64ToByte).Replace("-", string.Empty);
return signresult;
}
private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
{
byte[] pkcs8privatekey; pkcs8privatekey = Convert.FromBase64String(pemstr);
if (pkcs8privatekey != null)
{
RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey);
return rsa;
}
else return null;
}
private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
{
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[]; MemoryStream mem = new MemoryStream(pkcs8);
int lenstream = (int)mem.Length; BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
byte bt = ;
ushort twobytes = ;
try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
bt = binr.ReadByte();
if (bt != 0x02)
return null;
twobytes = binr.ReadUInt16();
if (twobytes != 0x0001)
return null;
seq = binr.ReadBytes(); //read the Sequence OID
if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
return null;
bt = binr.ReadByte();
if (bt != 0x04) //expect an Octet string
return null;
bt = binr.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count
if (bt == 0x81)
binr.ReadByte();
else
if (bt == 0x82)
binr.ReadUInt16(); //------ at this stage, the remaining sequence should be the RSA private key
byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey);
return rsacsp;
}
catch (Exception)
{return null;
}
finally
{
binr.Close();
}
}
private static bool CompareBytearrays(byte[] a, byte[] b)
{
if (a.Length != b.Length) return false;
int i = ; foreach (byte c in a)
{ if (c != b[i]) return false; i++; }
return true;
}
private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey);
BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
byte bt = ;
ushort twobytes = ;
int elems = ;
try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null; twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
return null;
bt = binr.ReadByte();
if (bt != 0x00)
return null; //------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus = MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception e)
{
return null;
}
finally { binr.Close(); }
}
private static int GetIntegerSize(BinaryReader binr)
{
byte bt = ;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = ;
bt = binr.ReadByte();
if (bt != 0x02) //expect integer
return ;
bt = binr.ReadByte(); if (bt == 0x81)
count = binr.ReadByte(); // data size in next byte
else
if (bt == 0x82)
{
highbyte = binr.ReadByte(); // data size in next 2 bytes
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, );
}
else
{
count = bt; // we already have the data size
}while (binr.ReadByte() == 0x00)
{ //remove high order zeros in data
count -= ;
}
binr.BaseStream.Seek(-, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
return count;
} #endregion #region verifySign
//onepay verify
public static bool verifyFromHexAscii(string sign, string publicKey, string content, string charset)
{
string decSign = System.Text.Encoding.UTF8.GetString(fromHexAscii(sign));
return verify(content, decSign, publicKey, charset);
}
public static byte[] fromHexAscii(string s)
{
try
{
int len = s.Length;
if ((len % ) != )
throw new Exception("Hex ascii must be exactly two digits per byte."); int out_len = len / ;
byte[] out1 = new byte[out_len];
int i = ;
StringReader sr = new StringReader(s);
while (i < out_len)
{
int val = ( * fromHexDigit(sr.Read())) + fromHexDigit(sr.Read());
out1[i++] = (byte)val;
}
return out1;
}
catch (IOException e)
{
throw new Exception("IOException reading from StringReader?!?!");
}
}
private static int fromHexDigit(int c)
{
if (c >= 0x30 && c < 0x3A)
return c - 0x30;
else if (c >= 0x41 && c < 0x47)
return c - 0x37;
else if (c >= 0x61 && c < 0x67)
return c - 0x57;
else
throw new Exception('\'' + c + "' is not a valid hexadecimal digit.");
} public static bool verify(string content, string signedString, string publicKey, string input_charset)
{
signedString = signedString.Replace("*", "+");
signedString = signedString.Replace("-", "/");
return JiJianverify(content, signedString, publicKey, input_charset); }
public static bool JiJianverify(string content, string signedString, string publicKey, string input_charset)
{
bool result = false;
byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content); byte[] data = Convert.FromBase64String(signedString);
RSAParameters paraPub = ConvertFromPublicKey(publicKey);
RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
rsaPub.ImportParameters(paraPub);
SHA1 sh = new SHA1CryptoServiceProvider();
result = rsaPub.VerifyData(Data, sh, data);
return result;
}
private static RSAParameters ConvertFromPublicKey(string pemFileConent)
{ byte[] keyData = Convert.FromBase64String(pemFileConent);
if (keyData.Length < )
{
throw new ArgumentException("pem file content is incorrect.");
}
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(keyData); RSAParameters para = new RSAParameters();
para.Modulus = publicKeyParam.Modulus.ToByteArrayUnsigned();
para.Exponent = publicKeyParam.Exponent.ToByteArrayUnsigned();
return para;
}
#endregion
}
C# RSA 加密的更多相关文章
- “不给力啊,老湿!”:RSA加密与破解
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 加密和解密是自古就有技术了.经常看到侦探电影的桥段,勇敢又机智的主角,拿着一长串毫 ...
- .NET 对接JAVA 使用Modulus,Exponent RSA 加密
最近有一个工作是需要把数据用RSA发送给Java 虽然一开始标准公钥 net和Java RSA填充的一些算法不一样 但是后来这个坑也补的差不多了 具体可以参考 http://www.cnblogs. ...
- Android数据加密之Rsa加密
前言: 最近无意中和同事交流数据安全传输的问题,想起自己曾经使用过的Rsa非对称加密算法,闲下来总结一下. 其他几种加密方式: Android数据加密之Rsa加密 Android数据加密之Aes加密 ...
- 兼容javascript和C#的RSA加密解密算法,对web提交的数据进行加密传输
Web应用中往往涉及到敏感的数据,由于HTTP协议以明文的形式与服务器进行交互,因此可以通过截获请求的数据包进行分析来盗取有用的信息.虽然https可以对传输的数据进行加密,但是必须要申请证书(一般都 ...
- RSA加密例子和中途遇到的问题
在进行RSA加密例子 package test; import java.io.IOException; import java.security.Key; import java.security. ...
- iOS中RSA加密详解
先贴出代码的地址,做个说明,因为RSA加密在iOS的代码比较少,网上开源的也很少,最多的才8个星星.使用过程中发现有错误.然后我做了修正,和另一个库进行了整合,然后将其支持CocoaPod. http ...
- iOS动态部署之RSA加密传输Patch补丁
概要:这一篇博客主要说明下iOS客户端动态部署方案中,patch(补丁)是如何比较安全的加载到客户端中. 在整个过程中,需要使用RSA来加密(你可以选择其它的非对称加密算法),MD5来做校验(同样,你 ...
- Java使用RSA加密解密及签名校验
该工具类中用到了BASE64,需要借助第三方类库:javabase64-1.3.1.jar注意:RSA加密明文最大长度117字节,解密要求密文最大长度为128字节,所以在加密和解密的过程中需要分块进行 ...
- 基于OpenSLL的RSA加密应用(非算法)
基于OpenSLL的RSA加密应用(非算法) iOS开发中的小伙伴应该是经常用der和p12进行加密解密,而且在通常加密不止一种加密算法,还可以加点儿盐吧~本文章主要阐述的是在iOS中基于openSL ...
- 通过ios实现RSA加密和解密
在加密和解密中,我们需要了解的知识有什么事openssl:RSA加密算法的基本原理:如何通过openssl生成最后我们需要的der和p12文件. 废话不多说,直接写步骤: 第一步:openssl来生成 ...
随机推荐
- SqlServer 循环建表、删除表、更新表
常用于分库分表 1.批量删除 declare @outter int declare @inner int ) ) ) begin set @tablePrefix='BankPayOrder_'+c ...
- Java工程师学习指南 入门篇
Java工程师学习指南 入门篇 最近有很多小伙伴来问我,Java小白如何入门,如何安排学习路线,每一步应该怎么走比较好.原本我以为之前的几篇文章已经可以解决大家的问题了,其实不然,因为我之前写的文章都 ...
- Linux基础命令 ls
目录 1. ls 列出目录的内容 -a --all: -A --almost-all: -b --escape: --block-size=SIZE: --color: --d --directory ...
- Golang GC原理
一.内存泄漏 内存泄露,是从操作系统的角度上来阐述的,形象的比喻就是“操作系统可提供给所有进程的存储空间(虚拟内存空间)正在被某个进程榨干”,导致的原因就是程序在运行的时候,会不断地动态开辟的存储空间 ...
- 负载均衡+session共享(memcached-session-manager实现)
前言 先给大家伙拜个年,祝大家:新的一年健健康康,平平安安! 本文的形成参考了很多人的博客,最多的应该是青葱岁月兄的这篇博客,大家可以先去看下,熟悉一些内容,因为本文是直接实践,一些理论性的知识就需要 ...
- netty源码解解析(4.0)-8 ChannelPipeline的设计
io.netty.channel.ChannelPipeline 设计原理 上图中,为了更直观地展示事件处理顺序, 故意有规律地放置两种handler的顺序,实际上ChannelInboundHa ...
- 使用WPF教你一步一步实现连连看(二)
连连看算法 第一步:我们考虑在同行或者同列的情况: 同行或者同列又分三种情况: 第一:边线,RowNum或者ColNum等于0或者9 第二:两个相邻 第三:同行不相邻,这种事有条件的,所在行(或列)的 ...
- oracle与mysql
『创业团队最佳选择是Oracle+MongoDB,而不是MySQL』,当深蓝在QQ群里抛出这样的观点的时候,就像是在马蜂窝里丢了一串鞭炮一样热闹起来. 创业者甲: 开什么玩笑,Oracle要收钱的,太 ...
- Docker 安装MySQL5.7(三)
Docker 安装MySQL5.7 1.搜索docker镜像(可以看到搜索的结果,这个结果是按照一定的星级评价规则排序的) docker search mysql 2.拉取docker的mysql镜像 ...
- http请求的headers详解
关于http请求的headers详解:这里以HTTP1.1为例结合postman返回的信息 1.Server →nginx/1.15.8 A name for the server 这是post ...