当前位置:网站首页 / .NET CORE / 正文

AY的AyCore.Shared的诞生笔记-安全

时间:2018年12月29日 | 作者 : aaronyang | 分类 : .NET CORE | 浏览: 839次 | 评论 0

AesShared使用,AyCore.Shared

image.png

原理语法:

安全性:

Core内置的语法,然后二次封装

image.png

接下来封装Base64

image.png

          string key = Base64Shared.Base64Encode("1234567812345678");
            Console.WriteLine(key); // MTIzNDU2NzgxMjM0NTY3OA ==
            string key2 = Base64Shared.Base64Decode(key);
            Console.WriteLine(key2); // 1234567812345678



接下来封装RSA

支付宝有:https://docs.open.alipay.com/291/105971 运行bat,方便测试用的。

image.png

使用此工具生成的时候一定要选择,PKCS1

OpenSSL也可以生成:https://docs.open.alipay.com/291/106130


RSA2 或者 RSA 

使用方式,私钥比公钥长。

            //2048 公钥
            string publicKey =
              "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy1QhBYylU4I5oCJidL2mQhnnKa/qILxHw/B+XxSL5xDubaaJDLSdTwhovHcFXjo0ktdnHO+yUire5UseEHPID1z36XZ7d2C2qe4swQXaw9XQQts3/ncHKFA2lYv/fHVkqq+bipi8zWv3OwPQd9FysldPRl2g+PZlvy/qsg9jsP3toU7/vbJn7E+7wO2p5lxgiLG8+U2+EsqFKBXfAhjOsfDtW1zs8pfMCskNaqaWVLwCpJqBQDNCO8IlbSEsrSGqIsfKzf2QkdioHxsbfm1DJ3vPTyHzYqaH6iQARR7nMW1mo2icYhio8JATdy2tS99Nieb+K9uGZYMdv+ixyU4mbwIDAQAB";
            //2048 私钥
            string privateKey =
                "MIIEowIBAAKCAQEAy1QhBYylU4I5oCJidL2mQhnnKa/qILxHw/B+XxSL5xDubaaJDLSdTwhovHcFXjo0ktdnHO+yUire5UseEHPID1z36XZ7d2C2qe4swQXaw9XQQts3/ncHKFA2lYv/fHVkqq+bipi8zWv3OwPQd9FysldPRl2g+PZlvy/qsg9jsP3toU7/vbJn7E+7wO2p5lxgiLG8+U2+EsqFKBXfAhjOsfDt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v2plLcD3IQZyKTpOpl9FGwcSLRtCgS3skr1/6fNlt9RQjw+79jCzsictX/W9xQeYmlFeRflyBWL89eEpzSDkabzVhsGk36EP43eiQKBgEO9GtPLGwqLn/NRERonneuFaozgI6Ad6HIMSy7GgX5cwQcdHBWE5FysRLi+fWhNqhStcvfdasd5aHPsS0r1FxJGVH7ERoAp4AGCbAhdCyy5zlZd6XgLHxJVIntSVcKMqh0ZnY/eebd814cdMPvKwe8tUNYGeK2z1ZopjULNUgm6";

            var rsa = new RSAShared(RSAType.RSA2, System.Text.Encoding.UTF8, privateKey, publicKey);

            string str = "AY技术 http://www.ayjs.net";
            Console.WriteLine("原始字符串:" + str);
            //加密
            string enStr = rsa.Encrypt(str);
            Console.WriteLine("加密字符串:" + enStr);
            //解密
            string deStr = rsa.Decrypt(enStr);
            Console.WriteLine("解密字符串:" + deStr);
            //私钥签名
            string signStr = rsa.Sign(str);
            Console.WriteLine("字符串签名:" + signStr);
           //公钥验证签名
            bool signVerify = rsa.Verify(str, signStr);
            Console.WriteLine("验证签名:" + signVerify);
            Console.Read();
        }

image.png

关于:RSA 有些是java语言加密的,.net不能解密,或者逆向也不行

建议使用Org.BouncyCastle.Crypto库

我AY的参考文章:https://www.cnblogs.com/AsprosL/p/8251468.html

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace Payment.LianLianPay.Sdk.Infrastructure
{
    public static class RsaHelper
    {
        /// <summary>
        /// private key sign
        /// </summary>
        /// <param name="preSign"></param>
        /// <param name="isJavaFormatKey"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string RsaSign(string preSign, bool isJavaFormatKey, string privateKey)
        {
            try
            {
                //// net
                //var rsa = new RSACryptoServiceProvider();
                //rsa.FromXmlString(privateKey);
                //byte[] signBytes = rsa.SignData(UTF8Encoding.UTF8.GetBytes(signStr), "md5");
                //return Convert.ToBase64String(signBytes);

                // net core 2.0
                using (var rsa = RSA.Create())
                {
                    if (isJavaFormatKey) privateKey = RsaPrivateKeyJava2DotNet(privateKey);
                    rsa.FromXmlStringExtensions(privateKey);
                    var bytes = rsa.SignData(Encoding.UTF8.GetBytes(preSign), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                    return Convert.ToBase64String(bytes);
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
        }
        /// <summary>
        /// .net => java Md5WithRsa 
        /// </summary>
        /// <param name="preSign"></param>
        /// <param name="isJavaFormatKey"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string RsaSignMd5WithRsa(string preSign, bool isJavaFormatKey, string privateKey)
        {
            try
            {
                //// net
                //var rsa = new RSACryptoServiceProvider();
                //rsa.FromXmlString(privateKey);
                //byte[] signBytes = rsa.SignData(UTF8Encoding.UTF8.GetBytes(signStr), "md5");
                //return Convert.ToBase64String(signBytes);

                // net core 2.0
                using (var rsa = RSA.Create())
                {
                    if (isJavaFormatKey) privateKey = RsaPrivateKeyJava2DotNet(privateKey);
                    rsa.FromXmlStringExtensions(privateKey);
                    var bytes = rsa.SignData(Encoding.UTF8.GetBytes(preSign), HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1);
                    return Convert.ToBase64String(bytes);
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
        }
        /// <summary>
        /// public key sign
        /// </summary>
        /// <param name="preSign"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static string RsaEncrypt(string preSign, string publicKey)
        {
            try
            {
                //// net
                //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                //rsa.FromXmlString(strPublicKey);
                //byte[] bytes = rsa.Encrypt(UTF8Encoding.UTF8.GetBytes(strEncryptInfo), false);
                //return Convert.ToBase64String(bytes);

                // net core 2.0
                using (var rsa = RSA.Create())
                {
                    publicKey = RsaPublicKeyJava2DotNet(publicKey);
                    rsa.FromXmlStringExtensions(publicKey);
                    var bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(preSign), RSAEncryptionPadding.Pkcs1);
                    return Convert.ToBase64String(bytes);
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
        }
        /// <summary>
        /// public key validate
        /// </summary>
        /// <param name="preSign"></param>
        /// <param name="isJavaFormatKey"></param>
        /// <param name="publicKey"></param>
        /// <param name="signedData"></param>
        /// <returns></returns>
        public static bool ValidateRsaSign(string preSign, bool isJavaFormatKey, string publicKey, string signedData)
        {
            try
            {
                //// net
                //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                //rsa.FromXmlString(publicKey);
                //return rsa.VerifyData(UTF8Encoding.UTF8.GetBytes(plainText), "md5", Convert.FromBase64String(signedData));

                // net core 2.0
                using (var rsa = RSA.Create())
                {
                    if (isJavaFormatKey) publicKey = RsaPublicKeyJava2DotNet(publicKey);
                    rsa.FromXmlStringExtensions(publicKey);
                    return rsa.VerifyData(Encoding.UTF8.GetBytes(preSign), Convert.FromBase64String(signedData), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
        }
        /// <summary>
        /// private key ,java->.net
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string RsaPrivateKeyJava2DotNet(string privateKey)
        {
            if (string.IsNullOrEmpty(privateKey))
            {
                return string.Empty;
            }
            var privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
            return
                $"<RSAKeyValue><Modulus>{Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned())}</Modulus><Exponent>{Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned())}</Exponent><P>{Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned())}</P><Q>{Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned())}</Q><DP>{Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned())}</DP><DQ>{Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned())}</DQ><InverseQ>{Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned())}</InverseQ><D>{Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())}</D></RSAKeyValue>";
        }
        /// <summary>
        /// public key ,java->.net
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns>格式转换结果</returns>
        public static string RsaPublicKeyJava2DotNet(string publicKey)
        {
            if (string.IsNullOrEmpty(publicKey))
            {
                return string.Empty;
            }

            var publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
            return string.Format(
                "<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
                Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
                Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned())
            );
        }
        /// <summary>
        /// private key ,.net->java
        /// </summary>
        /// <param name="privateKey">.net生成的私钥</param>
        /// <returns></returns>
        public static string RsaPrivateKeyDotNet2Java(string privateKey)
        {
            var doc = new XmlDocument();
            doc.LoadXml(privateKey);
            var m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            var exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            var d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            var p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            var q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            var dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            var dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            var qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));

            var privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);

            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
            var serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            return Convert.ToBase64String(serializedPrivateBytes);
        }
        /// <summary>
        /// public key ,.net->java
        /// </summary>
        /// <param name="publicKey">.net生成的公钥</param>
        /// <returns></returns>
        public static string RsaPublicKeyDotNet2Java(string publicKey)
        {
            var doc = new XmlDocument();
            doc.LoadXml(publicKey);
            var m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            var p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            var pub = new RsaKeyParameters(false, m, p);

            var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
            var serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return Convert.ToBase64String(serializedPublicBytes);
        }
        // 处理 下面两种方式都会出现的 Operation is not supported on this platform 异常
        // RSA.Create().FromXmlString(privateKey) 
        // new RSACryptoServiceProvider().FromXmlString(privateKey) 
        /// <summary>
        /// 扩展FromXmlString
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="xmlString"></param>
        private static void FromXmlStringExtensions(this RSA rsa, string xmlString)
        {
            var parameters = new RSAParameters();

            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlString);

            if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue"))
            {
                foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
                {
                    switch (node.Name)
                    {
                        case "Modulus":
                            parameters.Modulus = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                        case "Exponent":
                            parameters.Exponent = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                        case "P":
                            parameters.P = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                        case "Q":
                            parameters.Q = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                        case "DP":
                            parameters.DP = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                        case "DQ":
                            parameters.DQ = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                        case "InverseQ":
                            parameters.InverseQ = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                        case "D":
                            parameters.D = (string.IsNullOrEmpty(node.InnerText)
                                ? null
                                : Convert.FromBase64String(node.InnerText));
                            break;
                    }
                }
            }
            else
            {
                throw new Exception("Invalid XML RSA key.");
            }

            rsa.ImportParameters(parameters);
        }
        //        /// <summary>
        //        /// 扩展ToXmlString,创建公私钥
        //        /// </summary>
        //        /// <param name="includePrivateParameters"></param>
        //        /// <returns></returns>
        //        public static string ToCreateKey(bool includePrivateParameters)
        //        {
        //            using (var rsa = RSA.Create())
        //            {
        //                var parameters = rsa.ExportParameters(includePrivateParameters);
        //                return
        //                    $"<RSAKeyValue><Modulus>{(parameters.Modulus != null ? Convert.ToBase64String(parameters.Modulus) : null)}</Modulus><Exponent>{(parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null)}</Exponent><P>{(parameters.P != null ? Convert.ToBase64String(parameters.P) : null)}</P><Q>{(parameters.Q != null ? Convert.ToBase64String(parameters.Q) : null)}</Q><DP>{(parameters.DP != null ? Convert.ToBase64String(parameters.DP) : null)}</DP><DQ>{(parameters.DQ != null ? Convert.ToBase64String(parameters.DQ) : null)}</DQ><InverseQ>{(parameters.InverseQ != null ? Convert.ToBase64String(parameters.InverseQ) : null)}</InverseQ><D>{(parameters.D != null ? Convert.ToBase64String(parameters.D) : null)}</D></RSAKeyValue>";
        //            }
        //        }
        /// <summary>
        /// Generate XML Format RSA Key. Result: Index 0 is the private key and index 1 is the public key
        /// </summary>
        /// <param name="keySize">Key Size.Unit: bits</param>
        /// <returns></returns>
        public static List<string> XmlKey(int keySize)
        {
            using (var rsa = RSA.Create())
            {
                rsa.KeySize = keySize;
                var rsap = rsa.ExportParameters(true);
                var res = new List<string>();
                var privatElement = new XElement("RSAKeyValue");
                //Modulus
                var primodulus = new XElement("Modulus", Convert.ToBase64String(rsap.Modulus));
                //Exponent
                var priexponent = new XElement("Exponent", Convert.ToBase64String(rsap.Exponent));
                //P
                var prip = new XElement("P", Convert.ToBase64String(rsap.P));
                //Q
                var priq = new XElement("Q", Convert.ToBase64String(rsap.Q));
                //DP
                var pridp = new XElement("DP", Convert.ToBase64String(rsap.DP));
                //DQ
                var pridq = new XElement("DQ", Convert.ToBase64String(rsap.DQ));
                //InverseQ
                var priinverseQ = new XElement("InverseQ", Convert.ToBase64String(rsap.InverseQ));
                //D
                var prid = new XElement("D", Convert.ToBase64String(rsap.D));

                privatElement.Add(primodulus);
                privatElement.Add(priexponent);
                privatElement.Add(prip);
                privatElement.Add(priq);
                privatElement.Add(pridp);
                privatElement.Add(pridq);
                privatElement.Add(priinverseQ);
                privatElement.Add(prid);

                //添加私钥
                res.Add(privatElement.ToString());

                var publicElement = new XElement("RSAKeyValue");
                //Modulus
                var pubmodulus = new XElement("Modulus", Convert.ToBase64String(rsap.Modulus));
                //Exponent
                var pubexponent = new XElement("Exponent", Convert.ToBase64String(rsap.Exponent));

                publicElement.Add(pubmodulus);
                publicElement.Add(pubexponent);

                //添加公钥
                res.Add(publicElement.ToString());

                return res;
            }
        }
        /// <summary>
        /// Generate RSA key in Pkcs1 format. Result: Index 0 is the private key and index 1 is the public key
        /// </summary>
        /// <param name="keySize">Key Size.Unit: bits</param>
        /// <param name="format">Whether the format is true If it is standard pem file format</param>
        /// <returns></returns>
        public static List<string> Pkcs1Key(int keySize, bool format = true)
        {
            var res = new List<string>();

            var kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize));
            var keyPair = kpGen.GenerateKeyPair();

            var sw = new StringWriter();
            var pWrt = new PemWriter(sw);
            pWrt.WriteObject(keyPair.Private);
            pWrt.Writer.Flush();
            var privateKey = sw.ToString();

            if (!format)
            {
                privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\r\n", "");
            }

            res.Add(privateKey);

            var swpub = new StringWriter();
            var pWrtpub = new PemWriter(swpub);
            pWrtpub.WriteObject(keyPair.Public);
            pWrtpub.Writer.Flush();
            var publicKey = swpub.ToString();
            if (!format)
            {
                publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\r\n", "");
            }

            res.Add(publicKey);

            return res;
        }
        /// <summary>
        /// Generate Pkcs8 format RSA key. Result: Index 0 is the private key and index 1 is the public key
        /// </summary>
        /// <param name="keySize">Key Size.Unit: bits</param>
        /// <param name="format">Whether the format is true If it is standard pem file format</param>
        /// <returns></returns>
        public static List<string> Pkcs8Key(int keySize, bool format = true)
        {
            var res = new List<string>();

            var kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize));
            var keyPair = kpGen.GenerateKeyPair();

            var swpri = new StringWriter();
            var pWrtpri = new PemWriter(swpri);
            var pkcs8 = new Pkcs8Generator(keyPair.Private);
            pWrtpri.WriteObject(pkcs8);
            pWrtpri.Writer.Flush();
            var privateKey = swpri.ToString();

            if (!format)
            {
                privateKey = privateKey.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "").Replace("\r\n", "");
            }

            res.Add(privateKey);

            var swpub = new StringWriter();
            var pWrtpub = new PemWriter(swpub);
            pWrtpub.WriteObject(keyPair.Public);
            pWrtpub.Writer.Flush();
            var publicKey = swpub.ToString();
            if (!format)
            {
                publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\r\n", "");
            }

            res.Add(publicKey);

            return res;
        }
        /// <summary>
        /// Public Key Convert xml->xml
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static string PublicKeyXmlToPem(string publicKey)
        {
            var root = XElement.Parse(publicKey);
            //Modulus
            var modulus = root.Element("Modulus");
            //Exponent
            var exponent = root.Element("Exponent");

            var rsaKeyParameters = new RsaKeyParameters(false, new BigInteger(1, Convert.FromBase64String(modulus?.Value)), new BigInteger(1, Convert.FromBase64String(exponent?.Value)));

            var sw = new StringWriter();
            var pWrt = new PemWriter(sw);
            pWrt.WriteObject(rsaKeyParameters);
            pWrt.Writer.Flush();
            return sw.ToString();
        }
        /// <summary>
        /// Private Key Convert xml->Pkcs1
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyXmlToPkcs1(string privateKey)
        {
            var root = XElement.Parse(privateKey);
            //Modulus
            var modulus = root.Element("Modulus");
            //Exponent
            var exponent = root.Element("Exponent");
            //P
            var p = root.Element("P");
            //Q
            var q = root.Element("Q");
            //DP
            var dp = root.Element("DP");
            //DQ
            var dq = root.Element("DQ");
            //InverseQ
            var inverseQ = root.Element("InverseQ");
            //D
            var d = root.Element("D");

            var rsaPrivateCrtKeyParameters = new RsaPrivateCrtKeyParameters(
                new BigInteger(1, Convert.FromBase64String(modulus?.Value)),
                new BigInteger(1, Convert.FromBase64String(exponent?.Value)),
                new BigInteger(1, Convert.FromBase64String(d?.Value)),
                new BigInteger(1, Convert.FromBase64String(p?.Value)),
                new BigInteger(1, Convert.FromBase64String(q?.Value)),
                new BigInteger(1, Convert.FromBase64String(dp?.Value)),
                new BigInteger(1, Convert.FromBase64String(dq?.Value)),
                new BigInteger(1, Convert.FromBase64String(inverseQ?.Value)));

            var sw = new StringWriter();
            var pWrt = new PemWriter(sw);
            pWrt.WriteObject(rsaPrivateCrtKeyParameters);
            pWrt.Writer.Flush();
            return sw.ToString();

        }
        /// <summary>
        /// Format public key
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string PublicKeyFormat(string str)
        {
            if (str.StartsWith("-----BEGIN PUBLIC KEY-----"))
            {
                return str;
            }
            var res = new List<string> { "-----BEGIN PUBLIC KEY-----" };
            var pos = 0;
            while (pos < str.Length)
            {
                var count = str.Length - pos < 64 ? str.Length - pos : 64;
                res.Add(str.Substring(pos, count));
                pos += count;
            }
            res.Add("-----END PUBLIC KEY-----");
            var resStr = string.Join("\r\n", res);
            return resStr;
        }
        /// <summary>
        /// Format Pkcs8 format private key
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string Pkcs8PrivateKeyFormat(string str)
        {
            if (str.StartsWith("-----BEGIN PRIVATE KEY-----"))
            {
                return str;
            }
            var res = new List<string> { "-----BEGIN PRIVATE KEY-----" };
            var pos = 0;
            while (pos < str.Length)
            {
                var count = str.Length - pos < 64 ? str.Length - pos : 64;
                res.Add(str.Substring(pos, count));
                pos += count;
            }
            res.Add("-----END PRIVATE KEY-----");
            var resStr = string.Join("\r\n", res);
            return resStr;
        }
        /// <summary>
        /// Format Pkcs1 format private key
        /// Author:Zhiqiang Li
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string Pkcs1PrivateKeyFormat(string str)
        {
            if (str.StartsWith("-----BEGIN RSA PRIVATE KEY-----"))
            {
                return str;
            }
            var res = new List<string> { "-----BEGIN RSA PRIVATE KEY-----" };
            var pos = 0;
            while (pos < str.Length)
            {
                var count = str.Length - pos < 64 ? str.Length - pos : 64;
                res.Add(str.Substring(pos, count));
                pos += count;
            }
            res.Add("-----END RSA PRIVATE KEY-----");
            var resStr = string.Join("\r\n", res);
            return resStr;
        }
        /// <summary>
        /// Remove the Pkcs8 format private key format
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string Pkcs8PrivateKeyFormatRemove(string str)
        {
            if (!str.StartsWith("-----BEGIN PRIVATE KEY-----"))
            {
                return str;
            }
            return str.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "")
                .Replace("\r\n", "");
        }
        /// <summary>
        /// public Key pem to xml
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static string PublicKeyPemToXml(string publicKey)
        {
            publicKey = PublicKeyFormat(publicKey);

            var pr = new PemReader(new StringReader(publicKey));
            var obj = pr.ReadObject();
            if (!(obj is RsaKeyParameters rsaKey))
            {
                throw new Exception("Public key format is incorrect");
            }

            var publicElement = new XElement("RSAKeyValue");
            //Modulus
            var pubmodulus = new XElement("Modulus", Convert.ToBase64String(rsaKey.Modulus.ToByteArrayUnsigned()));
            //Exponent
            var pubexponent = new XElement("Exponent", Convert.ToBase64String(rsaKey.Exponent.ToByteArrayUnsigned()));

            publicElement.Add(pubmodulus);
            publicElement.Add(pubexponent);
            return publicElement.ToString();
        }
        /// <summary>
        /// Private Key Convert Pkcs1->xml
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyPkcs1ToXml(string privateKey)
        {
            privateKey = Pkcs1PrivateKeyFormat(privateKey);

            var pr = new PemReader(new StringReader(privateKey));
            if (!(pr.ReadObject() is AsymmetricCipherKeyPair asymmetricCipherKeyPair))
            {
                throw new Exception("Private key format is incorrect");
            }
            var rsaPrivateCrtKeyParameters =
                (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(
                    PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricCipherKeyPair.Private));

            var privatElement = new XElement("RSAKeyValue");
            //Modulus
            var primodulus = new XElement("Modulus", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Modulus.ToByteArrayUnsigned()));
            //Exponent
            var priexponent = new XElement("Exponent", Convert.ToBase64String(rsaPrivateCrtKeyParameters.PublicExponent.ToByteArrayUnsigned()));
            //P
            var prip = new XElement("P", Convert.ToBase64String(rsaPrivateCrtKeyParameters.P.ToByteArrayUnsigned()));
            //Q
            var priq = new XElement("Q", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Q.ToByteArrayUnsigned()));
            //DP
            var pridp = new XElement("DP", Convert.ToBase64String(rsaPrivateCrtKeyParameters.DP.ToByteArrayUnsigned()));
            //DQ
            var pridq = new XElement("DQ", Convert.ToBase64String(rsaPrivateCrtKeyParameters.DQ.ToByteArrayUnsigned()));
            //InverseQ
            var priinverseQ = new XElement("InverseQ", Convert.ToBase64String(rsaPrivateCrtKeyParameters.QInv.ToByteArrayUnsigned()));
            //D
            var prid = new XElement("D", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Exponent.ToByteArrayUnsigned()));

            privatElement.Add(primodulus);
            privatElement.Add(priexponent);
            privatElement.Add(prip);
            privatElement.Add(priq);
            privatElement.Add(pridp);
            privatElement.Add(pridq);
            privatElement.Add(priinverseQ);
            privatElement.Add(prid);

            return privatElement.ToString();
        }
        /// <summary>
        /// Private Key Convert Pkcs8->xml
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyPkcs8ToXml(string privateKey)
        {
            privateKey = Pkcs8PrivateKeyFormatRemove(privateKey);
            var privateKeyParam =
                (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));

            var privatElement = new XElement("RSAKeyValue");
            //Modulus
            var primodulus = new XElement("Modulus", Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()));
            //Exponent
            var priexponent = new XElement("Exponent", Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()));
            //P
            var prip = new XElement("P", Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()));
            //Q
            var priq = new XElement("Q", Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()));
            //DP
            var pridp = new XElement("DP", Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()));
            //DQ
            var pridq = new XElement("DQ", Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()));
            //InverseQ
            var priinverseQ = new XElement("InverseQ", Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()));
            //D
            var prid = new XElement("D", Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));

            privatElement.Add(primodulus);
            privatElement.Add(priexponent);
            privatElement.Add(prip);
            privatElement.Add(priq);
            privatElement.Add(pridp);
            privatElement.Add(pridq);
            privatElement.Add(priinverseQ);
            privatElement.Add(prid);

            return privatElement.ToString();
        }
        /// <summary>
        /// Private Key Convert xml->Pkcs8
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyXmlToPkcs8(string privateKey)
        {
            var root = XElement.Parse(privateKey);
            //Modulus
            var modulus = root.Element("Modulus");
            //Exponent
            var exponent = root.Element("Exponent");
            //P
            var p = root.Element("P");
            //Q
            var q = root.Element("Q");
            //DP
            var dp = root.Element("DP");
            //DQ
            var dq = root.Element("DQ");
            //InverseQ
            var inverseQ = root.Element("InverseQ");
            //D
            var d = root.Element("D");

            var rsaPrivateCrtKeyParameters = new RsaPrivateCrtKeyParameters(
                new BigInteger(1, Convert.FromBase64String(modulus?.Value)),
                new BigInteger(1, Convert.FromBase64String(exponent?.Value)),
                new BigInteger(1, Convert.FromBase64String(d?.Value)),
                new BigInteger(1, Convert.FromBase64String(p?.Value)),
                new BigInteger(1, Convert.FromBase64String(q?.Value)),
                new BigInteger(1, Convert.FromBase64String(dp?.Value)),
                new BigInteger(1, Convert.FromBase64String(dq?.Value)),
                new BigInteger(1, Convert.FromBase64String(inverseQ?.Value)));

            var swpri = new StringWriter();
            var pWrtpri = new PemWriter(swpri);
            var pkcs8 = new Pkcs8Generator(rsaPrivateCrtKeyParameters);
            pWrtpri.WriteObject(pkcs8);
            pWrtpri.Writer.Flush();
            return swpri.ToString();

        }
        /// <summary>
        /// Private Key Convert Pkcs1->Pkcs8
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyPkcs1ToPkcs8(string privateKey)
        {
            privateKey = Pkcs1PrivateKeyFormat(privateKey);
            var pr = new PemReader(new StringReader(privateKey));

            var kp = pr.ReadObject() as AsymmetricCipherKeyPair;
            var sw = new StringWriter();
            var pWrt = new PemWriter(sw);
            var pkcs8 = new Pkcs8Generator(kp?.Private);
            pWrt.WriteObject(pkcs8);
            pWrt.Writer.Flush();
            var result = sw.ToString();
            return result;
        }
        /// <summary>
        /// Private Key Convert Pkcs8->Pkcs1
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyPkcs8ToPkcs1(string privateKey)
        {
            privateKey = Pkcs8PrivateKeyFormat(privateKey);
            var pr = new PemReader(new StringReader(privateKey));

            var kp = pr.ReadObject() as RsaPrivateCrtKeyParameters;

            var keyParameter = PrivateKeyFactory.CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(kp));

            var sw = new StringWriter();
            var pWrt = new PemWriter(sw);
            pWrt.WriteObject(keyParameter);
            pWrt.Writer.Flush();
            var result = sw.ToString();
            return result;
        }
    }
}

  https://www.cnblogs.com/dj258/p/6049786.html



关于RSA中的一些 关键词说明:


https://www.cnblogs.com/shijingxiang/articles/4445272.html


公钥加密,私钥解密。

私钥签名,公钥验证。


公钥私钥的原则:

一个公钥对应一个私钥。

密钥对中,让大家都知道的是公钥,不告诉大家,只有自己知道的,是私钥。

如果用其中一个密钥加密数据,则只有对应的那个密钥才可以解密。

如果用其中一个密钥可以进行解密数据,则该数据必然是对应的那个密钥进行的加密。


比如有两个用户Alice和Bob,Alice想把一段明文通过双钥加密的技术发送给Bob,Bob有一对公钥和私钥,那么加密解密的过程如下:

Bob将他的公开密钥传送给Alice。

Alice用Bob的公开密钥加密她的消息,然后传送给Bob。

Bob用他的私人密钥解密Alice的消息。

Alice使用Bob的公钥进行加密,Bob用自己的私钥进行解密。

image.png

image.png

1. 信息加密

  收信者是唯一能够解开加密信息的人,因此收信者手里的必须是私钥。发信者手里的是公钥,其它人知道公钥没有关系,因为其它人发来的信息对收信者没有意义。

2. 登录认证

    客户端需要将认证标识传送给服务器,此认证标识(可能是一个随机数)其它客户端可以知道,因此需要用私钥加密,客户端保存的是私钥。服务器端保存的是公钥,其它服务器知道公钥没有关系,因为客户端不需要登录其它服务器。

3. 数字签名

  数字签名是为了表明信息没有受到伪造,确实是信息拥有者发出来的,附在信息原文的后面。就像手写的签名一样,具有不可抵赖性和简洁性。

  简洁性:对信息原文做hash,得到digest。信息越短加密的耗时越少。

  不可抵赖性:信息拥有者要保证签名的唯一性,必须是唯一能够加密digest的人,因此必须用私钥加密(就像字迹他人无法学会一样),得到签名。如果用公钥,那每个人都可以伪造签名了。

4.数字证书

  问题起源:对1和3,发信者怎么知道从网上获取的公钥就是真的?没有遭受中间人攻击?

  这样就需要第三方机构来保证公钥的合法性,这个第三方机构就是CA(Certificate Authority),证书中心。

     CA用自己的私钥对信息原文所有者发布的公钥和相关信息进行加密,得出的内容就是数字证书。

  信息原文的所有者以后发布信息时,除了带上自己的签名,还带上数字证书,就可以保证信息不被篡改了。信息的接收者先用CA给的公钥解出信息所有者的公钥,这样可以保证信息所有者的公钥是真正的公钥,然后就能通过该公钥证明数字签名是否真实了。


备注:

CORE和.NET Framework最新的微软下载地址:

https://dotnet.microsoft.com/download/visual-studio-sdks?utm_source=getdotnetsdk&utm_medium=referral


AyCore.Shared等代码差不多再开源,这等于是我的使用文档,一个研究和整合的记录。



关于加密和解密 签名和验证模糊的,最后看 https://www.jianshu.com/p/94cd6d5be142

我是理解了。在使用RSA进行通讯的时候,一般是两者结合,即:加密>签名>解密>验签


====================www.ayjs.net       杨洋    wpfui.com        ayui      ay  aaronyang=======请不要转载谢谢了。=========


支付宝 应用的RSA流程


.简介

RSA 是一种非对称的签名算法,即签名密钥(私钥)与验签密钥(公钥)是不一样的,私钥用于签名,公钥用于验签。

在与支付宝交易中,会有 2 对公私钥,即商户公私钥,支付宝公私钥。


商户公私钥:由商户生成,商户私钥用于对商户发往支付宝的数据签名;商户公钥需要上传至支付宝,当支付宝收到商户发来的数据时用该公钥验证签名。

支付宝公私钥:支付宝提供给商户,当商户收到支付宝发来的数据时,用该公钥验签。 



2.流程

 a. 移动端用商户私玥签名,将订单数据传给支付宝客户端,支付宝客户端将订单数据传给支付宝服务器,支付宝服务器根据订单数据中的商户信息,用商户上传的商户公钥验签,成功后进行支付操作;

b. 用户支付成功后,支付宝服务器用支付宝私钥签名回调数据并回调商家服务器(回调URL),同时支付宝客户端回调商家客户端;

c. 商家服务器用支付宝公钥验签,成功后更新商家订单状态等。



====================www.ayjs.net       杨洋    wpfui.com        ayui      ay  aaronyang=======请不要转载谢谢了。=========

AY自己写的。

接下来我们2对公钥私钥,完成一次通信

      //商户的私钥
            string c_privateKey = "MIIEpAIBAAKCAQEAxx0nwL0KJEsEpT5xygdak0amH457nB/+3vq29mNMZ5yHaC73pq0EHx0uaV22CsQzMA1AkwwKRaixtTBkCaJY9oxNOuj+zWuWp8nd1Kw8pksnvZFT4/runT/LYtTFDHpZP6SoQcxNPLkunJssX65bTvlBNyJghCwyvsHDJK98hQQ21DHwgK2wVktL+1RsZQw5txUHcLv27SQ3WPuREt5XIvRM8o302+AsHUnOgitKVjEESSFGrrNdoBdFi9I0tjQsQRMKlE2L5WZwMGuv0zzuwshnPOjJwhXsOIbnaC2OxuBCNNfVT36lEIfMEBg9tWuMPEw6YP/M40jEAJJYqL80bQIDAQABAoIBAQCTT0in2bP1IeMv9cDtvP8P0sb4tctRuIIxqb9PDivqw+2R8J2cHIjeFBLQNVqHIJzWQheyMsguvR2sdT6tugSjcy14FgTdKWnufPS3cS31wciHAUvVcUKz6Ayq88tM7f+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vy6JVPhKd7BikH8Uw==";

            //支付宝审核你成功后,给你的公钥
            string zfb_publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqXeY5LLzasRWrbvtPxzVxpv61ppVaPGfo3GLv/6QjGYRe9DDaoKaskSpFq4HQRXi1cy4OnWBW9UtqUxQoEDcdCzVpsKl7kByBOLaah1pypJft3q7wSVqzo/q7QykBwM9MEwxoy+7UfjrIqLsdszw7woJuHZBgqCzIAiw/IEKYoWtgPvuKmpq5A+MpiVvKAvhTae5ItbdTtueKNaEuv0Ua0jGAKRJpE14cD8LYpsXQYjslF5Ru35ObCcY/s1PQsdbfYx6kFUHXmMD4I/7YEgnCX+pV+vovLQRtHNu2WKqRZm0vVE/6/NksDEPyPlf8KJFwi10J9rfqy+gwvhmAVihbwIDAQAB";

            //商户上传的公钥
            string c_publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxx0nwL0KJEsEpT5xygdak0amH457nB/+3vq29mNMZ5yHaC73pq0EHx0uaV22CsQzMA1AkwwKRaixtTBkCaJY9oxNOuj+zWuWp8nd1Kw8pksnvZFT4/runT/LYtTFDHpZP6SoQcxNPLkunJssX65bTvlBNyJghCwyvsHDJK98hQQ21DHwgK2wVktL+1RsZQw5txUHcLv27SQ3WPuREt5XIvRM8o302+AsHUnOgitKVjEESSFGrrNdoBdFi9I0tjQsQRMKlE2L5WZwMGuv0zzuwshnPOjJwhXsOIbnaC2OxuBCNNfVT36lEIfMEBg9tWuMPEw6YP/M40jEAJJYqL80bQIDAQAB";

            //支付审核你成功后,给你的公钥的 对应的私钥
            string zfb_privateKey = "MIIEpQIBAAKCAQEAqXeY5LLzasRWrbvtPxzVxpv61ppVaPGfo3GLv/6QjGYRe9DDaoKaskSpFq4HQRXi1cy4OnWBW9UtqUxQoEDcdCzVpsKl7kByBOLaah1pypJft3q7wSVqzo/q7QykBwM9MEwxoy+7UfjrIqLsdszw7woJuHZBgqCzIA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Y1R3AoGBALZJgMCXDnYGEF7FoiNBZCIa1QrsgbLjdDT3T8SsaynAWom6W3MSl904B2mXf1ayIEpU/zOCvCJKYdetpQhxQ4MZTeMqsBCzaVsFu3ZLxF9/WVSYxmqBcJkRuE/LwZq1I1Ht9Hh/4xpOLa1mGNKg5jGJ+shbMXp59ukeBH+igaHpAoGAfAXQZmvZd1xOOJH5Ix9fJq1uV6bFkZ65n1CGmIfLdMZkN54wd+c0HQJxAdnaRSw56MJu8d+YwW7Hl+gDOBlFmFxXSwYgSuDfkFzK9KG07S6GQDs6/BGgGbnGrdp5E7MXIfZHnT3Ilqsj8NSaXtIewoTOzWlD03t274WbZ4tdtys=";

接下来,商户发信息

创建两个rsa

         string data = "AY讲解RSA http://www.ayjs.net";
            var c_rsa = new RSAShared(RSAType.RSA2, System.Text.Encoding.UTF8, c_privateKey, zfb_publicKey);
            var zfb_rsa = new RSAShared(RSAType.RSA2, System.Text.Encoding.UTF8, zfb_privateKey, c_publicKey);

然后就是模拟两者的过程

     string data = "AY讲解RSA http://www.ayjs.net";
            var c_rsa = new RSAShared(RSAType.RSA2, System.Text.Encoding.UTF8, c_privateKey, zfb_publicKey);
            var zfb_rsa = new RSAShared(RSAType.RSA2, System.Text.Encoding.UTF8, zfb_privateKey, c_publicKey);

            //商户发送信息
            string data_Str = c_rsa.Encrypt(data);
            Console.WriteLine("商户加密后的数据:" + data_Str);
            //商户开始签名:
            string sign_data_Str = c_rsa.Sign(data_Str);
            Console.WriteLine("商户签名加密后的数据:" + sign_data_Str);

            //模拟发送 signStr
            Console.WriteLine("商户发送了数据.....数据{0},签名{1}", data_Str, sign_data_Str);

            //支付宝收到信息
            Console.WriteLine("支付宝收到了数据.....开始验证");
            //验证消息
            bool signVerify = zfb_rsa.Verify(data_Str, sign_data_Str);
            if (signVerify)
            {
                //是商户发送的信息
                Console.WriteLine("商家发的数据验证通过");
                //处理你的数据
                string _c_send_data = zfb_rsa.Decrypt(data_Str);
                Console.WriteLine("支付宝:\"商户发的信息:" + _c_send_data);
                Console.WriteLine("支付宝数据处理成功!");
                Console.WriteLine("支付宝开始回调...有请求毕竟有响应");

                string zfb_send_data = "AY讲解RSA,你的文章讲的还可以";
                //支付宝加密
                string zfb_data_Str = zfb_rsa.Encrypt(zfb_send_data);
                Console.WriteLine("支付宝反馈的加密的数据:" + zfb_data_Str);
                //支付宝生成签名
                string zfb_data_sign_Str = zfb_rsa.Sign(zfb_data_Str);
                Console.WriteLine("支付宝反馈的签名加密后的数据:" + zfb_data_sign_Str);
                //模拟发送 zfb_data_Str
                Console.WriteLine("支付宝发送了数据.....数据{0},签名{1}", zfb_data_Str, zfb_data_sign_Str);

                //商户收到信息
                Console.WriteLine("商户收到了Response数据.....开始验证");
                bool _c_signVerify = c_rsa.Verify(zfb_data_Str, zfb_data_sign_Str);
                if (_c_signVerify)
                {
                    //是支付宝发回的数据
                    Console.WriteLine("支付宝返回的数据验证通过");
                    //处理你的数据
                    string _zfb_back_send_data = c_rsa.Decrypt(zfb_data_Str);
                    Console.WriteLine("商户:\"支付宝发的信息:" + _zfb_back_send_data);
                    Console.WriteLine("支付宝返回的数据处理成功!");
                }
                else
                {
                    //不是支付宝发送的数据
                    Console.WriteLine("支付宝发的信息不对,被篡改了吧.");
                }

            }
            else
            {
                //不是商户发送的数据
                Console.WriteLine("你这个商户发的信息不对,被篡改了吧.");
            }

效果:(这里对 发送的数据签名呢,还是对发送的数据加密后,然后求签名,不知道是哪个,我是对加密后的处理的),看了会,感觉应该对明文签名

image.png

====================www.ayjs.net       杨洋    wpfui.com        ayui      ay  aaronyang=======请不要转载谢谢了。=========

自己 只有在了解后,才 能真正实践下。



继续试试为了下支付宝的那个工具

根据秘钥长度 2048 是RSA2  ,1024是RSA

image.png

image.png

image.png

这样就签名好了


因为一开始是RSA2加密的,所以我们使用底部的签名 的内容,到第三个tab使用


哎呀,第三个,我没用支付宝的公钥,那个就是你申请成功后,支付宝给你的 公钥,你的公钥是给支付宝的。

image.png

这里不测试了。

最后1个tab就是验证自己的 公钥私钥是不是一对

image.png

第4个是 转换用的, java和.net 生成的 私钥不兼容的。转换下。

image.png


====================www.ayjs.net       杨洋    wpfui.com        ayui      ay  aaronyang=======请不要转载谢谢了。=========



我终于理解了。


推荐您阅读更多有关于“net core2,”的文章

猜你喜欢

额 本文暂时没人评论 来添加一个吧

发表评论

必填

选填

选填

必填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

  查看权限

合肥科大智能常年招聘C# .NET CORE,vue前端,JAVA开发,有想换工作的私聊我AY唯一QQ:875556003和AY交流

抖音号:wpfui,可以看到我的很多作品效果,私活合作请qq联系我

AYUI8社区版Github地址:前往获取

作者:杨洋(AaronYang简称AY,安徽六安人)目前是个人,还没公司AY唯一QQ:875556003和AY交流

高中学历,2015年1月17日开始,兴趣学习研究WPF,目前工作繁忙,不接任何活

声明:AYUI7个人与商用免费,源码可购买。部分DEMO不免费.AY主要靠卖技术服务挣钱

不是从我处购买的ayui7源码,我不提供任何技术服务,如果你举报从哪里买的,我可以帮你转正为我的客户,并送demo

查看捐赠

AYUI7.X MVC教程 更新如下:

第一课 第二课 程序加密教程

vs2015 企业版密钥HM6NR-QXX7C-DFW2Y-8B82K-WTYJV

vs2017 企业版密钥NJVYC-BMHX2-G77MM-4XJMR-6Q8QF

标签列表