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来生成 ...
随机推荐
- 测试工具之Jmeter(创建一个简单测试用例)
前面介绍了如何使用badboy录制jmeter脚本,以及如何导入脚本并进行测试 这里介绍下手动创建测试用例,主要步骤如下: 1.创建线程组 第一次打开Jmeter只有一个测试计划,右键“测试计划”选择 ...
- web自动化测试---自动化脚本设置百度搜索每页显示条数
前面学的都是基础知识,本篇将进入实战练习 以百度“搜索设置”为对象进行测试用例的写作: 百度的搜索设置在首页的“设置”里面,鼠标悬停之后即可显示,如下图红框位置: 测试目标是,修改每页的显示条数为50 ...
- 关于springboot aop 俩次调用的问题 aop多次调用
由于我在springboot 启动类中 给我的切面类进行了赋值 即@Bean 然而我在切面类中加了@Component 导致 springboot 注入了俩个 bean 所以导致 aop 多次执行 ...
- 死磕 java集合之ArrayDeque源码分析
问题 (1)什么是双端队列? (2)ArrayDeque是怎么实现双端队列的? (3)ArrayDeque是线程安全的吗? (4)ArrayDeque是有界的吗? 简介 双端队列是一种特殊的队列,它的 ...
- Linux学习笔记之二————Linux系统的文件和目录
一.Windows和Linux文件系统区别 1.在 windows 平台下,打开“计算机”,我们看到的是一个个的驱动器盘符: 每个驱动器都有自己的根目录结构,这样形成了多个树并列的情形,如图所示: ...
- python面试
第一部分 python基础篇 1.简述解释型和编译型编程语言? 解释型语言编写的程序不需要编译,在执行的时候,专门有一个解释器能够将VB语言翻译成机器语言,每个语句都是执行的时候才翻译.这样解释型语言 ...
- CentOS 7 个性化配置指南
博客原文地址:CentOS 7 个性化配置指南 - Wind Spirit 0x00 前言 该教程主要安装了如下软件包 iptables MySQL PHP PHP 相关模块 Nginx 主要配置实现 ...
- 基于easyui与MVC的前端界面
1.登录界面: 2.主界面: 下载源码
- 120分钟React快速扫盲教程
在教程开端先说些题外话,我喜欢在学习一门新技术或读过一本书后,写一篇教程或总结,既能帮助消化,也能加深印象和发现自己未注意的细节,写的过程其实仍然是一个学习的过程.有个记录的话,在未来需要用到相关知识 ...
- 自己动手实现java数据结构(一) 向量
1.向量介绍 计算机程序主要运行在内存中,而内存在逻辑上可以被看做是连续的地址.为了充分利用这一特性,在主流的编程语言中都存在一种底层的被称为数组(Array)的数据结构与之对应.在使用数组时需要事先 ...