Java HMAC hmacEncode(String algorithm, String input, String privateKey)

Here you can find the source of hmacEncode(String algorithm, String input, String privateKey)

Description

hmac Encode

License

Apache License

Declaration

public static String hmacEncode(String algorithm, String input, String privateKey)
            throws IllegalArgumentException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String hmacEncode(String algorithm, String input, String privateKey)
            throws IllegalArgumentException {
        try {// www  .ja  va 2 s . com
            byte[] keyBytes = privateKey.getBytes();
            Key key = new SecretKeySpec(keyBytes, 0, keyBytes.length, algorithm);
            Mac mac = Mac.getInstance(algorithm);
            mac.init(key);
            return byteArrayToHex(mac.doFinal(input.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            throw new IllegalArgumentException("Unknown algorithm: " + algorithm);
        } catch (InvalidKeyException ex) {
            throw new IllegalArgumentException("Illegal key: " + privateKey);
        }
    }

    protected static String byteArrayToHex(byte[] bytes) {
        int hn, ln, cx;
        String hexDigitChars = "0123456789abcdef";
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (cx = 0; cx < bytes.length; cx++) {
            hn = ((int) (bytes[cx]) & 0x00ff) / 16;
            ln = ((int) (bytes[cx]) & 0x000f);
            buf.append(hexDigitChars.charAt(hn));
            buf.append(hexDigitChars.charAt(ln));
        }
        return buf.toString();
    }
}

Related

  1. hmac(String msg, String keyString)
  2. HMAC(String username, BigInteger nonce, String hashedPassword)
  3. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  4. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  5. hmacDigest(String message, String secretKey, String algorithm)
  6. hmacHex(String keyString, String message, String hmac)
  7. hmacSha(byte[] keyBytes, byte[] text)
  8. hmacSha(String crypto, String key, String value)
  9. hmacSha1(byte[] data, byte[] key)