在很多的API调用的时候,会用到一些加密签名。比如:php中的 hash_hmac(data, key),那如何用JAVA实现这个方法呢?
PHP代码:
/*
* $data, 待签名内容字符串
* $key, 签名密钥
* $sign, 签名结果
*/
$sign = hash_hmac("sha1", $data, $key);
JAVA的实现方式:
/**
* 使用HMAC-SHA1签名方法对data进行签名
*/
public String genHMAC(String data, String key){
String result=null;
try{
String algorithm = "HmacSHA1";
//根据给定的字节数组构造一个密钥,并指定算法名称
SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), algorithm);
//生成一个指定Mac算法的Mac对象
Mac mac = Mac.getInstance(algorithm);
//永给定的密钥初始化mac
mac.init(signinKey);
//完成Mac操作
byte[] rawHmac = mac.doFinal(data.getBytes());
//结果处理成String类型
result = this.byte2hex(rawHmac);
}catch (NoSuchAlgorithmException e){
//System.err.println(e.getMessage());
}catch (InvalidKeyException e){
//System.err.println(e.getMessage());
}
if(null != result){
return new String(result);
}else{
return null;
}
}
private String byte2hex(final byte[] b){
String hs = "";
String stmp = "";
for(int n=0;n<b.length;n++){
stmp = (java.lang.Integer.toHexString(b[n] & 0xFF));
if(stmp.length() == 1){
hs = hs + "0" + stmp;
}else{
hs = hs + stmp;
}
}
return hs;
}
调用 genHMAC方法就能得到和PHP中hash_hmac方法一样的结果了。