C# .NET RSA 加密解密

namespace Utility.Security
{
    /// <summary>
    /// RSA加密解密
    /// </summary>
    public class RSAUtil
    {
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="str">需要加密的字符串</param>
        /// <param name="encryptKey">密钥</param>
        /// <returns>加密后的字符串</returns>
        public static string RSAEncrypt(string str, string encryptKey)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            byte[] privKeyBytes = Convert.FromBase64String(encryptKey);
            AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.CreateKey(privKeyBytes);
            IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());
            signer.Init(true, asymmetricKeyParameter);
            //加密
            byte[] encryptBytes = signer.ProcessBlock(bytes, 0, bytes.Length);
            string rsaString = Convert.ToBase64String(encryptBytes);
            return rsaString;
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="str">需要解密的字符串</param>
        /// <param name="decryptKey">密钥</param>
        /// <returns>解密后的字符串</returns>
        public static string RSADecrypt(string str, string decryptKey)
        {
            byte[] strBytes = Convert.FromBase64String(str);
            byte[] keyBytes = Convert.FromBase64String(decryptKey);
            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
            IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());
            signer.Init(false, asymmetricKeyParameter);
            byte[] decryptedBytes = signer.ProcessBlock(strBytes, 0, strBytes.Length);
            string decryptString = Encoding.UTF8.GetString(decryptedBytes);
            return decryptString;
        }
    }
}
—— 完 ——
相关推荐
评论

立 为 非 似

中 谁 昨 此

宵 风 夜 星

。 露 , 辰

文章点击榜

细 无 轻 自

如 边 似 在

愁 丝 梦 飞

。 雨 , 花