1. 程式人生 > >JAVA-自帶簽名加密類

JAVA-自帶簽名加密類

 

 

hmac

HMAC是金鑰相關的雜湊運算訊息認證碼,HMAC運算利用雜湊演算法,以一個金鑰和一個訊息為輸入,生成一個訊息摘要作為輸出

 

測試JAVA8中不支援HmacSHA384.HmacSHA512

使用apache  -  package org.apache.commons.codec.digest 包中 DigestUtils 也提供了豐富的MD5,SHA1等加密方法


public class signatureTest {


    String type = "HmacMD5,HmacSHA1,HmacSHA224,HmacSHA256"; //HmacSHA384.HmacSHA512

    @Test
    public void testSign1() throws NoSuchAlgorithmException {

        String secret = "ndE2jdZNFixH9G6Aidsfyf7lYT3PxW";
        String message = "channel";
        String hash = null;
        try {
            String[] aa = type.split(",");
            for(String type : aa){

                System.out.println("type:" + type);
                Mac sha256_HMAC = Mac.getInstance(type);
                SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), type);
                sha256_HMAC.init(secret_key);
                byte[] bytes = sha256_HMAC.doFinal(message.getBytes());

                System.out.println(byteArrayToHex1(bytes));
                System.out.println(byteArrayToHex2(bytes));
                System.out.println("-----------------------------------------------------");
            }
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========" + e.getMessage());
        }

    }



    private static String byteArrayToHex1(byte[] bytes) {
        return new HexBinaryAdapter().marshal(bytes);
    }


    private static String byteArrayToHex2(byte[] bytes) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; bytes!=null && n < bytes.length; n++) {
            stmp = Integer.toHexString(bytes[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }


}