如何使用'System.Security.Cryptography.AesManaged'来加密byte []?

Chr*_*ris 13 c# encryption cryptography

基本上我想使用System.Security.Cryptography.AesManaged(或者更好的类,如果你认为有一个?)来获取一个字节数组并使用给定的对称密钥创建另一个加密的字节数组(我假设我需要一?).

我还需要改变这个程序的方法.

关键是我可以加密存储的密码.我假设有一种简单的方法可以做到这一点?

谢谢

Mic*_*tta 12

编辑:注意eed3si9n的编辑...我同意,对称加密是密码的不错选择.请改用哈希(而不是 MD5).这是一个非常完整的例子.

一个简单的例子:

byte[] clear = GetCleartext();
HashAlgorithm sha2 = SHA256CryptoServiceProvider.Create();
byte[] hashed = sha2.ComputeHash(clear);
Run Code Online (Sandbox Code Playgroud)

要验证正确的密码,您将对提供的密码运行相同的计算,并将结果与​​数据库中的哈希值进行比较.

最好在明文中添加salt(随机数据)以避免彩虹表攻击.基本上,在散列之前,将已知的随机生成的值(该用户唯一的值)附加到明文.

  • 我需要密码将它们传递给另一个服务. (3认同)

Chr*_*ris 12

这是我最终做的,受到(旧版本)迈克尔答案的启发:

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 鉴于你上面的代码,你每次都会得到相同的密钥,这很好,但是你每次都会得到相同的IV,这很糟糕**.我很确定IV应该特定于您正在加密的数据,而Key可以是"全局的". (7认同)

Eug*_*ota 8

在C#中简单加密和解密数据.

编辑:对于密码,我建议使用BCrypt而不是进行双向加密,除非您确实需要恢复原始密码.通常,您只需要有人知道密码,而不是密码本身.