用C#写一个资源加密的方法
时间: 2023-12-05 16:03:56 浏览: 27
以下是一个简单的资源加密方法,使用C#编写:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
public static class ResourceEncryptor
{
// 加密密钥
private static readonly byte[] Key = { 1, 2, 3, 4, 5, 6, 7, 8 };
// 向量
private static readonly byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8 };
public static void EncryptResource(string filePath)
{
// 读取文件内容
byte[] fileData = File.ReadAllBytes(filePath);
// 创建加密算法对象
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
// 创建加密流
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
// 将文件内容写入加密流
csEncrypt.Write(fileData, 0, fileData.Length);
csEncrypt.FlushFinalBlock();
// 获取加密后的文件内容
byte[] encryptedData = msEncrypt.ToArray();
// 将加密后的文件内容写入原文件
File.WriteAllBytes(filePath, encryptedData);
}
}
}
}
}
```
使用时,只需调用 `EncryptResource` 方法并传入要加密的文件路径即可。注意,使用此方法加密的文件需要使用相同的密钥和向量进行解密。