/// <summary> /// 验签 /// </summary> /// <param name="sign"></param> /// <returns></returns> public static string CheckSign(string message) { //获取非业务参数header对象的长度 HeadersInfo headersInfo = new HeadersInfo(); PropertyInfo[] propertyInfo = headersInfo.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); //截取第一个下划线'_'前的文本为消息头,最后一个下划线'_'后的文本为签名 string[] list = message.Split('_'); //判断长度是否合法 if (list.Length < propertyInfo.Length) { return(UtilityEnum.InspectionResult.Invalid.ToString()); } string messageHeader = list[0]; string timestamp = list[1]; //要验证的签名数据 string signature = list[list.Length - 1]; byte[] hashByteSignature = Convert.FromBase64String(signature); //查看消息头是否正确 if (messageHeader != ConfigurationManager.AppSettings["messageHeader"]) { return(UtilityEnum.InspectionResult.Invalid.ToString()); } //文本截取签名(含下划线'_')后,是已签名的数据 string buffer = message.Substring(0, message.Length - signature.Length - 1); byte[] fromBase64Buffer = Encoding.Unicode.GetBytes(buffer); //加载发送方的公钥进行验签 var rsa = new RSACryptoServiceProvider(); var publicXmlKey = File.ReadAllText(Path.Combine(ConfigurationManager.AppSettings["basePathToStoreClientKeys"], "ClientRSA.Pub")); rsa.FromXmlString(publicXmlKey); //MD5 mD5 = new MD5CryptoServiceProvider(); //rsa.VerifyData(hashByteSignature, mD5, Convert.FromBase64String(buffer)); //rsa.VerifyData(hashByteSignature, CryptoConfig.MapNameToOID("MD5"), Convert.FromBase64String(buffer)); //哈希算法:SHA1(160bit)、SHA256(256bit)、MD5(128bit) if (rsa.VerifyData(fromBase64Buffer, CryptoConfig.MapNameToOID("SHA1"), hashByteSignature)) { //判断timestamp是否超时 if (UtilityHelper.IsTimestampValidity(timestamp)) { return(UtilityEnum.InspectionResult.Timeout.ToString()); } } else { return(UtilityEnum.InspectionResult.Invalid.ToString()); } return(UtilityEnum.InspectionResult.Validity.ToString()); }
public RESTJson GetClientEncryptionKey([FromBody] LoginInfo loginInfo) { RESTJson result = new RESTJson(); //非业务参数(如:时间戳等) HeadersInfo headersInfo = new HeadersInfo(); //根据非业务参数和业务参数拼接字符串并按照首字母排序 Dictionary <string, object> dic = new Dictionary <string, object>(); dic = SignHelper <HeadersInfo> .ObjConvertDic(dic, headersInfo); dic = SignHelper <LoginInfo> .ObjConvertDic(dic, loginInfo); string str = SignHelper <string> .DicSortToString(dic); //使用请求方的私钥进行加密生成签名 string sign = ClientEncryptionHelper.privateToSign(str); //判空 if (string.IsNullOrEmpty(sign)) { result.ErrMsg = "生成报文失败"; return(result); } //使用接收方的公钥进行加密生成加密报文 string message = ServerEncryptionHelper.PubKeyEncryption(str += '_' + sign); if (!string.IsNullOrEmpty(message)) { result.ErrCode = 1; result.ErrMsg = "生成报文成功"; result.Data = message; } return(result); }