【问题标题】:PHP Encryption is not matching with the asp.net encryptionPHP 加密与 asp.net 加密不匹配
【发布时间】:2016-12-21 07:05:48
【问题描述】:

这是.net的代码

public string GetMD5Hash(string name) {
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] ba = md5.ComputeHash(Encoding.UTF8.GetBytes(name));
    StringBuilder hex = new StringBuilder(ba.Length * 2);

    foreach (byte b in ba)
        hex.AppendFormat("{0:x2}", b);
    return Convert.ToString(hex);
}

在 php 中我使用下面的代码

class foobar {

    public function str2hex($string) {
        $hex = "";
        for ($i = 0; $i < strlen($string); $i++)
            $hex .= (strlen(dechex(ord($string[$i]))) < 2) ? "0" . dechex(ord($string[$i])) : dechex(ord($string[$i]));       
        return $hex;
    }

    public function GetMD5($pStr) { 
        $data = mb_convert_encoding($pStr, 'UTF-16LE', 'UTF-8');
        $h = $this->str2hex(md5($data, true)); 
        return $h;
    } 
}

$foobar = new foobar;  
$nisha =$foobar->GetMD5('5698882');
echo "</br>";
echo $nisha;

但输出与 .net 加密输出均不匹配 不一样

【问题讨论】:

    标签: php asp.net cryptography md5 cryptographic-hash-function


    【解决方案1】:

    要在 php 中生成md5 字符串的哈希,您只需要使用md5() 函数,更多详细信息在http://php.net/manual/en/function.md5.php

    您可以使用这些代码获取 md5 哈希,这对于 .net 和 php 都是相同的

    PHP md5 哈希

    <?php
    echo md5('abcdefghijklmnopqrstuvwxyz');
    ?>
    

    结果 -> c3fcd3d76192e4007dfb496cca67e13b

    .NET md5 哈希

    public string CalculateMD5Hash(string input)
    
    {
    
        // step 1, calculate MD5 hash from input
    
        MD5 md5 = System.Security.Cryptography.MD5.Create();
    
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    
        byte[] hash = md5.ComputeHash(inputBytes);
    
    
        // step 2, convert byte array to hex string
    
        StringBuilder sb = new StringBuilder();
    
        for (int i = 0; i < hash.Length; i++)
    
        {
    
            sb.Append(hash[i].ToString(“x2”));
    
        }
    
        return sb.ToString();
    
    }
    

    结果 -> c3fcd3d76192e4007dfb496cca67e13b

    【讨论】:

    • 感谢您的回复 rick,但 .net 开发人员无法更改他们的代码。是否有可能我们可以将上述.net 代码复制到 php 中?
    • 你能用你的 .net 代码为字符串 abcdefghijklmnopqrstuvwxyz 给我 md5 哈希
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多