java hmac/sha512 generation

前端 未结 3 847
一个人的身影
一个人的身影 2020-12-14 13:54

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



        
相关标签:
3条回答
  • 2020-12-14 14:08

    try that :

    private String generateHMAC( String datas )
    {
        MessageDigest md = MessageDigest.getInstance("SHA-512");
    
        md.update(datas.getBytes("UTF-8")); // Change this to "UTF-16" if needed
        byte[] digest = md.digest();
    
        StringBuffer hexString = new StringBuffer();
        for (int i=0;i<digest.length;i++) {
            hexString.append(Integer.toHexString(0xFF & digest[i]));
        }
    
        return  hexString.toString();
    }
    
    0 讨论(0)
  • 2020-12-14 14:10

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

    Use

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

    In your Java Code.

    Where DatatypeConverter.parseHexBinary() is from the JAXB API.

    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.

    0 讨论(0)
  • 2020-12-14 14:23

    I use this for SHA 512 in Java. It might help:

    public static String sha512 ( String str )
        {
            try
            {
                return sha512 ( str.getBytes ( "UTF-8" ) );
            }
            catch ( UnsupportedEncodingException e )
            {
                e.printStackTrace ( );
                return "";
            }
        }
    
    public static String sha512 ( byte[] array )
    {
        try
        {
            MessageDigest m = MessageDigest.getInstance ( "SHA-512" );
            m.update ( array );
            String hash = new BigInteger ( 1, m.digest ( ) ).toString ( 16 );
            while ( hash.length ( ) < 32 )
            {
                hash = "0" + hash;
            }
            return hash;
        }
        catch ( NoSuchAlgorithmException e )
        {
            e.printStackTrace ( );
            return "";
        }
    }
    

    I also remember that there is detailed answer about MD-5 in a post in stackoverflow (just the algorythm is different)

    0 讨论(0)
提交回复
热议问题