简体   繁体   中英

Java equivalent for PHP's pack function

I have a sample application which generates a SHA1 hash in PHP as follows.

base64_encode(pack('H*', sha1($pass)));

I tried to achieve the same in Java, but so far, the output is different. The approach I used is as follows (Base64 and Hex classes come from commons-codec library).

    byte[] rawSHA = null;
    byte[] base64HexSHA = null;
    String hex = null;
    MessageDigest md= null;

    // Get Message Digest Instance.
    try {
        md = MessageDigest.getInstance(SHA1_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("Unable to load SHA-1 Message Digest : " + e.getMessage(), e);
        throw new IllegalStateException("SHA-1 Message Digest Instance Not Found");
    }

    // Build SHA1 Hash
    rawSHA = md.digest(rawText.getBytes("UTF-8"));

    // Convert to HEX
    hex = new String(Hex.encodeHex(rawSHA));

    // Encode to Base 64
    base64HexSHA = Base64.encodeBase64(hex.getBytes("UTF-8"));

    // Return String
    return new String(base64HexSHA);

My question is, would the approach I have taken yield the same output as PHP's pack() function? My guess is that PHP pack() function returns the raw bytes where as the Hex.encodeHex returns hex string form (ref : http://www.w3schools.com/php/func_misc_pack.asp ).

How can I achieve the same output as PHP's pack() function in Java (or the full output of the above PHP code) ?

转换为HEX不是必需的,只需使用:

base64HexSHA = Base64.encodeBase64(rawSHA);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM