|
@@ -1,53 +0,0 @@
|
|
|
-package com.sooka.sponest.dataexchange.util;
|
|
|
-
|
|
|
-import javax.crypto.Mac;
|
|
|
-import javax.crypto.spec.SecretKeySpec;
|
|
|
-import java.io.UnsupportedEncodingException;
|
|
|
-import java.security.InvalidKeyException;
|
|
|
-import java.security.NoSuchAlgorithmException;
|
|
|
-
|
|
|
-public class HmacSHA256 {
|
|
|
-
|
|
|
- //十六进制字符集
|
|
|
- private final static char[] DIGEST_ARRAYS = {
|
|
|
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
|
|
|
- };
|
|
|
-
|
|
|
- /**
|
|
|
- * 功能:Signature生成算法
|
|
|
- * 输入参数:
|
|
|
- * 1.data: HMAC-SHA256的输入数据
|
|
|
- * 2.key: App Key
|
|
|
- * 输出参数:十六进制字符串编码的HMAC-SHA256值
|
|
|
- */
|
|
|
- public static String encode(String data, String key) {
|
|
|
- byte[] hashByte;
|
|
|
- try {
|
|
|
- Mac sha256HMAC = Mac.getInstance("HmacSHA256");
|
|
|
- SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
|
|
|
- sha256HMAC.init(secretKey);
|
|
|
-
|
|
|
- hashByte = sha256HMAC.doFinal(data.getBytes("UTF-8"));
|
|
|
- } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
|
|
|
- return null;
|
|
|
- }
|
|
|
-
|
|
|
- return bytesToHex(hashByte);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 功能:byte类型数组转换成十六进制字符串
|
|
|
- * 输入参数:
|
|
|
- * 1.bytes:被转换的字节数组
|
|
|
- * 输出参数:十六进制字符串
|
|
|
- */
|
|
|
- private static String bytesToHex(byte[] bytes) {
|
|
|
- StringBuffer hexStr = new StringBuffer();
|
|
|
- for (int i = 0; i < bytes.length; i++) {
|
|
|
- hexStr.append(DIGEST_ARRAYS[bytes[i] >>> 4 & 0X0F]);
|
|
|
- hexStr.append(DIGEST_ARRAYS[bytes[i] & 0X0F]);
|
|
|
- }
|
|
|
-
|
|
|
- return hexStr.toString();
|
|
|
- }
|
|
|
-}
|