📜  用公钥加密,用私钥解密 c# Code Example(1)

📅  最后修改于: 2023-12-03 14:56:23.014000             🧑  作者: Mango

使用公钥加密,使用私钥解密 c# 代码示例

在信息安全领域中,加密是一项非常重要的工作。公钥加密和私钥解密是一种加密方式,是非对称加密的一种形式。公钥加密和私钥解密可以用于数字签名、数据加密等场合。在这篇文章中,我们将介绍如何使用 c# 开发语言实现使用公钥加密,使用私钥解密的功能。

基本知识

在公钥加密方案中,有两个密钥:公钥和私钥。公钥是用来加密数据的,可以向外公开;私钥是用来解密数据的,只能自己持有。因此,公钥加密和私钥解密可以实现信息的安全传输。

c# 代码示例
  1. 生成 RSA 密钥对
using System.Security.Cryptography;

public static void GenerateRsaKeyPair(out string publicKey, out string privateKey)
{
    using var rsa = new RSACryptoServiceProvider();
    publicKey = rsa.ToXmlString(false);
    privateKey = rsa.ToXmlString(true);
}
  1. 使用公钥加密数据
using System.Security.Cryptography;
using System.Text;

public static string RsaEncrypt(string publicKey, string plainText)
{
    using var rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(publicKey);
    var bytes = Encoding.UTF8.GetBytes(plainText);
    var encryptedBytes = rsa.Encrypt(bytes, false);
    return Convert.ToBase64String(encryptedBytes);
}
  1. 使用私钥解密数据
using System.Security.Cryptography;
using System.Text;

public static string RsaDecrypt(string privateKey, string cipherText)
{
    using var rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(privateKey);
    var encryptedBytes = Convert.FromBase64String(cipherText);
    var decryptedBytes = rsa.Decrypt(encryptedBytes, false);
    return Encoding.UTF8.GetString(decryptedBytes);
}
使用示例
string publicKey, privateKey;
GenerateRsaKeyPair(out publicKey, out privateKey);
var plainText = "Hello, world!";
var cipherText = RsaEncrypt(publicKey, plainText);
var decryptedText = RsaDecrypt(privateKey, cipherText);
Console.WriteLine(decryptedText); // Output: Hello, world!
结论

使用 c# 编程语言,我们可以轻松地实现使用公钥加密、使用私钥解密的功能。公钥加密和私钥解密是非常重要的加密方式,在信息安全领域中被广泛应用。使用这种方法加密的数据可以实现安全传输,受到保护,不易被恶意程序解密。