在我的一个小项目中,我需要计算一个函数的散列。
我有一个PHP哈希操作示例
$pass = "123456";
$mysalt = strrev($pass);
echo hash_pbkdf2('sha1', $pass, $mysalt, 1000, 32); //using the PHP inbuilt function
echo "</br>";
include_once('PasswordHash.php');
echo pbkdf2('sha1', $pass, $mysalt, 1000, 16); //using external code它们具有相同的输出:523d904c8f2df96634d9eed3b444838e
现在,我需要我的代码向后兼容生成的C#,因为密码将由PHP进行验证。请求将由C#应用程序发送。
下面是我尝试过的: output = 8e59ead5f90c6af11cf80641d51c241c
public static class Program
{
public static string ReverseString(this string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main(string[] args)
{
var pass = "123456";
byte[] salt = Encoding.ASCII.GetBytes(pass.ReverseString());
//https://github.com/defuse/password-hashing/blob/master/PasswordHash.cs
//was getting error salt not 8 byte,
//http://stackoverflow.com/questions/1647481/what-is-the-c-sharp-equivalent-of-the-php-pack-function
salt = Pack(pass.ReverseString());
var hash = PasswordHash.PBKDF2(pass, salt, 1000, 16);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", string.Empty).ToLower());
Console.ReadKey();
}
public static byte[] Pack(string salt)
{
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms))
{
var data = Encoding.ASCII.GetBytes(salt);
bw.Write(data.Length + 4); // Size of ASCII string + length (4 byte int)
bw.Write(data);
}
return ms.ToArray();
}
}
}发布于 2014-05-14 13:57:48
看起来,Pack方法是不必要的,但是您的salt必须至少是8个字节。
$pass = "12345678";
$mysalt = strrev($pass);
echo hash_pbkdf2('sha1', $pass, $mysalt, 1000, 32); //using the PHP inbuilt function这将输出381dae25b08b6f141671c74715961b1b。
此C#代码提供相同的输出。
public static class Program
{
public static string ReverseString(this string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main(string[] args)
{
var pass = "12345678";
byte[] salt = Encoding.ASCII.GetBytes(pass.ReverseString());
//https://github.com/defuse/password-hashing/blob/master/PasswordHash.cs
//was getting error salt not 8 byte,
//https://stackoverflow.com/questions/1647481/what-is-the-c-sharp-equivalent-of-the-php-pack-function
var hash = PasswordHash.PBKDF2(pass, salt, 1000, 16);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", string.Empty).ToLower());
Console.ReadKey();
}
}从您的评论来看,您可能是在需求约束下进行开发的。如果您无法控制salt周围的需求,则可以查看this answer。
https://stackoverflow.com/questions/23593645
复制相似问题