// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;

public class HMACFun {
    public static String encodeText(byte[] key, String sSrc, String encoding) throws Exception {
       HMACMD5 hmacMD5 = new HMACMD5(key);
       byte[] textBytes = sSrc.getBytes(encoding);
       byte[] encodedTextBytes = hmacMD5.ComputeHash(textBytes);
       String sEncodedText = B64.b64encode(encodedTextBytes);
       return sEncodedText;
    }
    public static void main(String[] args) throws Exception {
        System.out.println(encodeText(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, "This is a test!","UTF-8"));
    }
}
class HMACMD5 {
    private final String HMAC_MD5_NAME = "HmacMD5";
    private SecretKeySpec sk;
    private Mac mac;
    public HMACMD5(byte[] key) throws GeneralSecurityException {
        init(key);
    }
    public HMACMD5(String key, String encoding) throws GeneralSecurityException, UnsupportedEncodingException {
        init(key.getBytes(encoding));
    }
    private void init(byte[] key) throws GeneralSecurityException {
        sk = new SecretKeySpec(key, HMAC_MD5_NAME);
        mac = Mac.getInstance(HMAC_MD5_NAME);
        mac.init(sk);
    }
    public byte[] ComputeHash(byte[] data) {
        return mac.doFinal(data);
    }
    public byte[] ComputeHash(String data, String encoding) throws UnsupportedEncodingException {
        return ComputeHash(data.getBytes(encoding));
    }
}
class B64 {
    public static String b64encode(byte[] b) throws MessagingException, IOException  {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream b64os = MimeUtility.encode(baos, "base64");
        b64os.write(b);
        b64os.close();
        return new String(baos.toByteArray());
     }
     public static byte[] b64decode(String s) throws MessagingException, IOException  {
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());
        InputStream b64is = MimeUtility.decode(bais, "Base64");
        byte[] tmp = new byte[s.length()];
        int n = b64is.read(tmp);
        byte[] res = new byte[n];
        System.arraycopy(tmp, 0, res, 0, n);
        return res;
     }
}
