帮助类

using System;
using System.Text;
using System.IO;
using System.Security.Cryptography; namespace Com.AppCode.RSA
{
public class Client
{
#region 生成签名 // <summary>
/// 签名
/// </summary>
/// <param name="content">需要签名的内容</param>
/// <param name="privateKey">私钥</param>
/// <param name="inputCharset">编码格式</param>
/// <returns>返回签名字符串</returns>
public static string Sign(string content, string privateKey, string inputCharset)
{
try
{
Encoding code = Encoding.GetEncoding(inputCharset);
byte[] data = code.GetBytes(content);
RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
SHA1 sh = new SHA1CryptoServiceProvider(); byte[] signData = rsa.SignData(data, sh);
return Convert.ToBase64String(signData);
}
catch
{
return "";
}
} #region 生成签名内部方法
/// <summary>
/// 把PKCS8格式的私钥转成PEK格式私钥,然后再填充RSACryptoServiceProvider对象
/// </summary>
/// <param name="pkcs8"></param>
/// <returns></returns>
internal 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);
RSACryptoServiceProvider rsacsp = null; int lenStream = (int)mem.Length;
BinaryReader binReader = new BinaryReader(mem);
byte bt = ;
ushort twoBytes = ; try
{
twoBytes = binReader.ReadUInt16();
if (twoBytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binReader.ReadByte(); //advance 1 byte
else if (twoBytes == 0x8230)
binReader.ReadInt16(); //advance 2 bytes
else
return null; bt = binReader.ReadByte();
if (bt != 0x02)
return null; twoBytes = binReader.ReadUInt16(); if (twoBytes != 0x0001)
return null; seq = binReader.ReadBytes(); //read the Sequence OID
if (!CompareBytearrays(seq, seqOID)) //make sure Sequence for OID is correct
return null; bt = binReader.ReadByte();
if (bt != 0x04) //expect an Octet string
return null; bt = binReader.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count
if (bt == 0x81)
binReader.ReadByte();
else
if (bt == 0x82)
binReader.ReadUInt16(); // at this stage, the remaining sequence should be the RSA private key
byte[] rsaprivkey = binReader.ReadBytes((int)(lenStream - mem.Position));
rsacsp = DecodeRSAPrivateKey(rsaprivkey); return rsacsp;
}
catch
{
return null;
}
finally
{
binReader.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;
} /// <summary>
/// PEM格式私钥转RSACryptoServiceProvider对象
/// </summary>
/// <param name="privkey"></param>
/// <returns></returns>
internal 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); // wrap Memory Stream with BinaryReader for easy reading
BinaryReader binReader = new BinaryReader(mem);
byte bt = ;
ushort twoBytes = ;
int elems = ;
try
{
twoBytes = binReader.ReadUInt16();
if (twoBytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
{
binReader.ReadByte(); // advance 1 byte
}
else if (twoBytes == 0x8230)
{
binReader.ReadInt16(); // advance 2 byte
}
else
{
return null;
} twoBytes = binReader.ReadUInt16();
if (twoBytes != 0x0102) // version number
return null;
bt = binReader.ReadByte();
if (bt != 0x00)
return null; // all private key components are Integer sequences
elems = GetIntegerSize(binReader);
modulus = binReader.ReadBytes(elems); elems = GetIntegerSize(binReader);
e = binReader.ReadBytes(elems); elems = GetIntegerSize(binReader);
d = binReader.ReadBytes(elems); elems = GetIntegerSize(binReader);
p = binReader.ReadBytes(elems); elems = GetIntegerSize(binReader);
q = binReader.ReadBytes(elems); elems = GetIntegerSize(binReader);
dp = binReader.ReadBytes(elems); elems = GetIntegerSize(binReader);
dq = binReader.ReadBytes(elems); elems = GetIntegerSize(binReader);
iq = binReader.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)
{
return null;
}
finally
{
binReader.Close();
}
} internal static int GetIntegerSize(BinaryReader binReader)
{
byte bt = ;
byte lowByte = 0x00;
byte highByte = 0x00;
int count = ;
bt = binReader.ReadByte();
if (bt != 0x02) //expect integer
return ;
bt = binReader.ReadByte(); if (bt == 0x81)
{
count = binReader.ReadByte(); // data size in next byte
}
else
{
if (bt == 0x82)
{
highByte = binReader.ReadByte(); // data size in next 2 bytes
lowByte = binReader.ReadByte();
byte[] modint = { lowByte, highByte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, );
}
else
{
count = bt; // we already have the data size
}
} while (binReader.ReadByte() == 0x00)
{ //remove high order zeros in data
count -= ;
}
binReader.BaseStream.Seek(-, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
return count;
} #endregion /// <summary>
/// 解析PKCS8格式的pem私钥
/// </summary>
/// <param name="pemstr"></param>
/// <returns></returns>
internal static RSACryptoServiceProvider DecodePemPrivateKey(string pemstr)
{
RSACryptoServiceProvider rsa = null;
byte[] pkcs8PrivteKey = Convert.FromBase64String(pemstr);
if (pkcs8PrivteKey != null)
{
rsa = DecodePrivateKeyInfo(pkcs8PrivteKey);
}
return rsa;
} #endregion #region 验签函数 /// <summary>
/// 验签函数
/// </summary>
/// <param name="content"></param>
/// <param name="signedString"></param>
/// <param name="publicKey"></param>
/// <param name="inputCharset"></param>
/// <returns></returns>
public static bool Verify(string content, string signedString, string publicKey, string inputCharset)
{
bool result = false; Encoding code = Encoding.GetEncoding(inputCharset);
byte[] data = code.GetBytes(content);
byte[] soureData = Convert.FromBase64String(signedString);
RSAParameters paraPub = ConvertFromPublicKey(publicKey);
RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
rsaPub.ImportParameters(paraPub);
SHA1 sh = new SHA1CryptoServiceProvider();
result = rsaPub.VerifyData(data, sh, soureData);
return result;
} /// <summary>
///
/// </summary>
/// <param name="pemFileConent"></param>
/// <returns></returns>
internal static RSAParameters ConvertFromPublicKey(string pempublicKey)
{
byte[] keyData = Convert.FromBase64String(pempublicKey);
if (keyData.Length < )
{
throw new ArgumentException("pem file content is incorrect.");
}
byte[] pemModulus = new byte[];
byte[] pemPublicExponent = new byte[];
Array.Copy(keyData, , pemModulus, , );
Array.Copy(keyData, , pemPublicExponent, , );
RSAParameters para = new RSAParameters();
para.Modulus = pemModulus;
para.Exponent = pemPublicExponent;
return para;
} public static string DecodeBase64(string code_type, string code)
{
string decode = "";
byte[] bytes = Convert.FromBase64String(code); //将2进制编码转换为8位无符号整数数组.
try
{
decode = Encoding.GetEncoding(code_type).GetString(bytes); //将指定字节数组中的一个字节序列解码为一个字符串。
}
catch
{
decode = code;
}
return decode;
} #endregion
}
}

单元测试

    [TestClass]
public class RSATest
{
private string pubkey = ""; private string prikye = ""; private string content = ""; [TestMethod]
public void TestMethod1()
{
var a = string.Format("待签名字符串:{0}", content); string res = Client.Sign(content, prikye, "UTF-8"); var b = string.Format("签名结果:{0}", res); bool ss = Client.Verify(content, res, pubkey, "UTF-8"); var c = string.Format("验签结果:{0}", ss);
}
}

.Net C# RSA签名和验签的更多相关文章

  1. Delphi RSA签名与验签【支持SHA1WithRSA(RSA1)、SHA256WithRSA(RSA2)和MD5WithRSA签名与验签】

    作者QQ:(648437169) 点击下载➨ RSA签名与验签 [delphi RSA签名与验签]支持3种方式签名与验签(SHA1WithRSA(RSA1).SHA256WithRSA(RSA2)和M ...

  2. erlang的RSA签名与验签

    1.RSA介绍 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对 其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥,即公钥,而 ...

  3. java/php/c#版rsa签名以及验签实现

    本文为转载,请转载请注明地址: 原文地址为        http://xw-z1985.iteye.com/blog/1837376 在开放平台领域,需要给isv提供sdk,签名是Sdk中需要提供的 ...

  4. .NET Core RSA 签名和验签(密钥为 16 进制编码)

    使用 OpenSSL 生成公私钥对,命令: $ openssl genrsa -out rsa_1024_priv.pem $ openssl pkcs8 -topk8 -inform PEM -in ...

  5. .Net C# RSA签名和验签重写

    namespace com._80community.unittest.CUP { /// <summary> /// CUP Client /// </summary> pu ...

  6. RSA签名、验签、加密、解密

    最近在做一个项目,与一个支付渠道进行连接进行充值,为了安全,每个接口访问时,都要先登陆(调用登陆接口),拿到一个sessionKey,后续业务接口内容用它来进行3DES加密处理.而登陆需要用到RSA进 ...

  7. RSA签名和验签Util

    目录 1.DigitalSign类 2.CryptException异常类 3.加签示例 1.DigitalSign类 import org.apache.commons.codec.binary.B ...

  8. .NET RSA解密、签名、验签

    using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Sec ...

  9. Delphi支付宝支付【支持SHA1WithRSA(RSA)和SHA256WithRSA(RSA2)签名与验签】

    作者QQ:(648437169) 点击下载➨Delphi支付宝支付             支付宝支付api文档 [Delphi支付宝支付]支持条码支付.扫码支付.交易查询.交易退款.退款查询.交易撤 ...

随机推荐

  1. Maven的New中没有Servlet问题(IDEA)

    1.问题 第一次使用Maven骨架创建Web项目的时候,遇到了 New 里面没有 servlet 的问题. 2.原因 经过查询,是因为IDEA检测到项目中没有导入相关的 jar 包导致. 3.解决方法 ...

  2. 重读APUE(11)-信号安全的可重入函数

    重入时间点 进程捕捉到信号并对其进行处理时,进程正在执行的正常指令序列就会被信号处理程序临时中断,它首先执行该信号粗合理程序中的指令:如果从信号处理程序返回,则继续执行捕捉到信号时进程正在执行的正常指 ...

  3. chip based learning

    chip types Transistor mode of operation Digital chip: 0/1  -> digital clac Analog chip: sound / b ...

  4. 一个数独引发的惨案:零知识证明(Zero-Knowledge Proof)

    导言:原文的作者是著名的Ghost和Spectre 这两个协议的创始团队的领队Aviv Zohar.原文作者说他的这篇原文又是引用了以下这两篇学术论文: How to Explain Zero Kno ...

  5. swift 第十四课 可视化view: @IBDesignable 、@IBInspectable

    以前应objctiew-c 写项目的时候,就知道有这两个关键字,现在用swift了.用法稍作改变,基本用法还是一致的 虽然使用这个之后,有时候会报错的非常的莫名其妙----(其实还是自己技术不够牛…… ...

  6. Django:(08)序列化器

    1.序列化和反序列化变量从内存中变成可存储或传输的过程称之为序列化,序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上.反过来,把变量内容从序列化的对象重新读到内存里称之为反序列 ...

  7. 文件夹中含有子文件夹,修改子文件夹中的图像存储格式(python实现)

    文件夹中含有子文件夹,修改子文件夹中的图像存储格式,把png图像改为jpg图像,python代码如下: import os import cv2 filePath = 'C:\\Users\\admi ...

  8. nrpe command

    1. nrpe 连接问题: 报错:/usr/local/nagios/libexec/check_nrpe  -H  destip   ;   CHECK_NRPE: Error - Could no ...

  9. 关于Python Web框架——Tornado

    关于Tornado的入门看这篇文章,写的非常好: https://zhuanlan.zhihu.com/p/37382503 Tornado 是一个Python web框架和异步网络库,使用非阻塞网络 ...

  10. Kafka 1.1.0 服务端源码阅读笔记

    网络层 01: 服务器的启动 02: Acceptor和Processor 03: RequestChannel API层 04: Handler和Apis 06: Produce请求(1): 写入本 ...