wisdomisite-java/src/main/java/com/zhgd/xmgl/util/EncriptionHelper.java

105 lines
3.2 KiB
Java
Raw Normal View History

2023-02-16 15:28:15 +08:00
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) {
2024-04-14 21:05:01 +08:00
log.error("error", e);
2023-02-16 15:28:15 +08:00
} catch (UnsupportedEncodingException e) {
2024-04-14 21:05:01 +08:00
log.error("error", e);
2023-02-16 15:28:15 +08:00
}
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) {
2024-04-14 21:05:01 +08:00
log.error("error", e);
2023-02-16 15:28:15 +08:00
} catch (InvalidKeyException e) {
2024-04-14 21:05:01 +08:00
log.error("error", e);
2023-02-16 15:28:15 +08:00
}
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();
}
}