C# RSA 加密 解密

 

public string publicKey = @"<RSAKeyValue><Modulus>xitE89Au1niOcLXTxtrdRxz9Q5rd3xczS83aSkmncJcRTj8jGa8HUi+cpAsh80qv9ayLAQF3zJgP6C4nGGJIqauguCDdONjUQHtrgyct/Gr1tL3q3ay/awJD6tujfnh0kOr57sxvo+yvHW+fXni7DUvGzJfZM1tlIC1avUy+oIU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        public string privateKey = @"<RSAKeyValue><Modulus>xitE89Au1niOcLXTxtrdRxz9Q5rd3xczS83aSkmncJcRTj8jGa8HUi+cpAsh80qv9ayLAQF3zJgP6C4nGGJIqauguCDdONjUQHtrgyct/Gr1tL3q3ay/awJD6tujfnh0kOr57sxvo+yvHW+fXni7DUvGzJfZM1tlIC1avUy+oIU=</Modulus><Exponent>AQAB</Exponent><P>xsN952COqpnuGSAW1GYQeH+Oqy8y0z5xu+HYQxmikfMonHdmymEk0TCTa4pjwg6i+n9uHf4vkwzym4hMWJN22w==</P><Q>/zvxeW+7Px0PIcMKvryw3eONiOaqUQXZaHNEmeJpt/Qj5XQBTGmgE1ATe/O+Bf8j2ri2pNf1aZwPEzDhPZh0Hw==</Q><DP>uSxnn6fVQhsmN0IuArMTpS8xO0o9j5AdZWyCjgDT9CUVMLAMk37tTfZzYT0Msz3vmHAfptGogNcPLtdMSTkZAQ==</DP><DQ>/bcdrGSIEw4U66/Rr5csjfXUzQDWz2HsIytqRzpNcwIq6L1vSQE6kdgo9i9udtGQV60ESksu9oOebKpLTQqOaw==</DQ><InverseQ>DkUyMqq8MQEeW4vHsnMgttENTBGKzJDjvU/C9s7tPM4i82ls/Dh3NvSF4liYVnvsvt17asL9pqZQHPvTIQqBCg==</InverseQ><D>Qj9y1KMzFUXGMI3Il4DRWpWpYTFjnNHvtxbBM/Z9gFkwUt0uicaGhwYdsoV6OxAr1NByw8pO11m6b58GONOagG52xZBWgoXzXWk0bpKEUqLlAxOI3p3Bs3yI+dp49eX0GfuY/JW64Uil58BIhDZ4Jsc5l4fRdrta3kLtFdMuJn0=</D></RSAKeyValue>";
       
        /// <summary>
        /// RSA公钥加密
        /// </summary>
        /// <param name="value">待加密的明文</param>
        /// <param name="publicKey">公钥</param>
        /// <param name="usePkcs8">是否使用pkcs8填充</param>
        /// <returns></returns>
        public  string RsaEncrypt(string value,  bool usePkcs8 = false)
        {
            if (string.IsNullOrEmpty(value)) return value;

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
            rsa.FromXmlString(publicKey);//将公钥导入到RSA对象中,准备加密;
            var buffer = Encoding.UTF8.GetBytes(value);
            buffer = rsa.Encrypt(buffer, false);
            return Convert.ToBase64String(buffer);          
        }

 

        /// <summary>
        /// RSA私钥解密
        /// </summary>
        /// <param name="value">密文</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="usePkcs8">是否使用pkcs8填充</param>
        /// <returns></returns>
        public string RsaDecrypt(string value,  bool usePkcs8 = false)
        {
            if (string.IsNullOrEmpty(value)) return value;

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
            rsa.FromXmlString(privateKey);//将私钥导入RSA中,准备解密;          
            var buffer = rsa.Decrypt(Convert.FromBase64String(value), false);
            
            return Encoding.UTF8.GetString(buffer);
        }

posted @ 2022-08-01 09:41  YuanY  阅读(3904)  评论(0编辑  收藏  举报