<?php
$pwd = "test";
$crypted = base64_encode(pack("H*", sha1(utf8_encode($pwd))));
echo("$crypted");
?>
所以我在上面得到了这个 PHP 代码,我正在尝试将它转换为 C# 代码。我尝试了以下方法,但它没有相同的输出。
var bytes = Encoding.UTF8.GetBytes("test");
SHA1 sha = new SHA1CryptoServiceProvider();
var result = sha.ComputeHash(bytes);
string hex = Encoding.UTF8.GetString(result, 0, result.Length);
byte[] packH = PackH(hex);
var base64String = Convert.ToBase64String(packH);
和方法:
public static byte[] PackH(string hex)
{
if ((hex.Length % 2) == 1) hex += '0';
var bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
而且因为我没有足够的声誉来回答我自己的问题,所以我会在这里写下答案:D
It seems that i needed to do some extra things:D
public static string Crypt(string data)
{
SHA1 sha = new SHA1Managed();
byte[] buffer = Encoding.UTF8.GetBytes(data);
byte[] computeHash = sha.ComputeHash(buffer);
string delimitedHexHash = BitConverter.ToString(computeHash);
string hexHash = delimitedHexHash.Replace("-", "");
byte[] packH = PackH(hexHash);
return Convert.ToBase64String(packH);
}
public static byte[] PackH(string hex)
{
if ((hex.Length%2) == 1) hex += '0';
var bytes = new byte[hex.Length/2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
甚至更容易
Console.WriteLine(Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes("root"))));