如何使用System.Security.Cryptography.AesManaged加密字节[]? [英] How to use 'System.Security.Cryptography.AesManaged' to encrypt a byte[]?
本文介绍了如何使用System.Security.Cryptography.AesManaged加密字节[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我想使用System.Security.Cryptography.AesManaged(或更好的类,如果你认为有一个?)采取一个字节数组和创建另一个加密字节数组,使用给定的对称密钥(我假设i需要一个?)。
Basically i want to use System.Security.Cryptography.AesManaged (or a better class, if you think there is one?) to take one byte array and create another encrypted byte array, using a given symmetric key (i assume i'll need one?).
我还需要改变这个过程的方式。
I also will need the way to reverse this procedure.
这是我可以加密存储的密码。
The point of this is so i can encrypt stored passwords. I assume there's a simple way to do this?
感谢
推荐答案
private string Encrypt(string input)
{
return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(input)));
}
private byte[] Encrypt(byte[] input)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes("hjiweykaksd", new byte[] { 0x43, 0x87, 0x23, 0x72, 0x45, 0x56, 0x68, 0x14, 0x62, 0x84 });
MemoryStream ms = new MemoryStream();
Aes aes = new AesManaged();
aes.Key = pdb.GetBytes(aes.KeySize / 8);
aes.IV = pdb.GetBytes(aes.BlockSize / 8);
CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
return ms.ToArray();
}
private string Decrypt(string input)
{
return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(input)));
}
private byte[] Decrypt(byte[] input)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes("hjiweykaksd", new byte[] { 0x43, 0x87, 0x23, 0x72, 0x45, 0x56, 0x68, 0x14, 0x62, 0x84 });
MemoryStream ms = new MemoryStream();
Aes aes = new AesManaged();
aes.Key = pdb.GetBytes(aes.KeySize / 8);
aes.IV = pdb.GetBytes(aes.BlockSize / 8);
CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
return ms.ToArray();
}
这篇关于如何使用System.Security.Cryptography.AesManaged加密字节[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文