代码之家  ›  专栏  ›  技术社区  ›  tanascius

php中的hmac ou sha256与c_不同

  •  8
  • tanascius  · 技术社区  · 15 年前

    这是我的PHP代码:

    hash_hmac( "sha256", utf8_encode( $filename ), utf8_encode( $password ) );
    

    这是我的密码:

    var hmacsha256 = new HMACSHA256( Encoding.UTF8.GetBytes( password ) );
    hmacsha256.ComputeHash( Encoding.UTF8.GetBytes( filename ) );
    

    不幸的是,两个结果都不同。有人能给我个提示吗?

    1 回复  |  直到 15 年前
        1
  •  16
  •   Ólafur Waage    15 年前

    我的C不是最好的,但我让它工作了,您需要做的是将字节数组结果转换为十六进制。

    PHP

    $hash = hash_hmac( "sha256", utf8_encode("Filename"), utf8_encode("Password"));
    echo $hash;
    // 5fe2ae06ff9828b33fe304545289a3f590bfd948ca9ab731c980379992ef41f1
    

    C.*

    string password = "Password";
    string filename = "Filename";
    
    var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(password));
    hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(filename));
    
    foreach(byte test in hmacsha256.Hash)
    {
        Console.Write(test.ToString("X2"));
    }
    // 5FE2AE06FF9828B33FE304545289A3F590BFD948CA9AB731C980379992EF41F1