C# RSA Encryption: Code Guide
In C#, the RSACryptoServiceProvider class can be used to perform RSA encryption and decryption.
Firstly, you need to generate an RSA key pair. Here is an example:
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
// 生成密钥对
RSAParameters publicKey = rsa.ExportParameters(false); // 获取公钥
RSAParameters privateKey = rsa.ExportParameters(true); // 获取私钥
// TODO: 将公钥和私钥保存到安全地方
}
Next, you can use the generated public key for encryption and the private key for decryption. Here is an example:
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
// 导入私钥
rsa.ImportParameters(privateKey);
// 加密数据
byte[] dataToEncrypt = Encoding.UTF8.GetBytes("Hello World");
byte[] encryptedData = rsa.Encrypt(dataToEncrypt, true);
// 使用公钥解密
rsa.ImportParameters(publicKey);
byte[] decryptedData = rsa.Decrypt(encryptedData, true);
// 输出解密后的数据
string decryptedText = Encoding.UTF8.GetString(decryptedData);
Console.WriteLine(decryptedText);
}
Please note, this is just a simple example. In practice, you may need to handle the storage and management of keys, as well as be aware of size limitations when encrypting data.