有什么方法可以不使用流来加密字节数组吗??
最佳答案
事实上,您根本不需要使用任何流来操作字节。 您唯一需要做的就是调用 ICryptoTransform 的 TransformFinalBlock() 方法,它可以是从 SymmetricAlgorithm 类派生的任何算法的加密器或解密器
public class CryptoProvider
{
private SymmetricAlgorithm _algorithm = new RijndaelManaged();
public byte[] EncryptData(byte[] data, string password)
{
GetKey(password);
ICryptoTransform encryptor = _algorithm.CreateEncryptor();
byte[] cryptoData = encryptor.TransformFinalBlock(data, 0, data.Length);
return cryptoData;
}
public byte[] DecryptData(byte[] cryptoData, string password)
{
GetKey(password);
ICryptoTransform decryptor = _algorithm.CreateDecryptor();
byte[] data = decryptor.TransformFinalBlock(cryptoData, 0, cryptoData.Length);
return data;
}
private void GetKey(string password)
{
byte[] salt = new byte[8];
byte[] passwordBytes = Encoding.ASCII.GetBytes(password);
int length = Math.Min(passwordBytes.Length, salt.Length);
for (int i = 0; i < length; i++)
salt[i] = passwordBytes[i];
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt);
_algorithm.Key = key.GetBytes(_algorithm.KeySize / 8);
_algorithm.IV = key.GetBytes(_algorithm.BlockSize / 8);
}
}
关于c# - .NET 加密字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/605498/