123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211 |
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- namespace Utils
- {
- public class SignatureAndVerification
- {
- /// <summary>
- /// nlog日志
- /// </summary>
- private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
- public static string keystore_password = AppSettingsHelper.Configuration["NHBridge:keystore_password"];
- public static string PrivateKeyPath = AppSettingsHelper.Configuration["NHBridge:PrivateKeyPath"];
- public static string PublicKeyPath = AppSettingsHelper.Configuration["NHBridge:PublicKeyPath"];
- /// <summary>
- /// 接收报文返回requsetBody和使用base64解析后的requsetBody以及缴费中心传送的签名
- /// </summary>
- /// <param name="request">请求报文</param>
- /// <returns></returns>
- public Dictionary<string, string> requestBodyOfBase64(string request)
- {
- logger.Info($"收到的报文:{request}");
- Dictionary<string, string> requestMap = new Dictionary<string, string>
- {
- //使用base64解析完成后的requsetBody
- { "requsetBodyOfDecoded", "" },
- //解析前的requsetBody
- { "requsetBody", "" },
- //获取缴费中心传送过来的签名
- { "signatureString", "" }
- };
- try
- {
- string signatureString = request.Substring(0, request.IndexOf("||"));
- string requsetBody = request.Substring(signatureString.Length + 2);
- string requsetBodyOfDecoded = Base64Util.DecodeData(requsetBody);
- logger.Info($"加签串:{signatureString},base64加密报文:{requsetBody},解密的报文:{requsetBodyOfDecoded}");
- if (!string.IsNullOrWhiteSpace(signatureString) && !string.IsNullOrWhiteSpace(requsetBody) && !string.IsNullOrWhiteSpace(requsetBodyOfDecoded))
- {
- requestMap["requsetBodyOfDecoded"] = requsetBodyOfDecoded;
- requestMap["requsetBody"] = requsetBody;
- requestMap["signatureString"] = signatureString;
- }
- else
- {
- logger.Error("非正常格式请求报文,请检查报文并联系发送方。");
- }
- }
- catch (Exception e)
- {
- logger.Error($"解析报文信息异常,报错信息:{e.Message},报错堆栈:{e.StackTrace}");
- }
- return requestMap;
- }
- /// <summary>
- /// 解析报文,验证签名
- /// </summary>
- /// <param name="requestMap"></param>
- /// <returns></returns>
- public string verify_sign(Dictionary<string, string> requestMap)
- {
- //使用base64解析完成后的requsetBody
- string requsetBodyOfDecoded = requestMap["requsetBodyOfDecoded"];
- //解析前的requsetBody
- string requsetBody = requestMap["requsetBody"];
- //获取缴费中心传送过来的签名
- string signatureString = requestMap["signatureString"];
- //报文解析错误处理
- if (string.IsNullOrWhiteSpace(signatureString))
- {
- logger.Error("解析报文出错");
- return "";
- }
- //验签
- bool sign = read_cer_and_verify_sign(requsetBody, signatureString);
- //如果验签失败,处理
- //if (!sign) {
- //}
- return requsetBodyOfDecoded;
- }
- /// <summary>
- /// 读取cer并验证公钥签名
- /// </summary>
- /// <param name="requsetBody">json报文数据</param>
- /// <param name="signature">加签标识</param>
- /// <returns>成功:true,失败:false</returns>
- public bool read_cer_and_verify_sign(string requsetBody, string signature)
- {
- bool result = false;
- try
- {
- byte[] orgin = Encoding.UTF8.GetBytes((requsetBody));//json报文数据获得字节数据
- byte[] singedBase64 = Convert.FromBase64String((signature));//对加签部分进行base64解密操作
- RSACryptoServiceProvider tMerchantKey = GetPublicKey();//读取证书
- result = tMerchantKey.VerifyData(orgin, "SHA1", singedBase64);
- logger.Info($"验证签名的加签串:{signature},签名验证结果:{result}");
- return result;
- }
- catch (Exception ex)
- {
- logger.Error(ex, "验签失败!");
- return result;
- }
- }
- /// <summary>
- /// 加签名
- /// </summary>
- /// <param name="contentForSign">需加标签的字符串</param>
- /// <returns></returns>
- public string signWhithsha1withrsa(string contentForSign)
- {
- string result = "";
- try
- {
- //string filePath = rootPath + PFXPATH;
- //获取私钥
- RSACryptoServiceProvider tMerchantKey = GetPrivateKey();
- SHA1Managed tHash = new SHA1Managed();
- //将传递需要加签的字符串进行base64操作
- byte[] base64 = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(contentForSign)));
- byte[] tHashedData = tHash.ComputeHash(base64);
- //对其进行加签名
- byte[] tSigned = tMerchantKey.SignHash(tHashedData, "SHA1");
- result = Convert.ToBase64String(tSigned);
- return result;
- }
- catch (Exception ex)
- {
- logger.Error(ex, "加签失败!");
- return result;
- }
- }
- /// <summary>
- /// 获取返回报文数据,加签名及加密
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- public string GetResponseJson(string json)
- {
- logger.Info("查询结果原始报文数据:" + json);
- // 加签名以及加密
- string signatrue = signWhithsha1withrsa(json);
- string responseJson = signatrue + "||" + Base64Util.EncodeData(json);
- logger.Info("查询结果返回报文数据(报文加签且base64加密后):" + responseJson);
- return responseJson;
- }
- /// <summary>
- /// 获取私钥
- /// </summary>
- /// <returns></returns>
- private static RSACryptoServiceProvider GetPrivateKey()
- {
- try
- {
- //以读取路径的方式读取文件 path为存放证书路径
- var cer = new X509Certificate2(File.ReadAllBytes(PrivateKeyPath), keystore_password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
- //byte[] rawData = Resource._103881104410001;
- //byte[] rawData = returnbyte("d://103881104410001.pfx");
- //string file = "d://103881104410001.pfx";
- //var cer = new X509Certificate2(rawData, Resource.keystore_password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
- return (RSACryptoServiceProvider)cer.PrivateKey;
- }
- catch { throw; }
- }
- /// <summary>
- /// 获取公钥
- /// </summary>
- /// <returns></returns>
- private static RSACryptoServiceProvider GetPublicKey()
- {
- try
- {
- //以读取路径的方式读取文件 path为存放证书路径
- var cer = new X509Certificate2(File.ReadAllBytes(PublicKeyPath));
- //var cer = new X509Certificate2(Resource.TrustPayTest);
- return (RSACryptoServiceProvider)cer.PublicKey.Key;
- }
- catch { throw; }
- }
- }
- }
|