2

我们之前使用 C#.net 2.0 创建 Web 应用程序。

使用以下代码对用户密码进行哈希处理并存储在数据库中。

private const string encryptionKey = "AE09F72B007CAAB5";

HMACSHA1 hash = new HMACSHA1();
hash.Key = HexToByte(encryptionKey);
encodedPassword = Convert.ToBase64String(
    hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

现在我们打算迁移到 php。

因此,当用户想要重新加入时,我们会遇到问题。

应该使用该方法的什么 php 等效项,以便数据库中的哈希值起作用?

例如,编码密码是 pa55w0rd 得到的哈希值是 oK9NOVhpTkxLoLfvh1430SFb5gw=

谢谢你。

4

4 回答 4

2

在您的 C# 应用程序中,您以两种不同的方式生成 byte[] 数组,结果略有不同。您的 PHP 脚本需要准确地模拟它们。

hash.Key = HexToByte(encryptionKey)
你传入一个 16 个字符长的字符串并得到一个 8 个字节的数组,就像hash.Key = new byte[]{0xAE, 0x09, 0xF7, 0x2B, 0x00, 0x7C, 0xAA, 0xB5 };但是
string password = "pa55w0rd";
byte[] b = Encoding.Unicode.GetBytes(password)
由于 Encoding.Unicode,返回一个包含 16 个元素的数组,例如在您的 php 脚本中,您可以使用$data = mb_convert_encoding($password, 'UTF16-LE')byte[] b = { 0x112, 0x0, 0x97, 0x0, 0x53, 0x0, 0x53, 0x0, 0x119, 0x0, 0x48, 0x0, 0x114, 0x0,0x100, 0x0 }
将 $password 的编码更改为 utf-16le以实现类似的结果. hash_hmac() 不知道任何编码会将字符串视为 16 字节单字节编码字符串,就像 .net 中的 hash.ComputeHash(byte[]) 一样。

<?php
$password = "pa55w0rd";
$key = HexToBytes("AE09F72B007CAAB5"); // 8 bytes, hex

// $to must be 'UTF-16LE' // $from depends on the "source" of $password $data = mb_convert_encoding($password, 'UTF-16LE', 'ASCII');

// I've saved this script as an ascii file -> the string literal is ASCII encoded // therefore php's strlen() returns 8 for $password and 16 for $data // this may differ in your case, e.g. if the contents of $password comes from a // http-request where the data is utf-8 encoded. Adjust the $from parameter for // mb_convert_encoding() accordingly echo 'Debug: |data|=', strlen($data), ' |password|=', strlen($password), "\n";

$h = HexToBytes(hash_hmac('sha1', $data, $key)); echo 'hmac-sha1: ', base64_encode($h);

function HexToBytes($s) { // there has to be a more elegant way... return join('', array_map('chr', array_map('hexdec', str_split($s, 2)))); }

印刷
调试:|数据|=16 |密码|=8
hmac-sha1: ok9NOVhpTkxLoLfvh1430SFb5gw=

于 2009-06-19T13:12:53.963 回答
0

使用 .Net 版本的 PHP ( Phalanger ) 或使用 .Net 网络服务进行编码/解码不是一种选择?

于 2009-06-19T10:00:48.373 回答
0

尝试类似:

<?php
 $key = "AE09F72B007CAAB5";
 echo base64_encode(hash_hmac("sha1", "test", $key, true));
?>
于 2009-06-19T10:20:03.967 回答
0

在 C# 中,哈希的默认格式是 HEX(AE09F72B007CAAB5 是一个十六进制数字)。PHP 默认为 Base64 格式。解决您的问题是将base64字符串转换为php中的十六进制的问题

于 2009-06-19T10:20:55.090 回答