java實現(xiàn)HmacSHA256算法進行加密方式
HmacSHA256算法進行加密
1. 使用HmacSHA256進行數(shù)據(jù)加密(需要使用秘鑰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. 加密后的字節(jié)也可以進行轉(zhuǎn)換成16位進制的字符串
/** ? ? ?* 將byte轉(zhuǎn)為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 對數(shù)據(jù)進行簽名 于是寫了個工具類方便以后及大家直接引用。
驗簽參數(shù)
? ? // 遍歷排序后的字典,將所有參數(shù)按"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); ? ? }
工具代碼
// ?項目需要對表的數(shù)據(jù)進行簽名 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(); ? ? } }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot實現(xiàn)權(quán)限驗證的示例步驟
權(quán)限驗證是一種用于控制對系統(tǒng)資源和操作的訪問的機制。它允許開發(fā)人員定義誰可以執(zhí)行特定操作或訪問特定資源,并確保只有經(jīng)過授權(quán)的用戶才能執(zhí)行這些操作,這篇文章主要介紹了SpringBoot實現(xiàn)權(quán)限驗證,需要的朋友可以參考下2023-08-08Java并發(fā)編程之ConcurrentLinkedQueue源碼詳解
今天帶小伙伴們學(xué)習(xí)一下Java并發(fā)編程之Java ConcurrentLinkedQueue源碼,本篇文章詳細(xì)分析了ConcurrentLinkedQueue源碼,有代碼示例,對正在學(xué)習(xí)java的小伙伴們很有幫助喲,需要的朋友可以參考下2021-05-05java Socket編程實現(xiàn)I/O多路復(fù)用的示例
本文主要介紹了java Socket編程實現(xiàn)I/O多路復(fù)用的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09Springboot?+redis+谷歌開源Kaptcha實現(xiàn)圖片驗證碼功能
這篇文章主要介紹了Springboot?+redis+?歌開源Kaptcha實現(xiàn)圖片驗證碼功能,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-01-01