package cn.orz.utlis;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HmacSHA1 {
/**
* 【调用加密算法】
* @param data
* @param key
* @return 返回加密后结果
*/
public static String HmacSHA1Encode(String data, String key) {
byte[] dataBytes = data.getBytes();
byte[] keyBytes = key.getBytes();
String result = hamcsha1(dataBytes, keyBytes);
return result;
}
public static String byte2hex(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
/**
* 【HmacSHA1加密算法实现】
* @param data
* @param key
* @return 返回加密后的密文字符串
*/
public static String hamcsha1(byte[] data, byte[] key) {
try {
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
return byte2hex(mac.doFinal(data));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
}
Java基于HmacSHA1实现不可逆加密
最新推荐文章于 2021-12-10 14:43:49 发布