我有一个 C# 代码,它使用 MD5 或 SHA1 算法获取提供的字符串的哈希值。这本身不是问题,但这里仅供参考:
public static string GetMD5(Encoding encoding, params string[] components)
{
return GetHashedString(HashingMethod.MD5, encoding, components);
}
public static string GetSHA1(Encoding encoding, params string[] components)
{
return GetHashedString(HashingMethod.SHA1, encoding, components);
}
private static string GetHashedString(HashingMethod method, Encoding encoding, params string[] components)
{
HashAlgorithm algorithm = null;
switch (method)
{
case HashingMethod.MD5:
algorithm = new MD5CryptoServiceProvider();
break;
case HashingMethod.SHA1:
algorithm = new SHA1CryptoServiceProvider();
break;
}
StringBuilder data = new StringBuilder();
foreach (string param in components)
data.Append(param);
byte[] bytes = encoding.GetBytes(data.ToString());
bytes = algorithm.ComputeHash(bytes);
StringBuilder result = new StringBuilder();
foreach (byte b in bytes)
result.AppendFormat("{0:x2}", b);
return result.ToString();
}
private enum HashingMethod { MD5, SHA1 }
Now, the real problem is which encoding am I supposed to pass to GetMD5 and GetSHA1 methods in order for them to return the same results as PHP's md5() and sha1()? I can't alter the PHP code and I don't even have an access to it, I'm just getting a hash signature and I know it's created with PHP. What I can alter is my C# code, if necessary.
I've looked around the internet and the answers I found vary. According to them for SHA1 I should use ASCII encoding and for MD5 I have no idea (my own tests seem to point to UTF8 though).
我必须承认我对 PHP 几乎一无所知。md5() 和 sha1() 中使用的编码是否总是相同的(如果是,是哪些)?或者也许有可能以某种方式改变它们——不是通过使用某种包装方法预先转换字符串,而是通过改变 md5() 和 sha1() 中使用的编码?换句话说,我可以期望每种方法都有特定的编码还是会有所不同?
编辑
让我们减少一些可能性,因为我的问题可能过于笼统,假设 PHP 哈希代码如下所示:
$hash = sha1($str)
普通字符串在哪里$str
,即没有应用 Base64,没有使用其他哈希算法等。我必须将什么编码传递给我的 GetSHA1 方法才能获得与上述 PHP 行产生的相同输出?甚至可以确定吗?PHP 的 md5() 和我的 GetMD5 的条件和问题相同。