Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

hash - HMAC-SHA1: How to do it properly in Java?

I'm hashing some values using HMAC-SHA1, using the following code in Java:

public static String hmacSha1(String value, String key) {
    try {
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();           
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Hex() belongs to org.apache.commons.codec

In PHP there's a similar function hash_hmac(algorithm, data, key) that I use to compare the values returned by my Java implementation.

So the first try is:

hash_hmac("sha1", "helloworld", "mykey") // PHP

that returns: 74ae5a4a3d9996d5918defc2c3d475471bbf59ac

My Java function returns 74ae5a4a3d9996d5918defc2c3d475471bbf59ac as well.

Ok, it seems working. Then I try to use a more complex key:

hash_hmac("sha1", "helloworld", "PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo") // PHP

that returns: e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a

While this time my Java impl returns: c19fccf57c613f1868dd22d586f9571cf6412cd0

The hash returned by my PHP code is not equal to the value returned by my Java function, and I can't find out why.

Any tips?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On your PHP side, use single-quotes around the key so that the $ character is not treated as a variable reference. i.e.,

hash_hmac("sha1", "helloworld", 'PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo')

Otherwise, the key you really get is PRIE7-Yf17kEnUEpi5hvW/#AFo (assuming the variable $oG2uS is not defined).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...