c# .net AES 解密 AES 加密
·
/// <summary>
/// 文件加密类
/// </summary>
public class FileEncryptTool
{
/// <summary>
/// 加密文件内容并写入-AES加密
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="content">加密内容</param>
/// <param name="pwd">加密密匙</param>
public void EncryptFile(string path, byte[] content, string pwd)
{
if (File.Exists(path))
{
File.Delete(path);
}
byte[] result;
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
result = AESTool.AESEncrypt(content, pwd);
fs.Position = 0;
fs.Write(result, 0, result.Length);
fs.Flush();
}
result = null;
}
/// <summary>
/// 解密文件内容-AES解密
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="pwd">加密密匙</param>
public ReturnModel DecryptFile(string path, string pwd)
{
ReturnModel returnModel = new ReturnModel();
byte[] read;
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
if (fs.Length < 1)
{
return returnModel;
}
read = new byte[fs.Length];
fs.Position = 0;
fs.Read(read, 0, read.Length);
returnModel.MessageOrString = Encoding.UTF8.GetString(AESTool.AESDecrypt(read, pwd));
read = null;
return returnModel;
}
}
}
/// <summary>
/// AES操作类
/// </summary>
public class AESTool
{
static byte[] rd_buffer;
static IBufferedCipher cipher;
/// <summary>
/// AES加密
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string AESEncrypt(string input, string key)
{
byte[] plainText = Encoding.UTF8.GetBytes(input);
cipher = CipherUtilities.GetCipher("AES/ECB/PKCS5Padding");
cipher.Init(true, GetKeyBySeed(key));
string re = Convert.ToBase64String(cipher.DoFinal(plainText));
plainText = null;
cipher = null;
return re;
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
public static byte[] AESEncrypt(byte[] plainText, string key)
{
cipher = CipherUtilities.GetCipher("AES/ECB/PKCS5Padding");
cipher.Init(true, GetKeyBySeed(key));
return cipher.DoFinal(plainText);
}
public static KeyParameter GetKeyBySeed(string strKey)
{
byte[] seed = Encoding.UTF8.GetBytes(strKey);
using (SHA1CryptoServiceProvider nd = new SHA1CryptoServiceProvider())
{
rd_buffer = nd.ComputeHash(SHA1.Create().ComputeHash(seed));
seed = null;
return new KeyParameter(rd_buffer.Take(16).ToArray());
}
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static byte[] AESDecrypt(byte[] cipherText, string pwd)
{
cipher = CipherUtilities.GetCipher("AES/ECB/PKCS5Padding");
cipher.Init(false, GetKeyBySeed(pwd));
return cipher.DoFinal(cipherText);
}
}
更多推荐


所有评论(0)