【问题标题】:Convert a C# line to PHP将 C# 行转换为 PHP
【发布时间】:2011-10-18 15:57:40
【问题描述】:

我在 C# 中有以下函数:

    static MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

    public string Guid GetMD5(string str)
    {
        lock (md5Provider)
        {
            return (new Guid(md5Provider.ComputeHash(Encoding.Unicode.GetBytes(str)))).ToString();
        }
    }

我需要相同的代码,但使用 PHP。 请注意,md5() 函数具有不同的行为。

谢谢

【问题讨论】:

  • md5 函数在任何地方都有相同的行为。如果你得到不同的输出,那么你就有不同的输入。例如你在一个地方做 utf-8,但在另一个地方做 iso-8859 - md5 处理原始字节,而不是字符。
  • Encoding.Unicode.GetBytes(str) 使用 UTF-16LE 编码返回代表 str 的字节。
  • 感谢您的回复,可能是编码问题。我仍然无法使用 PHP 重现此功能。

标签: c# php md5


【解决方案1】:

我怀疑您遇到的问题是 C# 代码返回用破折号分隔的哈希,因为您正在将哈希转换为 GUID,而 GUID.ToString() 返回 M$ 称为“注册表格式”的字符串,它是 GUID 的标准 8-4-4-4-12 字符串表示法。

如果是这种情况,您可以使用此函数获得相同的结果:

function md5_guid ($data, isFile = FALSE) {
  if ($isFile) {
    if (is_file($data) && is_readable($data)) {
      $hash = str_split(md5_file($data), 4);
    } else {
      return FALSE;
    }
  } else {
    $hash = str_split(md5($data), 4);
  }
  return "$hash[0]$hash[1]-$hash[2]-$hash[3]-$hash[4]-$hash[5]$hash[6]$hash[7]";
}


// Returns the MD5 hash of the string 'this is some data' in the format of a GUID
echo md5_guid('this is some data');

// Returns the MD5 hash of the file at 'somefile.txt' in the format of a GUID
echo md5_guid('somefile.txt', TRUE);

【讨论】:

  • 这是正确的。 Guid 类的 toString() 方法的默认值是添加破折号。您可以通过将格式参数传递给 toString 方法在您的 C# 代码中更改此行为,请参阅docs
  • @Jan-Henk ...或者您根本就不用理会 GUID 位,直接从MD5CryptoServiceProvider...
  • 哈哈确实,我在想什么:)
猜你喜欢
  • 2020-08-04
  • 1970-01-01
  • 2016-04-18
  • 2015-01-17
  • 2016-07-02
  • 2011-11-01
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多