JavaによってHMACが実現され、文字列ハッシュはアルファベットから成るすべての暗号文列になる。
2713 ワード
以下のJavaコードは、任意の文字列をHMACハッシュに通して、大文字のAからPまでの暗号文字列として出力することができる。
public class HMAC {
private final static String KEY_MAC = "HMACMD5";
/**
*
*/
private final static String[] hexDigits = { "A", "B", "C", "D", "E", "F","G", "H", "I", "J", "K", "L",
"M", "N", "O", "P" };
/**
* BASE64
* @param key
* @return
* @throws Exception
*/
public static String encryptBase64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
/**
* BASE64
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBase64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* HMAC
* @param data
* @param key
* @return
*/
public static byte[] encryptHMAC(byte[] data, String key) {
SecretKey secretKey;
byte[] bytes = null;
try {
secretKey = new SecretKeySpec(decryptBase64(key), KEY_MAC);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
bytes = mac.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
/**
* HMAC
* @param data
* @param key
* @return
*/
public static String encryptHMAC(String data, String key) throws UnsupportedEncodingException {
if (data==null||data.equals("")) {
return null;
}
byte[] bytes = encryptHMAC(data.getBytes(), key);
//return new String(bytes,"UTF-8");
return byteArrayToHexString(bytes);
}
private static String byteToHexString(byte b) {
int ret = b;
//System.out.println("ret = " + ret);
if (ret < 0) {
ret += 256;
}
int m = ret / 16;
int n = ret % 16;
return hexDigits[m] + hexDigits[n];
}
private static String byteArrayToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
sb.append(byteToHexString(bytes[i]));
}
return sb.toString();
}
/**
*
* @param args
*/
public static void main(String[] args) throws Exception {
String word = "This is a test";
System.out.println(encryptHMAC(word, "123"));
}
}