<?php
$pwd = "test";
$crypted = base64_encode(pack("H*", sha1(utf8_encode($pwd))));
echo("$crypted");
?>
因此,我得到了上面這個PHP代碼,我試圖將它轉換爲C#代碼。我試過以下,但它沒有相同的輸出。將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;
}
甚至easyier
Console.WriteLine(Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes("root"))));
爲什麼不開始比較逐步比較值,並確切地看到什麼失敗? – Tchoupi 2013-03-10 17:32:17
看起來你沒有實現一個等效的包函數,也許這將有助於:http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/ca080d6e-0707-4030-a3c7-462d5903b5f8 – Mark 2013-03-10 17:34:37