Java HMAC hmac(String msg, String keyString)

Here you can find the source of hmac(String msg, String keyString)

Description

hmac

License

Open Source License

Declaration

public static String hmac(String msg, String keyString) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

public class Main {

    public static String hmac(String msg, String keyString) {
        String digest = null;/*from  w w w .ja  va 2s .c  o  m*/
        try {
            SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(key);

            byte[] bytes = mac.doFinal(msg.getBytes("UTF-8"));

            StringBuffer hash = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(0xFF & bytes[i]);
                if (hex.length() == 1) {
                    hash.append('0');
                }
                hash.append(hex);
            }
            digest = hash.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return digest;
    }
}

Related

  1. hmac(byte key[], byte text[])
  2. hmac(String hash, String data, String key)
  3. HMAC(String username, BigInteger nonce, String hashedPassword)
  4. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  5. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  6. hmacDigest(String message, String secretKey, String algorithm)