php sha256 获取 Java sha256 数据

php·编程语言 · 2022-01-28
   public String toBase58() {
       byte[] data = new byte[25];
       data[0] = COIN_VERSION;
       System.arraycopy(toArray(), 0, data, 1, 20);
       byte[] checksum = Digest.sha256(Digest.sha256(data, 0, 21));
       System.arraycopy(checksum, 0, data, 21, 4);
       return Base58.encode(data);
   }

上面可以看到 java toBase58 方法是凉了两次 sha256

对应PHP连续两次sha256 如果想和java 实现的一样就需要 hex2bin(hash('sha256', hex2bin(hash('sha256', hex2bin($hexstr))) 每次sha256前 都需要先 二进制 hex2bin
查了很多问题, 给出的都不理想, java sha256 对比 php sha256 存在问题. 下面还有php转 base58 的方法

php base58 加密方法

 $string = hex2bin($$hexstr).substr(hex2bin(hash('sha256', hex2bin(hash('sha256', hex2bin($hexstr))))), 0, 4)
 base58_encode(string);
/**
 * base58 encode
 * @param $string
 * @return bool|string
 */
public static function base58_encode($string)
{
    $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
    $base = strlen($alphabet);
    if (is_string($string) === false) {
        return false;
    }
    if (strlen($string) === 0) {
        return '';
    }
    $bytes = array_values(unpack('C*', $string));
    $decimal = $bytes[0];
    for ($i = 1, $l = count($bytes); $i < $l; $i++) {
        $decimal = bcmul($decimal, 256);
        $decimal = bcadd($decimal, $bytes[$i]);
    }
    $output = '';
    while ($decimal >= $base) {
        $div = bcdiv($decimal, $base, 0);
        $mod = bcmod($decimal, $base);
        $output .= $alphabet[$mod];
        $decimal = $div;
    }
    if ($decimal > 0) {
        $output .= $alphabet[$decimal];
    }
    $output = strrev($output);
    foreach ($bytes as $byte) {
        if ($byte === 0) {
            $output = $alphabet[0] . $output;
            continue;
        }
        break;
    }
    return (string) $output;
}
php
Theme Jasmine by Kent Liao