問(wèn)題描述
基本上我想使用 System.Security.Cryptography.AesManaged (或者更好的類,如果你認(rèn)為有的話?)獲取一個(gè)字節(jié)數(shù)組并使用給定的對(duì)稱密鑰創(chuàng)建另一個(gè)加密字節(jié)數(shù)組(我假設(shè)我需要一個(gè)嗎?).
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?).
我還需要逆向這個(gè)過(guò)程的方法.
I also will need the way to reverse this procedure.
這樣做的目的是讓我可以加密存儲(chǔ)的密碼.我認(rèn)為有一種簡(jiǎn)單的方法可以做到這一點(diǎn)?
The point of this is so i can encrypt stored passwords. I assume there's a simple way to do this?
謝謝
推薦答案
你真的應(yīng)該在每次加密時(shí)生成一個(gè)隨機(jī) IV,不像我下面的古老代碼:
You really should generate a random IV each time you encrypt, unlike my ancient code below:
這是我最后所做的,靈感來(lái)自(舊版)邁克爾的回答:
Here's what i did in the end, inspired by (an older version of) michael's answer:
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();
}
這篇關(guān)于如何使用“System.Security.Cryptography.AesManaged"加密一個(gè)字節(jié)[]?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!