小智 15
实际上,您根本不需要使用任何流来操作字节.您唯一需要的是调用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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6362 次 |
| 最近记录: |