io.afu.utils.encryption.SHAEncryption Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils Show documentation
Show all versions of utils Show documentation
RffanLAB Utils For Many Way use
package io.afu.utils.encryption;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* sha 加密
*/
public class SHAEncryption {
public static final String HMAC_ALGORITHM_DEFAULT = "HmacSHA1";
public static final String HMAC_ALGORITHM_SHA256 = "HmacSHA256";
public static String sha256(String str){
MessageDigest messageDigest;
String encodeStr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes());
encodeStr = EncryptCommon.byteArrayToHex(messageDigest.digest());
}catch (Exception e){
e.printStackTrace();
}
return encodeStr;
}
public static String getHmacSha1(String data,String key){
return HmacSHA1(data,key);
}
public static String HmacSHA1(String data,String key){
return HmacSha(data,key,HMAC_ALGORITHM_DEFAULT);
}
public static String HmacSHA256(String data,String key) {
return HmacSha(data,key,HMAC_ALGORITHM_SHA256);
}
public static String HmacSha(String data,String key,String enType) {
byte[] dataByte= data.getBytes(StandardCharsets.UTF_8);
byte[] keyByte = key.getBytes(StandardCharsets.UTF_8);
try {
SecretKeySpec signingKey = new SecretKeySpec(keyByte, enType);
Mac mac = Mac.getInstance(enType);
mac.init(signingKey);
return EncryptCommon.byteArrayToHex(mac.doFinal(dataByte));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
/**
* 验证hmacSha1的加密是否正确
* @param targetStr 目标加密串
* @param orginStr 原始加密串
* @param key 加密key
* @return Boolean 比对结果
*/
public static Boolean verifyHmacSha1(String targetStr,String orginStr,String key){
String encryptedStr = getHmacSha1(orginStr,key);
if (encryptedStr.equals(targetStr)){
return true;
}
return false;
}
public static void main(String[] args){
System.out.println("args = [" + sha256("qunimad") + "]");
System.out.println("str = [qunimad], key = [233], encrypt = [" + getHmacSha1("qunimad","233") + "]");
}
}