C# RSA 文件 加密 解密

在 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" 的新文件中。

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值