java hmac / sha512代 [英] java hmac/sha512 generation

查看:141
本文介绍了java hmac / sha512代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个生成 HMAC 的PHP代码(而不是简单的消息摘要):

I have this php code which generate a HMAC (and not a simple message digest):

<?php 
$key = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
$binkey = pack("H*", $key); 
echo strtoupper(hash_hmac('sha512', "ABC", $binkey)); 
?>

使用 ABC 输入其输出为:

100A6A016A4B21AE120851D51C93B293D95B7D8A44B16ACBEFC2D1C9DF02B6F54FA3C2D6802E52FED5DF8652DDD244788A204682D2D1CE861FDA4E67F2792643

我需要在java中克隆它。

And I need to clone it in java.

所以这是我当前的java克隆:

So here is my current java clone :

private String generateHMAC( String datas )
    {

        //                final Charset asciiCs = Charset.forName( "utf-8" );
        Mac mac;
        String result = "";
        try
        {
            byte[] bytesKey = PayboxConstants.KEY.getBytes( );
            final SecretKeySpec secretKey = new SecretKeySpec( bytesKey, "HmacSHA512" );
            mac = Mac.getInstance( "HmacSHA512" );
            mac.init( secretKey );
            final byte[] macData = mac.doFinal( datas.getBytes( ) );
            byte[] hex = new Hex( ).encode( macData );
            result = new String( hex, "ISO-8859-1" );
        }
        catch ( final NoSuchAlgorithmException e )
        {
            AppLogService.error( e );
        }
        catch ( final InvalidKeyException e )
        {
            AppLogService.error( e );
        }
        catch ( UnsupportedEncodingException e )
        {
            AppLogService.error( e );
        }

        return result.toUpperCase( );

    }

但由于相同的输入,它不能完成工作( ABC)其输出为:

But it does not makes the job because for same input (ABC) its ouput is:

AA6492987D7A7AC81109E877315414806F1973CC47B897ECE713171A25A11B279329B1BFF39EA72A5EFB7EDCD71D1F34D5AAC49999A780BD13F019ED99685B80

我尝试了很多其他java代码,但它们都不是php版本的精确克隆。

I've tries a lot of other java code but none of them was an exact clone of php version.

我做了什么做错了吗?

推荐答案

你只是忘了模仿 pack()' Java代码中的行为(无论您需要什么)。

You simply forgot to mimic pack()'s behavior in your Java code (whatever you need that for).

使用

final SecretKeySpec secretKey = new SecretKeySpec( DatatypeConverter.parseHexBinary(PayboxConstants.KEY), "HmacSHA512" );

在您的Java代码中。

In your Java Code.

DatatypeConverter.parseHexBinary()来自 JAXB API

或者,如果你不这样做想要包含JAXB只是为了将HEX字符串转换为字节,您可能希望使用已发布的代码这里

Alternatively, if you don't want to include JAXB just for the purpose of converting HEX strings to bytes, you might want to use the code posted here.

这篇关于java hmac / sha512代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆