wisdomisite-java/src/main/java/com/zhgd/xmgl/util/EncriptionHelper.java
2024-04-14 21:05:01 +08:00

105 lines
3.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.zhgd.xmgl.util;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by jim.z.hu on 2018/7/11.
*/
@Slf4j
public class EncriptionHelper {
/**
* 利用java原生的摘要实现SHA256加密
*
* @param str 加密后的报文
* @return
*/
public static String getSHA256StrJava(String str) {
MessageDigest messageDigest;
String encodeStr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes("UTF-8"));
encodeStr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
log.error("error", e);
} catch (UnsupportedEncodingException e) {
log.error("error", e);
}
return encodeStr;
}
public static String HMACSHA256(String data, String key) {
String outPut = "";
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(data.getBytes());
outPut = byteArrayToHexString(bytes);
} catch (NoSuchAlgorithmException e) {
log.error("error", e);
} catch (InvalidKeyException e) {
log.error("error", e);
}
return outPut.toUpperCase();
}
public static String byteArrayToHexString(byte[] b) {
StringBuilder sb = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1) {
sb.append('0');
}
sb.append(stmp);
}
return sb.toString().toLowerCase();
}
/**
* sha256_HMAC加密
*
* @param message 消息
* @param secret 秘钥
* @return 加密后字符串
*/
public static String sha256_HMAC(String message, String secret) {
String hash = "";
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = byteArrayToHexString(bytes);
} catch (Exception e) {
log.info("Error HmacSHA256 ===========" + e.getMessage());
}
return hash;
}
private static String byte2Hex(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i = 0; i < bytes.length; i++) {
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length() == 1) {
//1得到一位的进行补0操作
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
}