import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* @author Administrator HMAC util
*/
public class HmacUtil {
private static final String ALGORITHM_HMACMD5="HmacMD5";
/**
* nothing about algorithm :HmacMD5,AES(128),DESede(168),HmacSHA1,HmacSHA256
* SecureRandom : use default config random user nextint
* encode : (byte to base64bytes)to String
* @return
*/
public static String init() {
String key = "";
try {
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM_HMACMD5);
SecretKey secretKey=generator.generateKey();
byte[]bytes=encode(secretKey.getEncoded());
key=new String(bytes);
System.out.println(key);
} catch (Exception e) {
e.printStackTrace();
}
return key;
}
/**
* USE HmacMD5
* @param plainText
* @param key
* @return
*/
public static String HmacEncrypt(String plainText, String key) {
Mac mac = null;
try {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM_HMACMD5);
mac = Mac.getInstance(ALGORITHM_HMACMD5);
mac.init(secretKey);
} catch (Exception e) {
e.printStackTrace();
}
byte[] dataBytes =mac.doFinal(plainText.getBytes());
return new String(encode(dataBytes));
}
/**
* base64 encode
* @param plainBytes
* @return byte[]
*/
public static byte[] encode(byte[]plainBytes){
Base64 base64=new Base64();
return base64.encode(plainBytes);
}
/**
* base64 decode
* @param cipherText
* @return byte[]
*/
public static byte[] decode(byte[]cipherText){
Base64 base64=new Base64();
return base64.decode(cipherText);
}
public static void main(String[] args) {
String str="我是张三";
System.out.println("明文信息:"+str);
String key = init();
System.out.println("生成的秘钥为__:"+key);
String hmacKey=HmacEncrypt(str, key);
System.out.println("用自己的秘钥做信息摘要__:"+hmacKey);
}
//===================运行结果
明文信息:我是张三
MF8mW4etH60UzW8xELiCmMGN3gdgO+fFyW0Pivg8pD+pd8cB8Y2BYGSrCfOQAXvHbDMFkK1xfytkYERMq3bQYA==
生成的秘钥为__:MF8mW4etH60UzW8xELiCmMGN3gdgO+fFyW0Pivg8pD+pd8cB8Y2BYGSrCfOQAXvHbDMFkK1xfytkYERMq3bQYA==
用自己的秘钥做信息摘要__:REsuoeYttq8fSVfTe+iD4A==