c# - C# PasswordDeriveBytes:似乎 Salt 无关紧要
问题描述
可能我误解了什么。以下代码通过 CryptDeriveKey 使用两种不同的盐生成两个相等的密钥。
那是控制台结果:
盐1:21 3e 18 a3 9a 8b 5f
--> 关键 da 89 ea 3d 91 08 20 98 20 e9 dc 45 d5 97 10 7f 8f 4a 52 15 26 68 ef 83
salt2:9e 分贝 4c 2b 49 b4 24
--> 关键 da 89 ea 3d 91 08 20 98 20 e9 dc 45 d5 97 10 7f 8f 4a 52 15 26 68 ef 83
我的错误是什么?
using System;
using System.Security.Cryptography;
namespace PasswordDeriveBytes_SaltDoesntMatter
{
class Program
{
// for usage in CreateAndPrintKeyAndSalt
private static readonly string password = "secret123";
private static readonly TripleDESCryptoServiceProvider cryptoServiceProvider = new TripleDESCryptoServiceProvider();
static void Main(string[] args)
{
byte[] salt1 = new byte[] { 33, 62, 24, 163, 154, 139, 95 };
byte[] salt2 = new byte[] { 158, 219, 76, 43, 73, 180, 36 };
// a TripleDESCryptoServiceProvider-instance for getting an IV
CreateAndPrintKeyAndSalt("salt1", salt1);
CreateAndPrintKeyAndSalt("salt2", salt2);
Console.ReadKey();
}
/// <summary>
/// print the salt and the CryptDeriveKey based on this salt
/// !! uses the const password and cryptoServiceProvider
/// </summary>
/// <param name="saltName">name of the used salt</param>
/// <param name="salt">the used salt</param>
/// <param name="cryptoServiceProvider"></param>
private static void CreateAndPrintKeyAndSalt(string saltName, byte[] salt)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);
byte[] aKey = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, cryptoServiceProvider.IV);
Console.WriteLine($"{saltName}: {ByteArrayInHexText(salt)} --> Key {ByteArrayInHexText(aKey)}");
}
/// <summary>
/// returns a Textstring of each byte in arr in hex-formatting separated by space
/// </summary>
/// <param name="arr">the array</param>
/// <returns>the formatted string</returns>
public static string ByteArrayInHexText(byte[] arr)
{
string s = "";
foreach (var item in arr)
{
s += $" {item:x2}";
}
return s.Substring(1);
}
}
}
解决方案
根据这个MSDN 博客:
调用 CryptDeriveKey 时,不使用在 PasswordDeriveBytes 对象上设置的盐和迭代计数,因此即使具有不同的盐和迭代计数也会产生相同的密钥,因为其余的输入也是相同的。
推荐阅读
- xquery - xQuery - 填充自定义数组
- symfony4 - FOSRestBundle - 在异常处理程序中使用来自约束的错误消息
- excel - 具有格式和范围的 PasteSpecial VBA
- excel - VBA,激活工作簿而不明确命名它
- sql - 使用 sum(column1$)/count(distinct(column2person) 的 SQL 脚本
- javascript - Redux 不更新 React 表单输入
- c++ - QT Json将许多数据保存到文件以及如何读取它
- javascript - 检查我的代码中按钮网格的背景颜色
- ios - 如何在 Coredata 中的相同实体之间创建多个关系?
- javascript - 使用 TypeORM 在 PostgreSQL 的一列中保存数据流