Generating a MAC that uses MD5 in Java

The following example generates a random key of 128 bits (16 bytes) necessary for HmacMD5 and computes a hash using this key. The key would have to be shared between sender and receiver.

import javax.crypto.spec.*;
import javax.crypto.Mac;
import javax.crypto.*;
import sun.misc.*;
public class Main
   public static void main(String []args) throws Exception {
      String message = "the sun is green and the grass shines";
      byte[] b = generateMAC(message);
      System.out.println("HMAC-MD5 for message '" + message + "':");
      System.out.println("t" + new BASE64Encoder().encode(generateMAC(message)));
   public static byte[] generateMAC(String message) throws Exception {
      // generate key
      SecureRandom sr = new SecureRandom();
      byte[] b = new byte[20];
      SecretKey key = new SecretKeySpec(b, "HmacMD5");
      // generate message digest based on key
      Mac mac = Mac.getInstance("HmacMD5");
      return mac.doFinal(message.getBytes());


HMAC-MD5 for message 'the sun is green and the grass shines':