C# SHA256WithRSA 签名、验签

  • 当前框架.net core 2.2,.net core3.0及其以上不需要重写FromXmlString(string)方法,直接使用new RSACryptoServiceProvider().FromXmlString(key);
  • 如若使用FromXmlString()方法报错 System.PlatformNotSupportedException:“Operation is not supported on this platform.” 请检查项目所使用的框架,或者重写FromXmlString(string)方法

使用SHA256WithRSA签名

        /// 
        /// RSA私钥,从Java格式转.net格式(不依赖第三方包)
        /// 
        /// 私钥
        /// 
        public static string RSAPrivateKeyJava2DotNet(string privateKey)
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
            return string.Format("{0}{1}

{2}

{3}{4}{5}{6}{7}
", Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())); } /// /// 私钥签名 /// /// /// /// public static string Sign(string contentForSign, string privateKey) { var netKey = RSAPrivateKeyJava2DotNet(privateKey); //转换成适用于.net的私钥 var rsa = FromXmlString(netKey); //.net core2.2及其以下版本使用,重写FromXmlString(string)方法 var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(netKey); //.net core3.0直接使用,不需要重写 var rsaClear = new RSACryptoServiceProvider(); var paras = rsa.ExportParameters(true); rsaClear.ImportParameters(paras); //签名返回 using (var sha256 = new SHA256CryptoServiceProvider()) { var signData = rsa.SignData(Encoding.UTF8.GetBytes(contentForSign), sha256); return Convert.ToBase64String(signData); } }

使用SHA256WithRSA验签


        /// 
        /// RSA公钥,从Java格式转.net格式(不依赖第三方包)
        /// 
        /// 
        /// 
        public static string RSAPublicKeyJava2DotNet(string publicKey)
        {
            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
            return string.Format("{0}{1}",
              Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
              Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
        }

        ///         
        /// RSA签名验证
        ///  
        /// 签名
        /// 验证的字符串
        /// 公钥
        /// 是否相同,true验证成功,false验证失败。
        public static bool VerifySignature(string encryptSource, string compareString, string publicKey)
        {
            try
            {
                //.net core2.2及其以下版本使用,重写FromXmlString(string)方法
                using (RSACryptoServiceProvider rsa = FromXmlString(RSAPublicKeyJava2DotNet(publicKey)))
                {
                    rsa.FromXmlString(netKey); //.net core3.0直接使用,不需要重写
                    byte[] signature = Convert.FromBase64String(encryptSource);
                    SHA256Managed sha256 = new SHA256Managed();
                    RSAPKCS1SignatureDeformatter df = new RSAPKCS1SignatureDeformatter(rsa);
                    df.SetHashAlgorithm("SHA256");
                    byte[] compareByte = sha256.ComputeHash(Encoding.UTF8.GetBytes(compareString));

                    return df.VerifySignature(compareByte, signature);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

重写FromXmlString()方法


        /// 
        /// 重写FromXmlString方法
        /// 
        /// 
        /// 
        public static RSACryptoServiceProvider FromXmlString(string xmlString)
        {
            var rsa = new RSACryptoServiceProvider();
            RSAParameters parameters = new RSAParameters();
            XmlDocument 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 = Convert.FromBase64String(node.InnerText); break;
                        case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break;
                        case "P": parameters.P = Convert.FromBase64String(node.InnerText); break;
                        case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break;
                        case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break;
                        case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break;
                        case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break;
                        case "D": parameters.D = Convert.FromBase64String(node.InnerText); break;
                    }
                }
            }
            else
            {
                throw new Exception("Invalid XML RSA key.");
            }

            rsa.ImportParameters(parameters);
            return rsa;
        }

参考文章
  • https://blog.csdn.net/qq_32002821/article/details/109801984
  • https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.rsapkcs1signaturedeformatter?view=netframework-4.8

你可能感兴趣的:(C# SHA256WithRSA 签名、验签)