public static bool ValidateBySecureKey(Dictionary <string, string> dictionary, string secureKey)
        {
            if (!dictionary.ContainsKey("signMethod") || !dictionary.ContainsKey("signature"))
            {
                return(false);
            }

            var result     = false;
            var signMethod = dictionary["signMethod"];

            if ("11" == signMethod)
            {
                var stringSign = dictionary["signature"];
                dictionary.Remove("signature");
                var stringData      = GetSignContent(dictionary, true, false);
                var strBeforeSha256 = stringData + "&" + SHA256.Compute(secureKey);
                var strAfterSha256  = SHA256.Compute(strBeforeSha256);
                result = stringSign == strAfterSha256;
            }
            else if ("12" == signMethod)
            {
                var stringSign = dictionary["signature"];
                dictionary.Remove("signature");
                var stringData   = GetSignContent(dictionary, true, false);
                var strBeforeSm3 = stringData + "&" + SM3.Compute(secureKey);
                var strAfterSm3  = SM3.Compute(strBeforeSm3);
                result = stringSign == strAfterSm3;
            }

            return(result);
        }
Пример #2
0
        public static void SignByCertInfo(Dictionary <string, string> reqData, string certId, AsymmetricKeyParameter parameters)
        {
            if (!reqData.ContainsKey("signMethod"))
            {
                throw new Exception("signMethod must Not null");
            }
            var signMethod = reqData["signMethod"];

            if (!reqData.ContainsKey("version"))
            {
                throw new Exception("version must Not null");
            }
            var version = reqData["version"];

            if ("01".Equals(signMethod))
            {
                reqData["certId"] = certId;

                var stringData       = GetSignContent(reqData, true, false);
                var stringSignDigest = SHA256.Compute(stringData);
                var stringSign       = SHA256WithRSA.SignData(stringSignDigest, parameters);

                //设置签名域值
                reqData["signature"] = stringSign;
            }
            else
            {
                throw new Exception("Error signMethod [" + signMethod + "] in SignByCertInfo. ");
            }
        }
Пример #3
0
        public static void SignBySecureKey(Dictionary <string, string> reqData, string secureKey)
        {
            if (!reqData.ContainsKey("signMethod"))
            {
                throw new Exception("signMethod must Not null");
            }
            var signMethod = reqData["signMethod"];

            var stringData = GetSignContent(reqData, true, false);

            if ("11".Equals(signMethod))
            {
                var strBeforeSha256 = stringData + "&" + SHA256.Compute(secureKey);
                var strAfterSha256  = SHA256.Compute(strBeforeSha256);
                //设置签名域值
                reqData["signature"] = strAfterSha256;
            }
            else if ("12".Equals(signMethod))
            {
                var strBeforeSm3 = stringData + "&" + SM3.Compute(secureKey);
                var strAfterSm3  = SM3.Compute(strBeforeSm3);
                //设置签名域值
                reqData["signature"] = strAfterSm3;
            }
            else
            {
                throw new Exception("Error signMethod [" + signMethod + "] in SignBySecureKey. ");
            }
        }
        public static void SignBySecureKey(Dictionary <string, string> dictionary, string secureKey)
        {
            if (!dictionary.ContainsKey("signMethod"))
            {
                throw new UnionPayException("signMethod must Not null");
            }

            var stringData = GetSignContent(dictionary, true, false);
            var signMethod = dictionary["signMethod"];

            if ("11" == signMethod)
            {
                var strBeforeSha256 = stringData + "&" + SHA256.Compute(secureKey);
                var strAfterSha256  = SHA256.Compute(strBeforeSha256);
                //设置签名域值
                dictionary["signature"] = strAfterSha256;
            }
            else if ("12" == signMethod)
            {
                var strBeforeSm3 = stringData + "&" + SM3.Compute(secureKey);
                var strAfterSm3  = SM3.Compute(strBeforeSm3);
                //设置签名域值
                dictionary["signature"] = strAfterSm3;
            }
            else
            {
                throw new UnionPayException("Error signMethod [" + signMethod + "] in SignBySecureKey. ");
            }
        }
        public static void SignByCertInfo(Dictionary <string, string> dictionary, string certId, ICipherParameters key)
        {
            if (!dictionary.ContainsKey("signMethod"))
            {
                throw new UnionPayException("signMethod must Not null");
            }

            if (!dictionary.ContainsKey("version"))
            {
                throw new UnionPayException("version must Not null");
            }

            var signMethod = dictionary["signMethod"];

            if ("01" == signMethod)
            {
                dictionary["certId"] = certId;

                var stringData       = GetSignContent(dictionary, true, false);
                var stringSignDigest = SHA256.Compute(stringData);
                var stringSign       = SHA256WithRSA.SignData(stringSignDigest, key);

                //设置签名域值
                dictionary["signature"] = stringSign;
            }
            else
            {
                throw new UnionPayException("Error signMethod [" + signMethod + "] in SignByCertInfo. ");
            }
        }
Пример #6
0
        public static bool ValidateBySecureKey(Dictionary <string, string> rspData, string secureKey)
        {
            if (!rspData.ContainsKey("signMethod") || !rspData.ContainsKey("signature"))
            {
                return(false);
            }
            var signMethod = rspData["signMethod"];

            var result = false;

            if ("11".Equals(signMethod))
            {
                var stringSign = rspData["signature"];
                rspData.Remove("signature");
                var stringData      = GetSignContent(rspData, true, false);
                var strBeforeSha256 = stringData + "&" + SHA256.Compute(secureKey);
                var strAfterSha256  = SHA256.Compute(strBeforeSha256);
                result = stringSign.Equals(strAfterSha256);
            }
            else if ("12".Equals(signMethod))
            {
                var stringSign = rspData["signature"];
                rspData.Remove("signature");
                var stringData   = GetSignContent(rspData, true, false);
                var strBeforeSm3 = stringData + "&" + SM3.Compute(secureKey);
                var strAfterSm3  = SM3.Compute(strBeforeSm3);
                result = stringSign.Equals(strAfterSm3);
            }
            else
            {
                return(false);
            }

            return(result);
        }
Пример #7
0
        private static string GetNPP10Sign(JDPayDictionary para, string algorithm, string salt)
        {
            if (para == null || para.Count == 0)
            {
                return(string.Empty);
            }

            var sb = new StringBuilder();

            foreach (var iter in para)
            {
                if (!string.IsNullOrEmpty(iter.Value) && iter.Key != "sign_type" && iter.Key != "sign_data" && iter.Key != "encrypt_type" && iter.Key != "encrypt_data" && iter.Key != "salt")
                {
                    sb.Append(iter.Key).Append("=").Append(iter.Value).Append("&");
                }
            }

            var sign = string.Empty;
            var data = sb.Remove(sb.Length - 1, 1).ToString() + salt;

            if ("SHA" == algorithm)
            {
                sign = SHA1.Compute(data).ToUpper();
            }
            else if ("SHA-256" == algorithm)
            {
                sign = SHA256.Compute(data).ToUpper();
            }

            return(sign);
        }
Пример #8
0
        public static string RSASign(string sourceSignString, AsymmetricKeyParameter privateKey)
        {
            var sha256SourceSignString = SHA256.Compute(sourceSignString);
            var newsks = RSA_ECB_PKCS1Padding.Encrypt(Encoding.UTF8.GetBytes(sha256SourceSignString), privateKey);

            return(Convert.ToBase64String(newsks, Base64FormattingOptions.InsertLineBreaks));
        }
Пример #9
0
 /// <summary>
 /// When text changes, update the hash to the output box
 /// </summary>
 private void InputTextBoxChanged(Object sender, EventArgs e)
 {
     Byte[] plainBytes = Encoding.UTF8.GetBytes(this.inputTextBox.Text);
     try
     {
         if (this.hashComboBox.SelectedIndex == 1)
         {
             this.OutputHash(MD5.Compute(plainBytes));
         }
         else if (this.hashComboBox.SelectedIndex == 2)
         {
             this.OutputHash(SHA1.Compute(plainBytes));
         }
         else if (this.hashComboBox.SelectedIndex == 3)
         {
             this.OutputHash(SHA256.Compute(plainBytes));
         }
         else if (this.hashComboBox.SelectedIndex == 4)
         {
             this.OutputHash(RMD160.Compute(plainBytes));
         }
         else
         {
             this.OutputHash(plainBytes);
         }
     }
     catch (InvalidOperationException)
     {
         this.outputTextBox.Text = "[ERROR: FIPS 140-2 compliance]";
     }
 }
Пример #10
0
        public void TestSha256()
        {
            //实测identityserver4.models下的SHA256计算结果与Meiyu.common下的SHA256不同
            var sha    = SHA256.Compute("secret");
            var is4sha = "secret".Sha256();

            Assert.Equal("K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=", is4sha);
        }
Пример #11
0
        public static bool RSACheckContent(string content, string sign, AsymmetricKeyParameter publicKey)
        {
            var sha256SourceSignString = SHA256.Compute(content);
            var decryptArr             = RSA_ECB_PKCS1Padding.Decrypt(Convert.FromBase64String(sign), publicKey);
            var decrypStr = Encoding.UTF8.GetString(decryptArr);

            return(sha256SourceSignString.Equals(decrypStr));
        }
Пример #12
0
        public static bool RSACheckContent(string content, string sign, ICipherParameters parameters)
        {
            var sha256SourceSignString = SHA256.Compute(content);
            var decryptArr             = Decrypt(sign, parameters);
            var decrypStr = Encoding.UTF8.GetString(decryptArr);

            return(sha256SourceSignString == decrypStr);
        }
Пример #13
0
        public static string RSASign(SortedDictionary <string, string> dic, ICipherParameters parameters)
        {
            var sourceSignString       = GetSignContent(dic);
            var sha256SourceSignString = SHA256.Compute(sourceSignString);
            var newsks = Encrypt(sha256SourceSignString, parameters);

            return(Convert.ToBase64String(newsks, Base64FormattingOptions.InsertLineBreaks));
        }
Пример #14
0
        public async Task <T> ExecuteAsync <T>(IJDPayRequest <T> request) where T : JDPayResponse
        {
            // 字典排序
            var sortedTxtParams = new JDPayDictionary(request.GetParameters());

            var content = BuildEncryptXml(request, sortedTxtParams);

            Logger?.LogTrace(0, "Request:{content}", content);

            using (var client = ClientFactory.CreateClient(JDPayOptions.DefaultClientName))
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(), content);

                Logger?.LogTrace(1, "Response:{content}", body);

                var parser = new JDPayXmlParser <T>();
                var rsp    = parser.Parse(JDPayUtility.FotmatXmlString(body));
                if (!string.IsNullOrEmpty(rsp.Encrypt))
                {
                    var encrypt          = rsp.Encrypt;
                    var base64EncryptStr = Encoding.UTF8.GetString(Convert.FromBase64String(encrypt));
                    var reqBody          = JDPaySecurity.DecryptECB(base64EncryptStr, Options.DesKeyBase64);
                    Logger?.LogTrace(2, "Encrypt Content:{body}", reqBody);

                    var reqBodyDoc = new XmlDocument()
                    {
                        XmlResolver = null
                    };
                    reqBodyDoc.LoadXml(reqBody);

                    var sign     = JDPayUtility.GetValue(reqBodyDoc, "sign");
                    var rootNode = reqBodyDoc.SelectSingleNode("jdpay");
                    var signNode = rootNode.SelectSingleNode("sign");
                    rootNode.RemoveChild(signNode);

                    var reqBodyStr = JDPayUtility.ConvertXmlToString(reqBodyDoc);
                    var xmlh       = rsp.Body.Substring(0, rsp.Body.IndexOf("<jdpay>"));
                    if (!string.IsNullOrEmpty(xmlh))
                    {
                        reqBodyStr = reqBodyStr.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlh);
                    }
                    var sha256SourceSignString = SHA256.Compute(reqBodyStr);
                    var decryptByte            = RSA_ECB_PKCS1Padding.Decrypt(Convert.FromBase64String(sign), Options.PublicKey);
                    var decryptStr             = JDPaySecurity.BytesToString(decryptByte);
                    if (sha256SourceSignString == decryptStr)
                    {
                        rsp         = parser.Parse(reqBody);
                        rsp.Encrypt = encrypt;
                    }
                    else
                    {
                        throw new Exception("sign check fail: check Sign and Data Fail!");
                    }
                }
                return(rsp);
            }
        }
Пример #15
0
        private void BuildParams <TModel, TResponse>(BaseRequest <TModel, TResponse> request)
        {
            //request.Add("version", _unionPayOptions.Version);
            //request.Add("encoding", _unionPayOptions.Encoding);
            //request.Add("bizType", _unionPayOptions.BizType);
            //request.Add("txnTime", _unionPayOptions.TxnTime);
            //request.Add("backUrl", _unionPayOptions.BackUrl);
            //request.Add("currencyCode", _unionPayOptions.CurrencyCode);
            //request.Add("txnType", _unionPayOptions.TxnType);
            //request.Add("txnSubType", _unionPayOptions.TxnSubType);
            //request.Add("accessType", _unionPayOptions.AccessType);
            //request.Add("frontUrl", _unionPayOptions.FrontUrl);
            //request.Add("signMethod", _unionPayOptions.SignMethod);
            //request.Add("channelType", _unionPayOptions.ChannelType);
            //request.Add("merId", _unionPayOptions.MerId);
            //request.Add("certId", SignCertificate.certId);

            request.Add("version", "5.1.0");
            request.Add("encoding", "UTF-8");
            request.Add("txnType", "01");
            request.Add("txnSubType", "01");
            request.Add("bizType", "000201");
            request.Add("signMethod", "01");
            request.Add("channelType", "08");
            request.Add("accessType", "0");
            request.Add("frontUrl", "http://localhost:8080/demo/api_02_b2b/FrontRcvResponse.aspx");
            request.Add("backUrl", "http://222.222.222.222:8080/demo/api_02_b2b/BackRcvResponse.aspx");
            request.Add("currencyCode", "156");
            request.Add("payTimeout", "20201106095402");
            request.Add("merId", "777290058110048");
            request.Add("orderId", "20201106093901185");
            request.Add("txnTime", "20201106093901");
            request.Add("txnAmt", "1000");
            request.Add("riskRateInfo", "{commodityName=测试商品名称}");
            request.Add("certId", "69629715588");
            var strData = request.ToUrl();


            //UnionPayUntil.Sign();
            //var signDigest = SecurityUtil.Sha256(strData, System.Text.Encoding.UTF8);
            //var stringSignDigest = BitConverter.ToString(signDigest).Replace("-", "").ToLower();

            //string stringSign = Convert.ToBase64String(byteSign);

            var stringSignDigest = SHA256.Compute(strData);
            var strSign          = UnionPayUntil.SignSha256WithRsa(stringSignDigest, SignCertificate.key);

            request.Add("signature", strSign);

            request.RequestUrl = _unionPayOptions.BaseUrl + request.RequestUrl;
        }
Пример #16
0
        private static string GetNPP10Sign(string content, string algorithm, string salt)
        {
            var sign = string.Empty;

            var data = content + salt;

            if ("SHA" == algorithm)
            {
                sign = SHA1.Compute(data);
            }
            else if ("SHA-256" == algorithm)
            {
                sign = SHA256.Compute(data);
            }

            return(sign);
        }
Пример #17
0
        private T DecryptResponseXml <T>(string xml) where T : JdPayNotifyResponse
        {
            var entity = JdPayUtil.Deserialize <T>(xml);

            if (!string.IsNullOrEmpty(entity?.Encrypt))
            {
                var key = Convert.FromBase64String(Options.DesKey);
                var base64EncryptStr = Encoding.UTF8.GetString(Convert.FromBase64String(entity.Encrypt));
                var reqBody          = DES3.DecryptECB(key, base64EncryptStr);

                var reqBodyDoc = new XmlDocument();
                reqBodyDoc.LoadXml(reqBody);

                var inputSign = JdPayUtil.GetValue(reqBodyDoc, "sign");
                var jdpayRoot = reqBodyDoc.SelectSingleNode("jdpay");
                var signNode  = jdpayRoot.SelectSingleNode("sign");
                jdpayRoot.RemoveChild(signNode);

                var reqBodyStr = JdPayUtil.ConvertXmlToString(reqBodyDoc);
                var xmlh       = xml.Substring(0, xml.IndexOf("<jdpay>"));
                if (!string.IsNullOrEmpty(xmlh))
                {
                    reqBodyStr = reqBodyStr.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlh);
                }
                var sha256SourceSignString = SHA256.Compute(reqBodyStr);
                var decryptByte            = JdPaySignature.Decrypt(inputSign, RSAPublicParameters);
                var decryptStr             = DES3.BytesToString(decryptByte);
                if (sha256SourceSignString == decryptStr)
                {
                    entity = JdPayUtil.Deserialize <T>(reqBody);
                }
                else
                {
                    throw new Exception("sign check fail: check Sign and Data Fail!");
                }

                entity.Body = reqBody;
            }
            else
            {
                entity.Body = xml;
            }
            return(entity);
        }
        public static bool Validate(Dictionary <string, string> dictionary, X509Certificate rootCert, X509Certificate middleCert, string secureKey, bool ifValidateCNName)
        {
            if (dictionary == null)
            {
                return(false);
            }

            if (!dictionary.ContainsKey("signMethod") || !dictionary.ContainsKey("signature") || !dictionary.ContainsKey("version"))
            {
                return(false);
            }

            var signMethod = dictionary["signMethod"];
            var result     = false;

            if ("01" == signMethod)
            {
                var signValue = dictionary["signature"];
                dictionary.Remove("signature");

                var stringData       = GetSignContent(dictionary, true, false);
                var stringSignDigest = SHA256.Compute(stringData);
                var signPubKeyCert   = dictionary["signPubKeyCert"];

                var cert = VerifyAndGetPubKey(signPubKeyCert, rootCert, middleCert, ifValidateCNName);
                if (cert == null)
                {
                    return(false);
                }

                result = SHA256WithRSA.VerifyData(stringSignDigest, signValue, cert.GetPublicKey());
            }
            else if ("11" == signMethod || "12" == signMethod)
            {
                return(ValidateBySecureKey(dictionary, secureKey));
            }
            else
            {
                return(false);
            }

            return(result);
        }
Пример #19
0
        private string GetEncryptXmlContent <T>(IJdPayRequest <T> request, JdPayDictionary dic) where T : JdPayResponse
        {
            var xmldoc = JdPayUtil.SortedDictionary2AllXml(dic);
            var smlStr = JdPayUtil.ConvertXmlToString(xmldoc);
            var sha256SourceSignString = SHA256.Compute(smlStr);
            var encyptBytes            = JdPaySignature.Encrypt(sha256SourceSignString, RSAPrivateParameters);
            var sign    = Convert.ToBase64String(encyptBytes, Base64FormattingOptions.InsertLineBreaks);
            var data    = smlStr.Replace("</jdpay>", "<sign>" + sign + "</sign></jdpay>");
            var encrypt = DES3.EncryptECB(DesKey, data);
            // 字典排序
            var reqdic = new JdPayDictionary
            {
                { VERSION, request.GetApiVersion() },
                { MERCHANT, Options.Merchant },
                { ENCRYPT, Convert.ToBase64String(Encoding.UTF8.GetBytes(encrypt)) }
            };

            return(JdPayUtil.SortedDictionary2XmlStr(reqdic));
        }
Пример #20
0
        private string BuildEncryptXml <T>(IJDPayRequest <T> request, JDPayDictionary dic) where T : JDPayResponse
        {
            var xmldoc = JDPayUtility.SortedDictionary2AllXml(dic);
            var smlStr = JDPayUtility.ConvertXmlToString(xmldoc);
            var sha256SourceSignString = SHA256.Compute(smlStr);
            var encyptBytes            = RSA_ECB_PKCS1Padding.Encrypt(Encoding.UTF8.GetBytes(sha256SourceSignString), PrivateKey);
            var sign    = Convert.ToBase64String(encyptBytes, Base64FormattingOptions.InsertLineBreaks);
            var data    = smlStr.Replace("</jdpay>", "<sign>" + sign + "</sign></jdpay>");
            var encrypt = JDPaySecurity.EncryptECB(data, DesKey);
            // 字典排序
            var reqdic = new JDPayDictionary
            {
                { VERSION, request.GetApiVersion() },
                { MERCHANT, Options.Merchant },
                { ENCRYPT, Convert.ToBase64String(Encoding.UTF8.GetBytes(encrypt)) }
            };

            return(JDPayUtility.SortedDictionary2XmlStr(reqdic));
        }
Пример #21
0
        public static bool Validate(Dictionary <string, string> rspData, string secureKey)
        {
            if (!rspData.ContainsKey("signMethod") || !rspData.ContainsKey("signature") || !rspData.ContainsKey("version"))
            {
                return(false);
            }

            var signMethod = rspData["signMethod"];
            var version    = rspData["version"];
            var result     = false;

            if ("01".Equals(signMethod))
            {
                var signValue = rspData["signature"];
                var signByte  = Convert.FromBase64String(signValue);
                rspData.Remove("signature");
                var stringData       = GetSignContent(rspData, true, false);
                var stringSignDigest = SHA256.Compute(stringData);

                var signPubKeyCert = rspData["signPubKeyCert"];
                var x509Cert       = VerifyAndGetPubKey(signPubKeyCert);
                if (x509Cert == null)
                {
                    return(false);
                }
                result = ValidateSha256WithRsa(x509Cert.GetPublicKey(), signByte, Encoding.UTF8.GetBytes(stringSignDigest));
            }
            else if ("11".Equals(signMethod) || "12".Equals(signMethod))
            {
                return(ValidateBySecureKey(rspData, secureKey));
            }
            else
            {
                return(false);
            }
            return(result);
        }
Пример #22
0
 /// <summary>
 /// When text changes, update the hash to the output box
 /// </summary>
 private void InputTextBoxChanged(Object sender, EventArgs e)
 {
     Byte[] plainBytes = Encoding.UTF8.GetBytes(this.inputTextBox.Text);
     if (this.hashComboBox.SelectedIndex == 1)
     {
         this.OutputHash(MD5.Compute(plainBytes));
     }
     else if (this.hashComboBox.SelectedIndex == 2)
     {
         this.OutputHash(SHA1.Compute(plainBytes));
     }
     else if (this.hashComboBox.SelectedIndex == 3)
     {
         this.OutputHash(SHA256.Compute(plainBytes));
     }
     else if (this.hashComboBox.SelectedIndex == 4)
     {
         this.OutputHash(RMD160.Compute(plainBytes));
     }
     else
     {
         this.OutputHash(plainBytes);
     }
 }
Пример #23
0
        public async Task <T> ExecuteAsync <T>(HttpRequest request) where T : JDPayNotifyResponse
        {
            if (request.HasFormContentType)
            {
                var parameters = await GetParametersAsync(request);

                var query = HttpClientEx.BuildQuery(parameters);
                Logger.LogInformation(0, "Request:{query}", query);

                var parser = new JDPayDictionaryParser <T>();
                var rsp    = parser.Parse(parameters);

                CheckNotifySign(rsp.Parameters, PrivateKey);
                return(rsp);
            }
            else if (request.HasTextXmlContentType())
            {
                var body = await new StreamReader(request.Body).ReadToEndAsync();
                Logger.LogInformation(0, "Request:{body}", body);

                var parser = new JDPayXmlParser <T>();
                var rsp    = parser.Parse(JDPayUtility.FotmatXmlString(body));
                if (!string.IsNullOrEmpty(rsp.Encrypt))
                {
                    var encrypt          = rsp.Encrypt;
                    var base64EncryptStr = Encoding.UTF8.GetString(Convert.FromBase64String(encrypt));
                    var reqBody          = DES3.DecryptECB(base64EncryptStr, DesKey);
                    Logger.LogInformation(1, "Encrypt Content:{body}", reqBody);

                    var reqBodyDoc = new XmlDocument();
                    reqBodyDoc.LoadXml(reqBody);

                    var sign     = JDPayUtility.GetValue(reqBodyDoc, "sign");
                    var rootNode = reqBodyDoc.SelectSingleNode("jdpay");
                    var signNode = rootNode.SelectSingleNode("sign");
                    rootNode.RemoveChild(signNode);

                    var reqBodyStr = JDPayUtility.ConvertXmlToString(reqBodyDoc);
                    var xmlh       = rsp.Body.Substring(0, rsp.Body.IndexOf("<jdpay>"));
                    if (!string.IsNullOrEmpty(xmlh))
                    {
                        reqBodyStr = reqBodyStr.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlh);
                    }
                    var sha256SourceSignString = SHA256.Compute(reqBodyStr);
                    var decryptByte            = RSA_ECB_PKCS1Padding.Decrypt(Convert.FromBase64String(sign), PublicKey);
                    var decryptStr             = DES3.BytesToString(decryptByte);
                    if (sha256SourceSignString == decryptStr)
                    {
                        rsp         = parser.Parse(reqBody);
                        rsp.Encrypt = encrypt;
                    }
                    else
                    {
                        throw new Exception("sign check fail: check Sign and Data Fail!");
                    }
                }
                return(rsp);
            }
            else
            {
                throw new Exception("sign check fail: check Sign and Data Fail!");
            }
        }
Пример #24
0
        /// <summary>
        /// Computes and shows the crypto results.
        /// </summary>
        private void TestAllAlgorithms()
        {
            /**
             * Input length is 17 chars but 19 bytes.
             */
            String input = "Hello to € World!";

            /**
             * Arrays for padding testing.
             */
            Byte[] pb = new Byte[12] {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
            };
            Byte[] nb = new Byte[12] {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
            };

            /**
             * Test PKCS#7 padding.
             */
            Byte[] pp = PKCS7.Pad(pb, 8);
            Byte[] pu = PKCS7.Unpad(pp);
            //
            this.outputBox.Text += "PKCS#7 padded: " + BytesToString(pp) + "\n";
            this.outputBox.Text += "PKCS#7 unpadded: " + BytesToString(pu) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test zero byte padding.
             */
            Byte[] np = ZEROS.Pad(nb, 8);
            Byte[] nu = ZEROS.Unpad(np);
            //
            this.outputBox.Text += "Zero byte padded: " + BytesToString(np) + "\n";
            this.outputBox.Text += "Zero byte unpadded: " + BytesToString(nu) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Text to bytes conversion from input.
             */
            Byte[] utf8Bytes = Encoding.UTF8.GetBytes(input);
            Byte[] ubeBytes  = Encoding.BigEndianUnicode.GetBytes(input);
            Byte[] uleBytes  = Encoding.Unicode.GetBytes(input);
            //
            this.outputBox.Text += "UTF-16 BE bytes: " + BytesToString(ubeBytes) + "\n";
            this.outputBox.Text += "UTF-16 LE bytes: " + BytesToString(uleBytes) + "\n";
            this.outputBox.Text += "UTF-8 bytes: " + BytesToString(utf8Bytes) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test base16 encoding.
             */
            String b16e = Base16.Encode(utf8Bytes);

            Byte[] b16d = Base16.Decode(b16e);
            //
            this.outputBox.Text += "Base16 encoded in UTF-8: " + b16e + "\n";
            this.outputBox.Text += "Base16 decoded in UTF-8: " + Encoding.UTF8.GetString(b16d) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test base64 encoding.
             */
            String b64e = Base64.Encode(utf8Bytes);

            Byte[] b64d = Base64.Decode(b64e);
            //
            this.outputBox.Text += "Base64 encoded in UTF-8: " + b64e + "\n";
            this.outputBox.Text += "Base64 decoded in UTF-8: " + Encoding.UTF8.GetString(b64d) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test generating GUID's.
             */
            String guid1 = GUID.Create();
            String guid2 = GUID.Create();
            String guid3 = GUID.Create();

            //
            this.outputBox.Text += "Generated GUID 1: " + guid1 + "\n";
            this.outputBox.Text += "Generated GUID 2: " + guid2 + "\n";
            this.outputBox.Text += "Generated GUID 3: " + guid3 + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test ROT13 encoding.
             */
            Byte[] r13e = ROT13.Encode(utf8Bytes);
            Byte[] r13d = ROT13.Decode(r13e);
            //
            this.outputBox.Text += "ROT13 encrypted in UTF-8: " + Encoding.UTF8.GetString(r13e) + "\n";
            this.outputBox.Text += "ROT13 decrypted in UTF-8: " + Encoding.UTF8.GetString(r13d) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test MD5 with one official test vector and custom input.
             * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/
             */
            Byte[] md5tv   = MD5.Compute(new Byte[0]);
            Byte[] md5utf8 = MD5.Compute(utf8Bytes);
            Byte[] md5key  = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] md5hmac = MD5.ComputeHMAC(md5key, utf8Bytes);
            //
            this.outputBox.Text += "MD5 from otv is ok: " + (Base16.Encode(md5tv) == "d41d8cd98f00b204e9800998ecf8427e").ToString() + "\n";
            this.outputBox.Text += "MD5 HMAC in UTF-8: " + Base16.Encode(md5hmac) + "\n";
            this.outputBox.Text += "MD5 in UTF-8: " + Base16.Encode(md5utf8) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test RIPEMD-160 with one official test vector and custom input.
             * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/
             */
            Byte[] rmd160tv   = RMD160.Compute(new Byte[0]);
            Byte[] rmd160utf8 = RMD160.Compute(utf8Bytes);
            Byte[] rmd160key  = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] rmd160hmac = RMD160.ComputeHMAC(rmd160key, utf8Bytes);
            //
            this.outputBox.Text += "RIPEMD-160 from otv is ok: " + (Base16.Encode(rmd160tv) == "9c1185a5c5e9fc54612808977ee8f548b2258d31").ToString() + "\n";
            this.outputBox.Text += "RIPEMD-160 HMAC in UTF-8: " + Base16.Encode(rmd160hmac) + "\n";
            this.outputBox.Text += "RIPEMD-160 in UTF-8: " + Base16.Encode(rmd160utf8) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test SHA-1 with one official test vector and custom input.
             * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/
             */
            Byte[] sha1tv   = SHA1.Compute(new Byte[0]);
            Byte[] sha1utf8 = SHA1.Compute(utf8Bytes);
            Byte[] sha1key  = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] sha1hmac = SHA1.ComputeHMAC(sha1key, utf8Bytes);
            //
            this.outputBox.Text += "SHA-1 from otv is ok: " + (Base16.Encode(sha1tv) == "da39a3ee5e6b4b0d3255bfef95601890afd80709").ToString() + "\n";
            this.outputBox.Text += "SHA-1 HMAC in UTF-8: " + Base16.Encode(sha1hmac) + "\n";
            this.outputBox.Text += "SHA-1 in UTF-8: " + Base16.Encode(sha1utf8) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test SHA-256 with one official test vector and custom input.
             * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/
             */
            Byte[] sha256tv   = SHA256.Compute(new Byte[0]);
            Byte[] sha256utf8 = SHA256.Compute(utf8Bytes);
            Byte[] sha256key  = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] sha256hmac = SHA256.ComputeHMAC(sha256key, utf8Bytes);
            //
            this.outputBox.Text += "SHA-256 from otv is ok: " + (Base16.Encode(sha256tv) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855").ToString() + "\n";
            this.outputBox.Text += "SHA-256 HMAC in UTF-8: " + Base16.Encode(sha256hmac) + "\n";
            this.outputBox.Text += "SHA-256 in UTF-8: " + Base16.Encode(sha256utf8) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test ARC4 with one official test vector and custom input.
             * Vectors from: http://reikon.us/arc4
             */
            Byte[] arc4tvk = Base16.Decode("0123456789abcdef");
            Byte[] arc4tvt = Base16.Decode("0123456789abcdef");
            Byte[] arc4tve = ARC4.Encrypt(arc4tvk, arc4tvt);
            Byte[] arc4tvd = ARC4.Decrypt(arc4tvk, arc4tve);
            //
            Byte[] arc4k = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] arc4e = ARC4.Encrypt(arc4k, utf8Bytes);
            Byte[] arc4d = ARC4.Decrypt(arc4k, arc4e);
            //
            this.outputBox.Text += "ARC4 otv encrypted is ok: " + (Base16.Encode(arc4tve) == "75b7878099e0c596") + "\n";
            this.outputBox.Text += "ARC4 otv decrypted is ok: " + (Base16.Encode(arc4tvd) == "0123456789abcdef") + "\n";
            this.outputBox.Text += "ARC4 encrypted in UTF-8: " + Base16.Encode(arc4e) + "\n";
            this.outputBox.Text += "ARC4 decrypted in UTF-8: " + Encoding.UTF8.GetString(arc4d) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test XXTEA with one official test vector and custom input.
             * Vectors from: http://www.crypt.co.za/post/27
             */
            Byte[] xxttvk = Base16.Decode("9e3779b99b9773e9b979379e6b695156");
            Byte[] xxttvt = Base16.Decode("0102040810204080fffefcf8f0e0c080");
            Byte[] xxttve = XXTEA.Encrypt(xxttvk, xxttvt);
            Byte[] xxttvd = XXTEA.Decrypt(xxttvk, xxttve);
            //
            Byte[] xxteak = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] xxteae = XXTEA.Encrypt(xxteak, PKCS7.Pad(utf8Bytes, 4));
            Byte[] xxtead = PKCS7.Unpad(XXTEA.Decrypt(xxteak, xxteae));
            //
            this.outputBox.Text += "XXTEA otv encrypted is ok: " + (Base16.Encode(xxttve) == "01b815fd2e4894d13555da434c9d868a") + "\n";
            this.outputBox.Text += "XXTEA otv decrypted is ok: " + (Base16.Encode(xxttvd) == "0102040810204080fffefcf8f0e0c080") + "\n";
            this.outputBox.Text += "XXTEA encrypted in UTF-8: " + Base16.Encode(xxteae) + "\n";
            this.outputBox.Text += "XXTEA decrypted in UTF-8: " + Encoding.UTF8.GetString(xxtead) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test AES-128 with one official test vector and custom input.
             * Vectors from: http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf
             */
            Byte[] aes128tvk = new Byte[16] {
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
            };
            Byte[] aes128tvt = new Byte[16] {
                0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
            };
            Byte[] aes128tve = AES.Encrypt(aes128tvk, aes128tvt, OperationMode.ECB, null); // No padding needed.
            Byte[] aes128tvd = AES.Decrypt(aes128tvk, aes128tve, OperationMode.ECB, null); // No padding needed.
            //
            Byte[] aes128k = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] aes128e = AES.Encrypt(aes128k, PKCS7.Pad(utf8Bytes, 16), OperationMode.ECB, null);
            Byte[] aes128d = PKCS7.Unpad(AES.Decrypt(aes128k, aes128e, OperationMode.ECB, null));
            //
            this.outputBox.Text += "AES-128 otv encrypted is ok: " + (Base16.Encode(aes128tve) == "69c4e0d86a7b0430d8cdb78070b4c55a") + "\n";
            this.outputBox.Text += "AES-128 otv decrypted is ok: " + (Base16.Encode(aes128tvd) == "00112233445566778899aabbccddeeff") + "\n";
            this.outputBox.Text += "AES-128 (ECB mode) encrypted in UTF-8: " + Base16.Encode(aes128e) + "\n";
            this.outputBox.Text += "AES-128 (ECB mode) decrypted in UTF-8: " + Encoding.UTF8.GetString(aes128d) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test AES-192 with one official test vector and custom input.
             * Vectors from: http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf
             */
            Byte[] aes192tvk = new Byte[24] {
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17
            };
            Byte[] aes192tvt = new Byte[16] {
                0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
            };
            Byte[] aes192tve = AES.Encrypt(aes192tvk, aes192tvt, OperationMode.ECB, null); // No padding needed.
            Byte[] aes192tvd = AES.Decrypt(aes192tvk, aes192tve, OperationMode.ECB, null); // No padding needed.
            //
            Byte[] aes192i = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] aes192k = Encoding.UTF8.GetBytes("123456789012345678901234");
            Byte[] aes192e = AES.Encrypt(aes192k, PKCS7.Pad(utf8Bytes, 16), OperationMode.CBC, aes192i);
            Byte[] aes192d = PKCS7.Unpad(AES.Decrypt(aes192k, aes192e, OperationMode.CBC, aes192i));
            //
            this.outputBox.Text += "AES-192 otv encrypted is ok: " + (Base16.Encode(aes192tve) == "dda97ca4864cdfe06eaf70a0ec0d7191") + "\n";
            this.outputBox.Text += "AES-192 otv decrypted is ok: " + (Base16.Encode(aes192tvd) == "00112233445566778899aabbccddeeff") + "\n";
            this.outputBox.Text += "AES-192 (CBC mode) encrypted in UTF-8: " + Base16.Encode(aes192e) + "\n";
            this.outputBox.Text += "AES-192 (CBC mode) decrypted in UTF-8: " + Encoding.UTF8.GetString(aes192d) + "\n";
            this.outputBox.Text += "\n";

            /**
             * Test AES-256 with one official test vector and custom input.
             * Vectors from: http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf
             */
            Byte[] aes256tvk = new Byte[32] {
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
            };
            Byte[] aes256tvt = new Byte[16] {
                0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
            };
            Byte[] aes256tve = AES.Encrypt(aes256tvk, aes256tvt, OperationMode.ECB, null); // No padding needed.
            Byte[] aes256tvd = AES.Decrypt(aes256tvk, aes256tve, OperationMode.ECB, null); // No padding needed.
            //
            Byte[] aes256i = Encoding.UTF8.GetBytes("1234567890123456");
            Byte[] aes256k = Encoding.UTF8.GetBytes("12345678901234561234567890123456");
            Byte[] aes256e = AES.Encrypt(aes256k, PKCS7.Pad(utf8Bytes, 16), OperationMode.CBC, aes256i);
            Byte[] aes256d = PKCS7.Unpad(AES.Decrypt(aes256k, aes256e, OperationMode.CBC, aes256i));
            //
            this.outputBox.Text += "AES-256 otv encrypted is ok: " + (Base16.Encode(aes256tve) == "8ea2b7ca516745bfeafc49904b496089") + "\n";
            this.outputBox.Text += "AES-256 otv decrypted is ok: " + (Base16.Encode(aes256tvd) == "00112233445566778899aabbccddeeff") + "\n";
            this.outputBox.Text += "AES-256 (CBC mode) encrypted in UTF-8: " + Base16.Encode(aes256e) + "\n";
            this.outputBox.Text += "AES-256 (CBC mode) decrypted in UTF-8: " + Encoding.UTF8.GetString(aes256d) + "\n";
            this.outputBox.Text += "\n";
        }
Пример #25
0
 public static string FromDestination(byte[] destination)
 {
     byte[] hashResult = SHA256.Compute(destination);
     return(Base32.ToString(hashResult) + ".b32.i2p");
 }
Пример #26
0
        public async Task <T> ExecuteAsync <T>(HttpRequest request) where T : JDPayNotifyResponse
        {
            if (request.HasFormContentType || request.Method == "GET")
            {
                var rspInstance = Activator.CreateInstance <T>();

                var parameters = GetParameters(request, !(rspInstance is JDPayDefrayPayNotifyResponse));

                var query = JDPayUtility.BuildQuery(parameters);
                Logger?.LogTrace(0, "Request:{query}", query);

                var parser = new JDPayDictionaryParser <T>();
                var rsp    = parser.Parse(parameters);

                if (rsp is JDPayDefrayPayNotifyResponse)
                {
                    CheckNotifyDefrayPaySign(rsp.Parameters);
                }
                else
                {
                    CheckNotifySign(rsp.Parameters);
                }

                return(rsp);
            }
            else if (request.HasTextXmlContentType())
            {
                var body = await new StreamReader(request.Body).ReadToEndAsync();
                Logger?.LogTrace(0, "Request:{body}", body);

                var parser = new JDPayXmlParser <T>();
                var rsp    = parser.Parse(JDPayUtility.FotmatXmlString(body));
                if (!string.IsNullOrEmpty(rsp.Encrypt))
                {
                    var encrypt          = rsp.Encrypt;
                    var base64EncryptStr = Encoding.UTF8.GetString(Convert.FromBase64String(encrypt));
                    var reqBody          = JDPaySecurity.DecryptECB(base64EncryptStr, Options.DesKeyBase64);
                    Logger?.LogTrace(1, "Encrypt Content:{reqBody}", reqBody);

                    var reqBodyDoc = new XmlDocument()
                    {
                        XmlResolver = null
                    };
                    reqBodyDoc.LoadXml(reqBody);

                    var sign     = JDPayUtility.GetValue(reqBodyDoc, "sign");
                    var rootNode = reqBodyDoc.SelectSingleNode("jdpay");
                    var signNode = rootNode.SelectSingleNode("sign");
                    rootNode.RemoveChild(signNode);

                    var reqBodyStr = JDPayUtility.ConvertXmlToString(reqBodyDoc);
                    var xmlh       = rsp.Body.Substring(0, rsp.Body.IndexOf("<jdpay>"));
                    if (!string.IsNullOrEmpty(xmlh))
                    {
                        reqBodyStr = reqBodyStr.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlh);
                    }
                    var sha256SourceSignString = SHA256.Compute(reqBodyStr);
                    var decryptByte            = RSA_ECB_PKCS1Padding.Decrypt(Convert.FromBase64String(sign), Options.PublicKey);
                    var decryptStr             = JDPaySecurity.BytesToString(decryptByte);
                    if (sha256SourceSignString == decryptStr)
                    {
                        rsp         = parser.Parse(reqBody);
                        rsp.Encrypt = encrypt;
                        return(rsp);
                    }
                    else
                    {
                        throw new Exception("sign check fail: check Sign and Data Fail!");
                    }
                }
                else
                {
                    throw new Exception("encrypt is Empty!");
                }
            }
            else
            {
                throw new Exception("content type is not supported!");
            }
        }