C# RSA 非对称加密算法

2023年4月25日 886点热度 0人点赞 0条评论
内容纲要

注意,
C# RSA 只能导入导出 PKCS1 的公钥,不能处理 PKCS8 的。否则会报错。
C# RSA 可以导出导入 PCKS8 的私钥,可以按照 pem 格式处理,也可以按照文本格式处理,

示例如下:

using Newtonsoft.Json;

void Main()
{
    var keySize = 2048;

    var rsaCryptoServiceProvider = new RSACryptoServiceProvider(keySize);

    // 打印私钥、公钥
    Convert.ToBase64String(rsaCryptoServiceProvider.ExportPkcs8PrivateKey()).Dump();
    Convert.ToBase64String(rsaCryptoServiceProvider.ExportRSAPublicKey()).Dump();

    var parameters = rsaCryptoServiceProvider.ExportParameters(true);
    // 加密后的字符串
    var cipherText = Encrypt("hello world", parameters);

    // 解密后的字符串
    var plainText = Decrypt(cipherText, parameters);
    Console.WriteLine(plainText);

}

// 加密
public string Encrypt(string data, RSAParameters key)
{

    using (var rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportParameters(key);
        var byteData = Encoding.UTF8.GetBytes(data);
        var encryptData = rsa.Encrypt(byteData, false);
        return Convert.ToBase64String(encryptData);
    }
}

// 解密
public string Decrypt(string cipherText, RSAParameters key)
{

    using (var rsa = new RSACryptoServiceProvider())
    {
        var cipherByteData = Convert.FromBase64String(cipherText);
        rsa.ImportParameters(key);

        var encryptData = rsa.Decrypt(cipherByteData, false);
        return Encoding.UTF8.GetString(encryptData);
    }
}

导出导入公钥:


        /// <summary>
        /// 导入公钥
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        private static RSACryptoServiceProvider ImportPublicKeyFromPEM(RSACryptoServiceProvider rsa, string publicKey)
        {
            publicKey = publicKey
            .Replace("-----BEGIN RSA PUBLIC KEY-----", "")
            .Replace("-----END RSA PUBLIC KEY-----", "")
            .Replace("-----BEGIN PUBLIC KEY-----", "")
            .Replace("-----END PUBLIC KEY-----", "")
                .Replace("\r", "")
                .Replace("\n", "");
            rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out var bytesRead);
            return rsa;
        }

        /// <summary>
        /// 导出公钥
        /// </summary>
        /// <param name="rsa"></param>
        /// <returns></returns>
        public static string ExportPublicKeyToPEM(RSACryptoServiceProvider rsa)
        {
            return rsa.ExportRSAPublicKeyPem();
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="encryptedMessage"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string Encrypt(byte[] encryptedMessage, out byte[] bytes)
        {
            // Decrypt the message using the public key  
            byte[] decryptedMessage = RsaPublic.Encrypt(encryptedMessage, false);
            bytes = decryptedMessage;
            string decryptedMessageString = Encoding.UTF8.GetString(decryptedMessage);
            return decryptedMessageString;
        }
        public static string Encrypt(string encryptedMessage)
        {
            // Decrypt the message using the public key  
            byte[] decryptedMessage = RsaPublic.Encrypt(Encoding.UTF8.GetBytes(encryptedMessage), false);

            string decryptedMessageString = Encoding.UTF8.GetString(decryptedMessage);
            return decryptedMessageString;
        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="encryptedMessage"></param>
        /// <returns></returns>
        public static string Decrypt(string encryptedMessage)
        {
            // Decrypt the message using the public key  
            byte[] decryptedMessage = RsaPublic.Decrypt(Encoding.ASCII.GetBytes(encryptedMessage), false);

            string decryptedMessageString = Encoding.UTF8.GetString(decryptedMessage);
            return decryptedMessageString;
        }
        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="encryptedMessage"></param>
        /// <returns></returns>
        public static string Decrypt(byte[] encryptedMessage)
        {
            // Decrypt the message using the public key  
            byte[] decryptedMessage = RsaPublic.Decrypt(encryptedMessage, false);

            string decryptedMessageString = Encoding.UTF8.GetString(decryptedMessage);
            return decryptedMessageString;
        }

痴者工良

高级程序员劝退师

文章评论