四时宝库

程序员的知识宝库

C# RSA加密解密 简单样例(.net rsa加密)

在C#中,可以使用RSA算法进行加密和解密。

RSA是一种非对称加密算法,它使用公钥进行加密,私钥进行解密。

以下是一个简单的示例代码,演示如何在C#中使用RSA进行加密和解密:

using System;
using System.Security.Cryptography;
using System.Text;

public class RsaEncryptionExample
{
    public static byte[] Encrypt(string plainText, RSAParameters publicKey)
    {
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            rsa.ImportParameters(publicKey);

            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] encryptedBytes = rsa.Encrypt(plainBytes, true);
            return encryptedBytes;
        }
    }

    public static string Decrypt(byte[] encryptedBytes, RSAParameters privateKey)
    {
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            rsa.ImportParameters(privateKey);

            byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, true);
            string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
            return decryptedText;
        }
    }

    public static void Main()
    {
        string plainText = "Hello, world!";

        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            RSAParameters publicKey = rsa.ExportParameters(false);
            RSAParameters privateKey = rsa.ExportParameters(true);

            byte[] encryptedBytes = Encrypt(plainText, publicKey);
            string decryptedText = Decrypt(encryptedBytes, privateKey);

            Console.WriteLine("Plain Text: " + plainText);
            Console.WriteLine("Encrypted Bytes: " + Convert.ToBase64String(encryptedBytes));
            Console.WriteLine("Decrypted Text: " + decryptedText);
        }
    }
}

这个示例使用了RSACryptoServiceProvider类来生成RSA公钥和私钥。

然后,使用公钥对明文进行加密,使用私钥对密文进行解密。

请注意,生成的公钥和私钥是随机生成的,并且在加密和解密过程中需要保持一致。

希望这个示例对您有帮助!

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接