在 C# 中使用 RSA 进行文件的加密与解密可以按照以下步骤操作:(仅供参考)
生成 RSA 公钥和私钥对。
using System;
using System.Security.Cryptography;
public class Program
{
public static void Main()
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
// 获取公钥和私钥字符串
string publicKeyString = rsa.ToXmlString(false);
string privateKeyString = rsa.ToXmlString(true);
Console.WriteLine("Public Key:\n" + publicKeyString);
Console.WriteLine("\nPrivate Key:\n" + privateKeyString);
}
}
}
运行上述代码将会输出生成的公钥和私钥字符串。
使用公钥对要加密的数据进行加密。
using System;
using System.IO;
using System.Security.Cryptography;
public class Program
{
public static byte[] EncryptFile(string filePath, string publicKey)
{
using (RSA rsa = RSA.Create())
{
rsa.FromXmlString(publicKey);
using (StreamReader reader = File.OpenText(filePath))
{
byte[] dataBytes = Convert.FromBase64String(reader.ReadLine());
return rsa.Encrypt(dataBytes, false);
}
}
}
public static void Main()
{
string filePath = "path_to_your_file";
// 调用函数进行加密并保存到新文件
byte[] encryptedData = EncryptFile(filePath, publicKeyString);
File.WriteAllBytes("encrypted_file", encryptedData);
}
}
其中 filePath 为需要加密的文件路径,publicKey 为之前生成的公钥字符串。该代码将会从指定文件中读取内容,然后使用公钥对内容进行加密,最后将结果写入名为 "encrypted_file" 的新文件中。
使用私钥对已经加密的数据进行解密。
using System;
using System.IO;
using System.Security.Cryptography;
public class Program
{
public static byte[] DecryptFile(byte[] encryptedData, string privateKey)
{
using (RSA rsa = RSA.Create())
{
rsa.FromXmlString(privateKey);
return rsa.Decrypt(encryptedData, false);
}
}
public static void Main()
{
byte[] encryptedData = File.ReadAllBytes("encrypted_file");
// 调用函数进行解密并保存到新文件
byte[] decryptedData = DecryptFile(encryptedData, privateKeyString);
File.WriteAllBytes("decrypted_file", decryptedData);
}
}
其中 encryptedData 为之前加密得到的二进制数据,privateKey 为之前生成的私钥字符串。该代码将会使用私钥对传入的加密数据进行解密,并将结果写入名为 "decrypted_file" 的新文件中。