【问题标题】:Android: Hmac SHA512 in javaAndroid:Java中的Hmac SHA512
【发布时间】:2016-03-30 16:11:57
【问题描述】:

我在 php 中有以下代码:

$binKey = pack("H*", $keyTest);
$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));

我如何在 android (java) 中实现同样的功能。

我尝试了一些可用于 hmac sha512 的方法,但是 php sn-p 的结果与我的不同。

提前致谢

【问题讨论】:

    标签: android encryption hmac


    【解决方案1】:

    你可以用这个来检查它。在其中我使用 HmacSHA512 算法对其进行加密,然后我使用 base64 对其进行编码。

    try {
                String secret = "secret";
                String message = "Message";
    
                Mac sha_HMAC = Mac.getInstance("HmacSHA512");
    
                SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA512");
                sha_HMAC.init(secret_key);
    
                String hash = Base64.encodeToString(sha_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
                System.out.println(hash);
                Log.e("string is ",hash);
    
            }
            catch (Exception e){
                System.out.println("Error");
            }
    

    【讨论】:

    • 感谢您的回答。但是与我在问题中提到的 php 相比,这段代码给出了相同消息的不同结果。我猜这行有问题: $binKey = pack("H*", $keyTest);
    • 可能是因为加密算法有HMACsha256和HMACsha512
    【解决方案2】:

    您可以在此处查看相同问题的答案:java hmac/sha512 generation

    我已经搜索了很长时间才能看到正确的答案。我给你代码,也许它会帮助别人。

    private String generateHMAC( String datas )
    {
    
        //                final Charset asciiCs = Charset.forName( "utf-8" );
        Mac mac;
        String result = "";
        try
        {
          final SecretKeySpec secretKey = new SecretKeySpec( DatatypeConverter.parseHexBinary(PayboxConstants.KEY), "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( );
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多