开发者

Java equivalent for PHP's pack function

开发者 https://www.devze.com 2023-03-14 19:09 出处:网络
I have a sample application which generates a SHA1 hash in PHP as follows. base64_encode(pack(\'H*\', sha1($pass)));

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 Instan开发者_C百科ce 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) ?


Convertion to HEX is not required, just use this:

base64HexSHA = Base64.encodeBase64(rawSHA);
0

精彩评论

暂无评论...
验证码 换一张
取 消