1 回答
TA贡献1853条经验 获得超6个赞
在对您的代码进行一些测试后,我最终使用了这两种方法。
我认为您的代码的主要问题是Decrypt从未对plainTextBytes-array做任何事情。
private static string Encrypt(byte[] plainTextBytes)
{
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
}
}
return Convert.ToBase64String(cipherTextBytes);
}
解密
public static byte[] Decrypt(string base64)
{
byte[] cipherTextBytes = Convert.FromBase64String(base64);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (BinaryReader srDecrypt = new BinaryReader(cryptoStream))
{
return srDecrypt.ReadBytes(cipherTextBytes.Length);
}
}
}
}
- 1 回答
- 0 关注
- 196 浏览
添加回答
举报