/// <summary> /// 对控件支付成功返回的结果信息中data域进行验签(控件端获取的应答信息) /// </summary> /// <param name="jsonData">json格式数据,例如:{"sign" : "J6rPLClQ64szrdXCOtV1ccOMzUmpiOKllp9cseBuRqJ71pBKPPkZ1FallzW18gyP7CvKh1RxfNNJ66AyXNMFJi1OSOsteAAFjF5GZp0Xsfm3LeHaN3j/N7p86k3B1GrSPvSnSw1LqnYuIBmebBkC1OD0Qi7qaYUJosyA1E8Ld8oGRZT5RR2gLGBoiAVraDiz9sci5zwQcLtmfpT5KFk/eTy4+W9SsC0M/2sVj43R9ePENlEvF8UpmZBqakyg5FO8+JMBz3kZ4fwnutI5pWPdYIWdVrloBpOa+N4pzhVRKD4eWJ0CoiD+joMS7+C0aPIEymYFLBNYQCjM0KV7N726LA==", "data" : "pay_result=success&tn=201602141008032671528&cert_id=68759585097"}</param> /// <param name="encoding"></param> /// <returns></returns> public static bool ValidateAppResponse(string jsonData, Encoding encoding) { log.Info("控件返回报文验签:[" + jsonData + "]"); //获取签名 Dictionary <string, object> data = SDKUtil.JsonToDictionary(jsonData); string stringData = (string)data["data"]; string signValue = (string)data["sign"]; Dictionary <string, string> dataMap = SDKUtil.parseQString(stringData, encoding); byte[] signByte = Convert.FromBase64String(signValue); byte[] signDigest = SecurityUtil.Sha1X16(stringData, encoding); string stringSignDigest = BitConverter.ToString(signDigest).Replace("-", "").ToLower(); log.Debug("sha1结果:[" + stringSignDigest + "]"); RSACryptoServiceProvider provider = CertUtil.GetValidateProviderFromPath(dataMap["cert_id"]); if (null == provider) { log.Error("未找到证书,无法验签,验签失败。"); return(false); } bool result = SecurityUtil.ValidateBySoft(provider, signByte, encoding.GetBytes(stringSignDigest)); if (result) { log.Info("验签成功"); } else { log.Info("验签失败"); } return(result); }
/// <summary> /// 验证签名 /// </summary> /// <param name="rspData"></param> /// <param name="encoder"></param> /// <returns></returns> public static bool Validate(Dictionary <string, string> rspData, Encoding encoding) { //获取签名 string signValue = rspData["signature"]; log.Info("签名原文:[" + signValue + "]"); byte[] signByte = Convert.FromBase64String(signValue); rspData.Remove("signature"); string stringData = SDKUtil.CreateLinkString(rspData, true, false); log.Info("排序串:[" + stringData + "]"); byte[] signDigest = SecurityUtil.Sha1X16(stringData, encoding); string stringSignDigest = BitConverter.ToString(signDigest).Replace("-", "").ToLower(); log.Debug("sha1结果:[" + stringSignDigest + "]"); RSACryptoServiceProvider provider = CertUtil.GetValidateProviderFromPath(rspData["certId"]); if (null == provider) { log.Error("未找到证书,无法验签,验签失败。"); return(false); } bool result = SecurityUtil.ValidateBySoft(provider, signByte, encoding.GetBytes(stringSignDigest)); if (result) { log.Info("验签成功"); } else { log.Info("验签失败"); } return(result); }
/// <summary> /// 对待签名数据计算签名并赋值certid,signature字段返回签名后的报文 /// </summary> /// <param name="reqData"></param> /// <param name="encoding">编码</param> /// <param name="certPath">证书路径</param> /// <param name="certPwd">证书密码</param> /// <returns></returns> public static void Sign(Dictionary <string, string> reqData, Encoding encoding, string certPath, string certPwd) { reqData["certId"] = CertUtil.GetSignCertId(certPath, certPwd); //将Dictionary信息转换成key1=value1&key2=value2的形式 string stringData = SDKUtil.CreateLinkString(reqData, true, false); log.Info("待签名排序串:[" + stringData + "]"); string stringSign = null; byte[] signDigest = SecurityUtil.Sha1X16(stringData, encoding); string stringSignDigest = BitConverter.ToString(signDigest).Replace("-", "").ToLower(); log.Info("sha1结果:[" + stringSignDigest + "]"); byte[] byteSign = SecurityUtil.SignBySoft(CertUtil.GetSignProviderFromPfx(certPath, certPwd), encoding.GetBytes(stringSignDigest)); stringSign = Convert.ToBase64String(byteSign); log.Info("签名结果:[" + stringSign + "]"); //设置签名域值 reqData["signature"] = stringSign; }
/// <summary> /// 证书方式签名(多证书时使用),指定证书路径。 /// </summary> /// <param name="reqData"></param> /// <param name="encoding">编码</param> /// <param name="certPath">证书路径</param> /// <param name="certPwd">证书密码</param> /// <returns></returns> public static void SignByCertInfo(Dictionary <string, string> reqData, string certPath, string certPwd, Encoding encoding) { if (!reqData.ContainsKey("signMethod")) { log.Error("signMethod must Not null"); return; } string signMethod = reqData["signMethod"]; if (!reqData.ContainsKey("version")) { log.Error("version must Not null"); return; } string version = reqData["version"]; if ("01".Equals(signMethod)) { reqData["certId"] = CertUtil.GetSignCertId(certPath, certPwd); //将Dictionary信息转换成key1=value1&key2=value2的形式 string stringData = SDKUtil.CreateLinkString(reqData, true, false, encoding); log.Info("待签名排序串:[" + stringData + "]"); if ("5.0.0".Equals(version)) { byte[] signDigest = SecurityUtil.Sha1(stringData, encoding); string stringSignDigest = SDKUtil.ByteArray2HexString(signDigest); log.Info("sha1结果:[" + stringSignDigest + "]"); byte[] byteSign = SecurityUtil.SignSha1WithRsa(CertUtil.GetSignKeyFromPfx(certPath, certPwd), encoding.GetBytes(stringSignDigest)); string stringSign = Convert.ToBase64String(byteSign); log.Info("5.0.0报文sha1RSA签名结果:[" + stringSign + "]"); //设置签名域值 reqData["signature"] = stringSign; } else { byte[] signDigest = SecurityUtil.Sha256(stringData, encoding); string stringSignDigest = SDKUtil.ByteArray2HexString(signDigest); log.Info("sha256结果:[" + stringSignDigest + "]"); byte[] byteSign = SecurityUtil.SignSha256WithRsa(CertUtil.GetSignKeyFromPfx(certPath, certPwd), encoding.GetBytes(stringSignDigest)); string stringSign = Convert.ToBase64String(byteSign); log.Info("5.1.0报文sha256RSA签名结果:[" + stringSign + "]"); //设置签名域值 reqData["signature"] = stringSign; } } else { log.Error("Error signMethod [" + signMethod + "] in SignByCertInfo. "); } }
/// <summary> /// 解密 /// </summary> /// <param name="dataString">原数据</param> /// <returns>解密结果</returns> public static byte[] decryptData(byte[] data) { try { return(CertUtil.GetSignProviderFromPfx().Decrypt(data, false)); } catch (Exception e) { log.Error("decryptData error: " + e.Message); return(new byte[0]); } }
///<summary> /// 加密 /// </summary> /// <returns></returns> public static byte[] encryptedData(byte[] encData, SDKConfig con) { try { byte[] enBytes = CertUtil.GetEncryptKey(con).Encrypt(encData, false); return(enBytes); } catch (Exception e) { log.Error("encryptedData error: " + e.Message); return(new byte[0]); } }
///// <summary> ///// 密码计算 ///// </summary> ///// <param name="aPin"></param> ///// <returns></returns> //private static byte[] pin2PinBlock(string aPin) //{ // int tTemp = 1; // int tPinLen = aPin.Length; // byte[] tByte = new byte[8]; // try // { // tByte[0] = (byte)Convert.ToInt32(tPinLen.ToString(), 10); // if (tPinLen % 2 == 0) // { // for (int i = 0; i < tPinLen; ) // { // string a = aPin.Substring(i, 2).Trim(); // tByte[tTemp] = (byte)Convert.ToInt32(a, 16); // if (i == (tPinLen - 2)) // { // if (tTemp < 7) // { // for (int x = (tTemp + 1); x < 8; x++) // { // tByte[x] = (byte)0xff; // } // } // } // tTemp++; // i = i + 2; // } // } // else // { // for (int i = 0; i < tPinLen - 1; ) // { // string a; // a = aPin.Substring(i, 2); // tByte[tTemp] = (byte)Convert.ToInt32(a, 16); // if (i == (tPinLen - 3)) // { // string b = aPin.Substring(tPinLen - 1) + "F"; // tByte[tTemp + 1] = (byte)Convert.ToInt32(b, 16); // if ((tTemp + 1) < 7) // { // for (int x = (tTemp + 2); x < 8; x++) // { // tByte[x] = (byte)0xff; // } // } // } // tTemp++; // i = i + 2; // } // } // } // catch (Exception e) // { // log.Error("pin2PinBlock error" + e.Message); // } // return tByte; //} ///// <summary> ///// 获取卡号密码pinblock计算 ///// </summary> ///// <param name="aPin"></param> ///// <param name="aCardNO"></param> ///// <returns></returns> //public static byte[] pin2PinBlockWithCardNO(string aPin, string aCardNO) //{ // byte[] tPinByte = pin2PinBlock(aPin); // if (aCardNO.Length == 11) // { // aCardNO = "00" + aCardNO; // } // else if (aCardNO.Length == 12) // { // aCardNO = "0" + aCardNO; // } // byte[] tPanByte = formatPan(aCardNO); // byte[] tByte = new byte[8]; // for (int i = 0; i < 8; i++) // { // tByte[i] = (byte)(tPinByte[i] ^ tPanByte[i]); // } // return tByte; //} ///// <summary> ///// 卡号计算 ///// </summary> ///// <param name="aPan"></param> ///// <returns></returns> //private static byte[] formatPan(string aPan) //{ // int tPanLen = aPan.Length; // byte[] tByte = new byte[8]; // int temp = tPanLen - 13; // try // { // tByte[0] = (byte)0x00; // tByte[1] = (byte)0x00; // for (int i = 2; i < 8; i++) // { // string a = aPan.Substring(temp, 2).Trim(); // tByte[i] = (byte)Convert.ToInt32(a, 16); // temp = temp + 2; // } // } // catch (Exception e) // { // log.Error("formatPan error:" + e.Message); // } // return tByte; //} ///<summary> /// 加密 /// </summary> /// <returns></returns> private static byte[] encryptedData(byte[] encData) { try { IBufferedCipher c = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding"); c.Init(true, new ParametersWithRandom(CertUtil.GetEncryptKey(), new SecureRandom())); return(c.DoFinal(encData)); } catch (Exception e) { log.Error("encryptedData error: " + e.Message); return(new byte[0]); } }
/// <summary> /// 解密,多证书 /// </summary> /// <param name="dataString">原字符串</param> /// <param name="encoding">编码</param> /// <returns>解密结果</returns> public static string DecryptData(string dataString, Encoding encoding, string certPath, string certPwd) { byte[] data = Convert.FromBase64String(dataString); data = decryptData(data, CertUtil.GetSignProviderFromPfx(certPath, certPwd)); return(encoding.GetString(data)); }
/// <summary> /// 解密 /// </summary> /// <param name="dataString">原字符串</param> /// <param name="encoding">编码</param> /// <returns>解密结果</returns> public static string DecryptData(string dataString, Encoding encoding, SDKConfig con) { byte[] data = Convert.FromBase64String(dataString); data = decryptData(data, CertUtil.GetSignProviderFromPfx(con)); return(encoding.GetString(data)); }
//获取敏感信息加密证书的物理序列号 public static String GetEncryptCertId() { return(CertUtil.GetEncryptCertId()); }
/// <summary> /// 获取应答报文中的加密公钥证书,并存储到本地,并备份原始证书。 /// 更新成功则返回1,无更新返回0,失败异常返回-1。 /// </summary> /// <param name="dic">Dictionary数据</param> /// <param name="encoding">编码</param> /// <returns>成功返回1,无更新返回0,失败异常返回-1</returns> public static int UpdateEncryptCert(Dictionary <string, string> dic, Encoding encoding) { if (!dic.ContainsKey("encryptPubKeyCert") || !dic.ContainsKey("certType")) { log.Error("encryptPubKeyCert or certType is null."); return(-1); } string strCert = dic["encryptPubKeyCert"]; string certType = dic["certType"]; X509Certificate x509Cert = CertUtil.GetPubKeyCert(strCert); if (x509Cert == null) { log.Error("从encryptPubKeyCert获取证书内容失败。"); return(-1); } if ("01".Equals(certType)) { if (!CertUtil.GetEncryptCertId().Equals(x509Cert.SerialNumber.ToString())) { // ID不同时进行本地证书更新操作 string localCertPath = SDKConfig.EncryptCert; string newLocalCertPath = SDKUtil.GenBackupName(localCertPath); // 1.将本地证书进行备份存储 try { System.IO.File.Copy(localCertPath, newLocalCertPath, true); } catch (Exception e) { log.Error("备份旧加密证书失败:", e); return(-1); } // 2.备份成功,进行新证书的存储 FileStream fs = null; try { fs = File.OpenWrite(localCertPath); Byte[] info = encoding.GetBytes(strCert); fs.Write(info, 0, info.Length); } catch (Exception e) { log.Error("写入新加密证书失败:", e); return(-1); } finally { if (fs != null) { fs.Close(); } } log.Info("save new encryptPubKeyCert success"); CertUtil.resetEncryptCertPublicKey(); return(1); } else { log.Info("加密公钥无更新。"); return(0); } } else if ("02".Equals(certType)) { log.Info("加密公钥无更新。"); return(0); } else { log.Error("unknown cerType:" + certType); return(-1); } }
/// <summary> /// 验证签名 /// </summary> /// <param name="rspData"></param> /// <param name="encoder"></param> /// <returns></returns> public static bool Validate(Dictionary <string, string> rspData, Encoding encoding) { if (!rspData.ContainsKey("version")) { log.Error("version is null, cannot validate signature."); return(false); } string version = rspData["version"]; if (!rspData.ContainsKey("signature")) { log.Error("signature is null, cannot validate signature."); return(false); } string signature = rspData["signature"]; string signMethod = null; if (rspData.ContainsKey("signMethod")) { signMethod = rspData["signMethod"]; } else if (!VERSION_1_0_0.Equals(version)) { log.Error("signMethod is null, cannot validate signature."); return(false); } bool result = false; if ("01".Equals(signMethod) || VERSION_1_0_0.Equals(version)) { log.Info("验签处理开始"); if (VERSION_5_0_0.Equals(version) || VERSION_1_0_0.Equals(version)) { string signValue = rspData["signature"]; log.Info("签名原文:[" + signValue + "]"); byte[] signByte = Convert.FromBase64String(signValue); rspData.Remove("signature"); string stringData = SDKUtil.CreateLinkString(rspData, true, false, encoding); log.Info("排序串:[" + stringData + "]"); byte[] signDigest = SecurityUtil.Sha1(stringData, encoding); string stringSignDigest = SDKUtil.ByteArray2HexString(signDigest); log.Debug("sha1结果:[" + stringSignDigest + "]"); AsymmetricKeyParameter key = CertUtil.GetValidateKeyFromPath(rspData["certId"]); if (null == key) { log.Error("未找到证书,无法验签,验签失败。"); return(false); } result = SecurityUtil.ValidateSha1WithRsa(key, signByte, encoding.GetBytes(stringSignDigest)); } else { string signValue = rspData["signature"]; log.Info("签名原文:[" + signValue + "]"); byte[] signByte = Convert.FromBase64String(signValue); rspData.Remove("signature"); string stringData = SDKUtil.CreateLinkString(rspData, true, false, encoding); log.Info("排序串:[" + stringData + "]"); byte[] signDigest = SecurityUtil.Sha256(stringData, encoding); string stringSignDigest = SDKUtil.ByteArray2HexString(signDigest); log.Debug("sha256结果:[" + stringSignDigest + "]"); string signPubKeyCert = rspData["signPubKeyCert"]; X509Certificate x509Cert = CertUtil.VerifyAndGetPubKey(signPubKeyCert); if (x509Cert == null) { log.Error("获取验签证书失败,无法验签,验签失败。"); return(false); } result = SecurityUtil.ValidateSha256WithRsa(x509Cert.GetPublicKey(), signByte, encoding.GetBytes(stringSignDigest)); } } else if ("11".Equals(signMethod) || "12".Equals(signMethod)) { return(ValidateBySecureKey(rspData, SDKConfig.SecureKey, encoding)); } else { log.Error("Error signMethod [" + signMethod + "], version [" + version + "] in Validate. "); return(false); } if (result) { log.Info("验签成功"); } else { log.Info("验签失败"); } return(result); }
/// <summary> /// 解密 /// </summary> /// <param name="dataString">原字符串</param> /// <param name="encoding">编码</param> /// <returns>解密结果</returns> public static string DecryptData(string dataString, Encoding encoding) { byte[] data = Convert.FromBase64String(dataString); data = decryptData(data, CertUtil.GetSignKeyFromPfx()); return(encoding.GetString(data)); }
//获取敏感信息加密证书的物理序列号 public static String GetEncryptCertId(SDKConfig con) { return(CertUtil.GetEncryptCertId(con)); }