在要求输入邮箱的文本域,请填写真实的邮件地址。非真实邮件地址,将收不到回复信息。

非对称解密RSA

C# 清风 10℃ 0评论

   /// <summary>
   /// 非对称解密RSA
   /// </summary>
   public  class PemRsaEncrypt
    {
       /// <summary>
       /// RSA解密
       /// </summary>
       /// <param name="filePath">pem私钥证书路径</param>
       /// <param name="content">加密的文本</param>
       /// <returns>解密后的明文</returns>
       public static string Decrypt(string filePath,string content)
       {
           using (var fileStream = System.IO.File.OpenText(filePath))
           {
               string privateJavaKey = fileStream.ReadToEnd().Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "").Replace("\r", "").Replace("\n", "");
               RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateJavaKey));
               string xmlPrivateKey = string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                            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()));

               RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
               byte[] cipherbytes;
               rsa.FromXmlString(xmlPrivateKey);
               cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
               return Encoding.UTF8.GetString(cipherbytes);
           }
       }
    }

转载请注明:清风博客 » 非对称解密RSA

喜欢 (0)or分享 (0)
支付宝扫码打赏 微信打赏
发表我的评论
取消评论

CAPTCHA Image
Reload Image
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址