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来生成 ...
随机推荐
- Studying
美团spark实践:http://tech.meituan.com/spark-in-meituan.html CDH5.6.0-HBase1.0.0:http://archive.cloudera. ...
- php实现聊天室功能
原理:长连接 一.长连接与短连接 短连接:客户端与服务端每进行一次报文收发交易时才进行通讯连接.交易完毕后立即断开连接. 长连接:客户端与服务端先建立连接, 连接建立后不断开,然后在进行报文发送和接收 ...
- 图文教程 | 开启远程访问mysql数据库权限
!!!考虑到安全性,不建议使用 所以将指定用户的host改为:% 即可 执行:(以root用户为例) use mysql; update user set host = "%" ...
- 扩展方法IEnumerable<T>转换为IList<SelectListItem> ,提供@Html.DropDownList使用
由于在MVC中经常会使用到@Html.DropDownList方法,而该方法接收的是List<SelectListItem> 参数,因此就想着写一个扩展方法,直接把IEnumerable转 ...
- AI时代的OCR识别技术浅析
人工智能这个词可谓是耳熟能详,近几年人工智能热潮再次席卷而来,引起轰动的要数google的AlphaGo,相继打败了围棋界的韩国选手李世石以及世界冠军柯洁,见证了人工智能发展的里程碑式的变革,人工智能 ...
- JavaScript 深入之从原型到原型链
1 .构造函数创建对象 我们先使用构造函数创建一个对象: function Person(){ } var p = new Person(); p.name = 'ccy'; console.log( ...
- [转]Angular4---部署---将Angular项目部署到IIS上
本文转自:https://www.cnblogs.com/kingkangstudy/p/7699710.html Angular项目部署到一个IIS服务器上 1.安装URL rewrite组件: 网 ...
- SqlHelper 1.0
SqlHelper类,可以简化对数据库的操作. 将程序中需要经常用到的数据库操作,如:连接字符串.对数据的增.删.改.查封装成“SqlHelper”类中的静态属性,方便在程序各部分进行调用. 增(in ...
- Java坦克大战(三)
关于这个坦克大战的项目是在学习Java基础的时候,拿来练习的最近看到这些代码,感觉很亲切,就把他们都复制下来,编辑成博客.回首看去,Java基础的学习确实应该建立在找项目练习上,这样才能将学到的基础知 ...
- Debian、Ubuntu恢复误删除(或者说重装)的/var/lib/dpkg
在使用ubuntu的使用,有可能会碰到dpkg挂掉,网上的通用解决方法,如果不管用: 1, dpkg 被中断,您必须手工运行 sudo dpkg --configure -a解决此问题 2, sudo ...