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

匆匆过客 提交于 2019-11-28 03:39:20

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).

Recommend Apache Common Codec Library, quite simple and easy to use. HmacUtils.hmacSha1Hex(key, string_to_sign);

Any $ symbol in double quotes ("") is regarded as a a variable in PHP. You can avoid the error by using either single quotes as pointed out by the previous commenter or you can escape the dollar sign as below

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

Notice $ is now \$

In Java, and using maven:

Add the below dependency into the pom.xml:

 <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.4</version>
    </dependency>

and then try to sign it using this

HmacUtils.hmacSha1Hex(key, string_to_sign);

The other answers pointing out HmacUtils from Apache commons have been deprecated by now. Apache commons now recommends using:

new HmacUtils(HmacAlgorithms.HMAC_SHA_1, key).hmacHex(string_to_sign)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!