|
|
@@ -0,0 +1,71 @@
|
|
|
+package com.template.common.utils;
|
|
|
+
|
|
|
+import javax.crypto.Mac;
|
|
|
+import javax.crypto.spec.SecretKeySpec;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+public class EncryptionUtils
|
|
|
+{
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 将加密后的字节数组转换成字符串
|
|
|
+ *
|
|
|
+ * @param b 字节数组
|
|
|
+ * @return 字符串
|
|
|
+ */
|
|
|
+ public static String byteArrayToHexString(byte[] b) {
|
|
|
+ StringBuilder hs = new StringBuilder();
|
|
|
+ String stmp;
|
|
|
+ for (int n = 0; b!=null && n < b.length; n++) {
|
|
|
+ stmp = Integer.toHexString(b[n] & 0XFF);
|
|
|
+ if (stmp.length() == 1)
|
|
|
+ {
|
|
|
+ hs.append('0');
|
|
|
+ }
|
|
|
+ hs.append(stmp);
|
|
|
+ }
|
|
|
+ return hs.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) {
|
|
|
+ System.err.println("Error HmacSHA256 ===========,{}"+ e.getMessage());
|
|
|
+ }
|
|
|
+ return hash;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String getSignContent(Map<String, String> params) {
|
|
|
+ // 第一步:检查参数是否已经排序
|
|
|
+ String[] keys = params.keySet().toArray(new String[0]);
|
|
|
+ Arrays.sort(keys);
|
|
|
+
|
|
|
+ // 第二步:把所有参数名和参数值串在一起
|
|
|
+ StringBuilder query = new StringBuilder();
|
|
|
+
|
|
|
+ for (String key : keys) {
|
|
|
+ String value = params.get(key);
|
|
|
+ if ((!"".equals(key) && null != key) && (!"".equals(value) && null != value))
|
|
|
+ {
|
|
|
+ query.append(key).append(value);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return query.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+}
|