.Net C# RSA签名和验签重写
- namespace com._80community.unittest.CUP
- {
- /// <summary>
- /// CUP Client
- /// </summary>
- public interface IClient
- {
- /// <summary>
- /// Generate Signature
- /// </summary>
- /// <param name="content">contents requiring signatures</param>
- /// <param name="privateKey">private key</param>
- /// <param name="inputCharset">coding format</param>
- /// <returns>the signature string</returns>
- string Sign(string content, string inputCharset);
- /// <summary>
- /// Verification Signature
- /// </summary>
- /// <param name="content">contents requiring signature verification </param>
- /// <param name="signedString">the signature string</param>
- /// <param name="publicKey">public key</param>
- /// <param name="inputCharset">coding format</param>
- /// <returns></returns>
- bool Verify(string content, string signedString, string inputCharset);
- }
- }
- using System;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
- namespace com._80community.unittest.CUP
- {
- /// <summary>
- /// CUP Client
- /// </summary>
- public class Client : IClient
- {
- private string serverUrl;
- private string merchantNo;
- private string privateKey;
- private string publicKey;
- public Client(string serverUrl, string merchantNo, string privateKey, string publicKey)
- {
- this.serverUrl = serverUrl;
- this.merchantNo = merchantNo;
- this.privateKey = privateKey;
- this.publicKey = publicKey;
- }
- #region Generate Signature
- // <summary>
- /// Generate Signature
- /// </summary>
- public string Sign(string content, string inputCharset = "UTF-8")
- {
- 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 Internal Method for Generating Signature
- /// <summary>
- /// 把PKCS8格式的私钥转成PEK格式私钥,然后再填充RSACryptoServiceProvider对象
- /// </summary>
- /// <param name="pkcs8"></param>
- /// <returns></returns>
- internal 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 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 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 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 RSACryptoServiceProvider DecodePemPrivateKey(string pemstr)
- {
- RSACryptoServiceProvider rsa = null;
- byte[] pkcs8PrivteKey = Convert.FromBase64String(pemstr);
- if (pkcs8PrivteKey != null)
- {
- rsa = DecodePrivateKeyInfo(pkcs8PrivteKey);
- }
- return rsa;
- }
- #endregion
- #region Verification Signature
- /// <summary>
- /// Verification Signature
- /// </summary>
- public bool Verify(string content, string signedString, string inputCharset = "UTF-8")
- {
- 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 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 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
- #region Get the value of the key from the key file
- /// <summary>
- /// Get the value of the key from the key file
- /// </summary>
- /// <param name="type">RSA PRIVATE KEY/RSA PUBLIC KEY</param>
- /// <param name="pemUrl">url of the key file</param>
- /// <returns>base64 string</returns>
- static public string GetKeyFromPem(string type, string pemUrl)
- {
- string base64 = string.Empty;
- using (FileStream fs = File.OpenRead(pemUrl))
- {
- byte[] data1 = new byte[fs.Length];
- fs.Read(data1, , data1.Length);
- string pem = Encoding.UTF8.GetString(data1);
- string header = String.Format("-----BEGIN {0}-----\\n", type);
- string footer = String.Format("-----END {0}-----", type);
- int start = pem.IndexOf(header) + header.Length;
- int end = pem.IndexOf(footer, start);
- base64 = pem.Substring(start, (end - start));
- }
- return base64;
- }
- #endregion
- }
- }
- using System.Configuration;
- namespace Entity.Common
- {
- static public partial class AppConfig
- {
- static public string GetServerUrl
- {
- get { return ConfigurationManager.AppSettings["CupServerUrl"]; }
- }
- static public string GetMerchantNo
- {
- get { return ConfigurationManager.AppSettings["CupMerchantNo"]; }
- }
- static public string GetMerchantName
- {
- get { return ConfigurationManager.AppSettings["CupMerchantName"]; }
- }
- static public string GetPublicKey
- {
- get { return ConfigurationManager.AppSettings["CupPublicKey"]; }
- }
- static public string GetPrivateKey
- {
- get { return ConfigurationManager.AppSettings["CupPrivateKey"]; }
- }
- static public string GetPublicKeyPem
- {
- get { return ConfigurationManager.AppSettings["CupPublicKeyPem"]; }
- }
- static public string GetPrivateKeyPem
- {
- get { return ConfigurationManager.AppSettings["CupPrivateKeyPem"]; }
- }
- }
- }
- <appSettings>
- <add key="CupServerUrl" value=""/>
- <add key="CupMerchantNo" value=""/>
- <add key="CupMerchantName" value=""/>
- <add key="CupPublicKey" value=""/>
- <add key="CupPrivateKey" value=""/>
- <add key="CupPublicKeyPem" value="rsa_public_key.pem"/>
- <add key="CupPrivateKeyPem" value="rsa_private_key.pem"/>
- </appSettings>
- [TestClass]
- public class RSATest
- {
- string serverUrl = AppConfig.GetServerUrl;
- string merchantNo = AppConfig.GetMerchantNo;
- //string publicKey = AppConfig.GetPublicKey;
- //string privateKey = AppConfig.GetPrivateKey;
- private string content = "";
- [TestMethod]
- public void TestMethod1()
- {
- string temp = AppDomain.CurrentDomain.BaseDirectory.Replace("bin\\Debug", "");
- string publicKeyPem = Path.Combine(temp, AppConfig.GetPublicKeyPem);
- string privateKeyPem = Path.Combine(temp, AppConfig.GetPrivateKeyPem);
- string publicKey = Client.GetKeyFromPem("RSA PUBLIC KEY", publicKeyPem);
- string privateKey = Client.GetKeyFromPem("RSA PRIVATE KEY", privateKeyPem);
- Client client = new Client(serverUrl, merchantNo, privateKey, publicKey);
- var a = string.Format("待签名字符串:{0}", content);
- string res = client.Sign(content);
- var b = string.Format("签名结果:{0}", res);
- bool ss = client.Verify(content, res);
- var c = string.Format("验签结果:{0}", ss);
- }
- }
.Net C# RSA签名和验签重写的更多相关文章
- Delphi RSA签名与验签【支持SHA1WithRSA(RSA1)、SHA256WithRSA(RSA2)和MD5WithRSA签名与验签】
作者QQ:(648437169) 点击下载➨ RSA签名与验签 [delphi RSA签名与验签]支持3种方式签名与验签(SHA1WithRSA(RSA1).SHA256WithRSA(RSA2)和M ...
- erlang的RSA签名与验签
1.RSA介绍 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对 其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥,即公钥,而 ...
- .Net C# RSA签名和验签
帮助类 using System; using System.Text; using System.IO; using System.Security.Cryptography; namespace ...
- java/php/c#版rsa签名以及验签实现
本文为转载,请转载请注明地址: 原文地址为 http://xw-z1985.iteye.com/blog/1837376 在开放平台领域,需要给isv提供sdk,签名是Sdk中需要提供的 ...
- .NET Core RSA 签名和验签(密钥为 16 进制编码)
使用 OpenSSL 生成公私钥对,命令: $ openssl genrsa -out rsa_1024_priv.pem $ openssl pkcs8 -topk8 -inform PEM -in ...
- RSA签名、验签、加密、解密
最近在做一个项目,与一个支付渠道进行连接进行充值,为了安全,每个接口访问时,都要先登陆(调用登陆接口),拿到一个sessionKey,后续业务接口内容用它来进行3DES加密处理.而登陆需要用到RSA进 ...
- RSA签名和验签Util
目录 1.DigitalSign类 2.CryptException异常类 3.加签示例 1.DigitalSign类 import org.apache.commons.codec.binary.B ...
- .NET RSA解密、签名、验签
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Sec ...
- Delphi支付宝支付【支持SHA1WithRSA(RSA)和SHA256WithRSA(RSA2)签名与验签】
作者QQ:(648437169) 点击下载➨Delphi支付宝支付 支付宝支付api文档 [Delphi支付宝支付]支持条码支付.扫码支付.交易查询.交易退款.退款查询.交易撤 ...
随机推荐
- Java并发指南14:Java并发容器ConcurrentSkipListMap与CopyOnWriteArrayList
原文出处http://cmsblogs.com/ 『chenssy』 到目前为止,我们在Java世界里看到了两种实现key-value的数据结构:Hash.TreeMap,这两种数据结构各自都有着优缺 ...
- Maven的几种新建项目方式
1. 使用原型创建Maven的java工程 (1) 选择 JDK 的版本,勾选“使用原型创建”,选中 maven-archetype-quickstart,下一步. (2) 填写公司名,填写项目名,修 ...
- 修改oracle用户登录密码
运行sqlplus进入输入密码界面 用户名输入: connect as sysdba 密码:这边乱输就可以了 然后进行输入下面的命令: 修改密码命令 alter user system identif ...
- SpringBoot保存数据报错:could not execute statement; SQL [n/a]; constraint [PRIMARY];nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
使用SpringBoot做JAVA开发时,用Repository.save();保存数据的时候遇到了报错: could not execute statement; SQL [n/a]; constr ...
- 《maven实战》笔记(2)----一个简单maven项目的搭建,测试和打包
参照<maven实战>在本地创建对应的基本项目helloworld,在本地完成后项目结构如下: 可以看到maven项目的骨架:src/main/java(javaz主代码)src/test ...
- jack语言编译器的实现过程
目录: 1, 背景介绍
- Day04:循环结构(while、do-while、for)
Java 循环结构 - while ,do...while,for 反复执行一段相同或相似代码的格式. 顺序结构的程序语句只能被执行一次.如果您想要同样的操作执行多次,,就需要使用循环结构. Java ...
- jdbc访问oracle超慢,但是PLSQL访问正常
oracle数据库连接非常慢,sqlplus很快,用客户端就很慢,十几秒才好.然后服务器内存一下就飙升到了90%,最开始以为是表空间占满了,数据库连接数占满了.折腾了半天,重启,还是很慢.应用连接数据 ...
- Charles系列三:Charles打断点(包含修改请求,修改返回的内容),模拟慢速网络(弱网测试),域名映射,过滤请求,接口调试,打压测试
一:Charles断点的使用(包含修改请求,修改返回的数据) 设置断点来修改请求和返回的数据,在开发过程中可以模拟多种响应.步骤如下: 1.添加断点方法有两种: 方法1:找到Charles中菜单项Pr ...
- Memcache分布式锁
在分布式缓存的应用中,会遇到多个客户端同时争用的问题.这个时候,需要用到分布式锁,得到锁的客户端才有操作权限 下面通过一个简单例子介绍: 这里引用的是Memcached.ClientLibrary.d ...