java HmacSHA256算法加密
MikeTeas 人气:0HmacSHA256算法进行加密
1. 使用HmacSHA256进行数据加密(需要使用秘钥secret)
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { String secret="2131231@#42"; String message="我加密一下"; Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes("utf-8"), "HmacSHA256"); sha256_HMAC.init(secretKey); byte[] hash = sha256_HMAC.doFinal(message.getBytes("utf-8")); String encodeStr = Base64.encodeBase64String(hash); String encodeStr16=byte2Hex(hash); }
2. 加密后的字节也可以进行转换成16位进制的字符串
/** * 将byte转为16进制 * * @param bytes * @return */ 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(); }
注释:MD5算法进行加密的属于比较弱的加密算法,所以要想强一点加密的话可以使用sha256加密算法
HmacSHA256 签名及验签
一个项目需要用到HmacSHA256 对数据进行签名 于是写了个工具类方便以后及大家直接引用。
验签参数
// 遍历排序后的字典,将所有参数按"keyvalue"格式拼接在一起 StringBuilder basestring = new StringBuilder(); for (Map.Entry<String, String> param : entrys) { if(!StringUtils.isBlank(param.getValue())) { basestring.append(param.getKey()); basestring.append(param.getValue()); } } basestring.append(secret); logger.info("basestring is = {}", basestring); // 使用SHA256对待签名串求签 boolean returnFlag = SignatureUtils.valid(basestring.toString(), secret, userSign); if (! returnFlag ) { logger.info("user sign error==============sign={}, string={}", clientSign, basestring); }
工具代码
// 项目需要对表的数据进行签名 package com.api.common.utils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; public abstract class SignatureUtils { private static Logger logger = LogManager.getLogger(SignatureUtils.class); private static final String ALGORITHM = "HmacSHA256"; public static boolean valid(String message, String secret, String signature) { return signature != null && signature.equals(sign(message, secret)); } public static String sign(String message, String secret) { try { Mac hmac = Mac.getInstance(ALGORITHM); SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), ALGORITHM); hmac.init(secret_key); byte[] bytes = hmac.doFinal(message.getBytes()); logger.info("service sign is "+byteArrayToHexString(bytes)); return byteArrayToHexString(bytes); } catch (Exception ex) { logger.error("签名错误:", ex); } return null; } private static String byteArrayToHexString(byte[] bytes) { StringBuilder hs = new StringBuilder(); String tempStr; for (int index = 0; bytes != null && index < bytes.length; index++) { tempStr = Integer.toHexString(bytes[index] & 0XFF); if (tempStr.length() == 1) hs.append('0'); hs.append(tempStr); } return hs.toString().toLowerCase(); } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容