update lianlian

This commit is contained in:
2023-05-26 16:14:45 +08:00
parent 03f7fd703a
commit 9a238d6ae2
34 changed files with 50 additions and 48 deletions

View File

@@ -1,248 +0,0 @@
/**
*/
package com.jsowell.common.lianlian;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
public class Cryptos {
private static final String AES = "AES";
private static final String AES_CBC = "AES/CBC/PKCS5Padding";
private static final String HMACSHA1 = "HmacSHA1";
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final int DEFAULT_HMACSHA1_KEYSIZE = 160; //RFC2401
private static final int DEFAULT_AES_KEYSIZE = 128;
private static final int DEFAULT_IVSIZE = 16;
private static final byte[] DEFAULT_KEY = new byte[]{-97,88,-94,9,70,-76,126,25,0,3,-20,113,108,28,69,125};
private static SecureRandom random = new SecureRandom();
//-- HMAC-SHA1 funciton --//
/**
* 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
*
* @param input 原始输入字符数组
* @param key HMAC-SHA1密钥
*/
public static byte[] hmacSha1(byte[] input, byte[] key) {
try {
SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
Mac mac = Mac.getInstance(HMACSHA1);
mac.init(secretKey);
return mac.doFinal(input);
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 校验HMAC-SHA1签名是否正确.
*
* @param expected 已存在的签名
* @param input 原始输入字符串
* @param key 密钥
*/
public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) {
byte[] actual = hmacSha1(input, key);
return Arrays.equals(expected, actual);
}
/**
* 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
* HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
*/
public static byte[] generateHmacSha1Key() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
//-- AES funciton --//
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
*/
public static String aesEncrypt(String input) {
try {
return Encodes.encodeHex(aesEncrypt(input.getBytes(DEFAULT_URL_ENCODING), DEFAULT_KEY));
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
*/
public static String aesEncrypt(String input, String key) {
try {
return Encodes.encodeHex(aesEncrypt(input.getBytes(DEFAULT_URL_ENCODING), Encodes.decodeHex(key)));
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
*/
public static byte[] aesEncrypt(byte[] input, byte[] key) {
return aes(input, key, Cipher.ENCRYPT_MODE);
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
* @param iv 初始向量
*/
public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
return aes(input, key, iv, Cipher.ENCRYPT_MODE);
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
*/
public static String aesDecrypt(String input) {
try {
return new String(aesDecrypt(Encodes.decodeHex(input), DEFAULT_KEY), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
*/
public static String aesDecrypt(String input, String key) {
try {
return new String(aesDecrypt(Encodes.decodeHex(input), Encodes.decodeHex(key)), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
*/
public static byte[] aesDecrypt(byte[] input, byte[] key) {
return aes(input, key, Cipher.DECRYPT_MODE);
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
* @param iv 初始向量
*/
public static byte[] aesDecrypt(byte[] input, byte[] key, byte[] iv) {
return aes(input, key, iv, Cipher.DECRYPT_MODE);
}
/**
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
*
* @param input 原始字节数组
* @param key 符合AES要求的密钥
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
*/
private static byte[] aes(byte[] input, byte[] key, int mode) {
try {
SecretKey secretKey = new SecretKeySpec(key, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(mode, secretKey);
return cipher.doFinal(input);
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
*
* @param input 原始字节数组
* @param key 符合AES要求的密钥
* @param iv 初始向量
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
*/
private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
try {
SecretKey secretKey = new SecretKeySpec(key, AES);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(AES_CBC);
cipher.init(mode, secretKey, ivSpec);
return cipher.doFinal(input);
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
*/
public static String generateAesKeyString() {
return Encodes.encodeHex(generateAesKey(DEFAULT_AES_KEYSIZE));
}
/**
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
*/
public static byte[] generateAesKey() {
return generateAesKey(DEFAULT_AES_KEYSIZE);
}
/**
* 生成AES密钥,可选长度为128,192,256位.
*/
public static byte[] generateAesKey(int keysize) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(keysize);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
*/
public static byte[] generateIV() {
byte[] bytes = new byte[DEFAULT_IVSIZE];
random.nextBytes(bytes);
return bytes;
}
}

View File

@@ -1,113 +0,0 @@
/**
*/
package com.jsowell.common.lianlian;
import org.apache.commons.lang3.Validate;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
public class Digests {
private static final String SHA1 = "SHA-1";
private static final String MD5 = "MD5";
private static SecureRandom random = new SecureRandom();
/**
* 对输入字符串进行md5散列.
*/
public static byte[] md5(byte[] input) {
return digest(input, MD5, null, 1);
}
public static byte[] md5(byte[] input, int iterations) {
return digest(input, MD5, null, iterations);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input) {
return digest(input, SHA1, null, 1);
}
public static byte[] sha1(byte[] input, byte[] salt) {
return digest(input, SHA1, salt, 1);
}
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
return digest(input, SHA1, salt, iterations);
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
if (salt != null) {
digest.update(salt);
}
byte[] result = digest.digest(input);
for (int i = 1; i < iterations; i++) {
digest.reset();
result = digest.digest(result);
}
return result;
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 生成随机的Byte[]作为salt.
*
* @param numBytes byte数组的大小
*/
public static byte[] generateSalt(int numBytes) {
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
return bytes;
}
/**
* 对文件进行md5散列.
*/
public static byte[] md5(InputStream input) throws IOException {
return digest(input, MD5);
}
/**
* 对文件进行sha1散列.
*/
public static byte[] sha1(InputStream input) throws IOException {
return digest(input, SHA1);
}
private static byte[] digest(InputStream input, String algorithm) throws IOException {
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
int bufferLength = 8 * 1024;
byte[] buffer = new byte[bufferLength];
int read = input.read(buffer, 0, bufferLength);
while (read > -1) {
messageDigest.update(buffer, 0, read);
read = input.read(buffer, 0, bufferLength);
}
return messageDigest.digest();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
}

View File

@@ -1,142 +0,0 @@
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.jsowell.common.lianlian;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class Encodes {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
/**
* Hex编码.
*/
public static String encodeHex(byte[] input) {
return new String(Hex.encodeHex(input));
}
/**
* Hex解码.
*/
public static byte[] decodeHex(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw Exceptions.unchecked(e);
}
}
/**
* Base64编码.
*/
public static String encodeBase64(byte[] input) {
return new String(Base64.encodeBase64(input));
}
/**
* Base64编码.
*/
public static String encodeBase64(String input) {
try {
return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
} catch (UnsupportedEncodingException e) {
return "";
}
}
// /**
// * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
// */
// public static String encodeUrlSafeBase64(byte[] input) {
// return Base64.encodeBase64URLSafe(input);
// }
/**
* Base64解码.
*/
public static byte[] decodeBase64(String input) {
return Base64.decodeBase64(input.getBytes());
}
/**
* Base64解码.
*/
public static String decodeBase64String(String input) {
try {
return new String(Base64.decodeBase64(input.getBytes()), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* Base62编码。
*/
public static String encodeBase62(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
}
return new String(chars);
}
/**
* Html 转码.
*/
public static String escapeHtml(String html) {
return StringEscapeUtils.escapeHtml4(html);
}
/**
* Html 解码.
*/
public static String unescapeHtml(String htmlEscaped) {
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
}
/**
* Xml 转码.
*/
public static String escapeXml(String xml) {
return StringEscapeUtils.escapeXml10(xml);
}
/**
* Xml 解码.
*/
public static String unescapeXml(String xmlEscaped) {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public static String urlEncode(String part) {
try {
return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.unchecked(e);
}
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public static String urlDecode(String part) {
try {
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.unchecked(e);
}
}
}

View File

@@ -1,72 +0,0 @@
package com.jsowell.common.lianlian;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 关于异常的工具类.
*/
public class Exceptions {
private static Logger logger = LoggerFactory.getLogger(Exceptions.class);
/**
* 将CheckedException转换为UncheckedException.
*/
public static RuntimeException unchecked(Exception e) {
if (e instanceof RuntimeException) {
return (RuntimeException) e;
} else {
return new RuntimeException(e);
}
}
/**
* 将ErrorStack转化为String.
*/
public static String getStackTraceAsString(Throwable e) {
if (e == null) {
return "";
}
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* 判断异常是否由某些底层的异常引起.
*/
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
Throwable cause = ex.getCause();
while (cause != null) {
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
if (causeClass.isInstance(cause)) {
return true;
}
}
cause = cause.getCause();
}
return false;
}
/**
* 在request中获取异常类
*
* @param request
* @return
*/
public static Throwable getThrowable(HttpServletRequest request) {
Throwable ex = null;
if (request.getAttribute("exception") != null) {
ex = (Throwable) request.getAttribute("exception");
} else if (request.getAttribute("javax.servlet.error.exception") != null) {
ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
}
return ex;
}
}

View File

@@ -1,58 +0,0 @@
package com.jsowell.common.lianlian;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Map;
public class GBSignUtils {
public static final Logger logger = LoggerFactory.getLogger(GBSignUtils.class);
public static String sign(Map<String, String> paramValues, String secret) {
try {
StringBuilder sb = new StringBuilder();
for (String value : paramValues.values()) {
if (StringUtils.isNotBlank(value)) {
sb.append(value);
}
}
logger.debug("需要签名的内容:{},密钥{}", sb.toString(), secret);
byte[] md5Digest = HmacMD5Encrypt(sb.toString(), secret);
String result = Encodes.encodeHex(md5Digest).toUpperCase();
logger.debug("HmacSHA1的签名内容{}", result);
return result;
} catch (Exception e) {
throw new RuntimeException("数据签名出错", e);
}
}
/**
* 使用 HMAC-MD5 签名方法对对encryptText进行签名
*
* @param encryptText
* 被签名的字符串
* @param encryptKey
* 密钥
* @return
* @throws Exception
*/
public static byte[] HmacMD5Encrypt(String encryptText, String encryptKey) throws Exception {
byte[] data = encryptKey.getBytes("UTF-8");
// 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKey secretKey = new SecretKeySpec(data, "HmacMD5");
// 生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance("HmacMD5");
// 用给定密钥初始化 Mac 对象
mac.init(secretKey);
byte[] text = encryptText.getBytes("UTF-8");
// 完成 Mac 操作
return mac.doFinal(text);
}
}

View File

@@ -1,143 +0,0 @@
package com.jsowell.common.lianlian;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Maps;
import com.jsowell.common.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.Date;
import java.util.Map;
/**
* @author 联联充电
*/
@Slf4j
@SuppressWarnings(value = "unused")
public class HttpRequestUtil {
/**
* httpClient--post请求--http
*
* @param url
* @param json
* @return
*/
public static String httpPost(String url, String json, String token) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//创建httpPost
HttpPost httpPost = new HttpPost(url);
//设置Content-Type
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", token);
//写入json数据
httpPost.setEntity(new StringEntity(json));
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000)
.setConnectionRequestTimeout(50000)
.setSocketTimeout(50000)
.build();
httpPost.setConfig(requestConfig);
//发起请求获取response对象
response = httpClient.execute(httpPost);
//获取结果状态码
int resultCode = response.getStatusLine().getStatusCode();
if (resultCode == 200) {
//获取返回数据实体对象
HttpEntity entity = response.getEntity();
//转化为字符串
String result = EntityUtils.toString(entity, "UTF-8");
//封装统一的返回数据接收类
//ResponseMsg responseMsg = (ResponseMsg) JSON.parse(result);
return result;
} else {
log.info("http请求失败");
}
} catch (Exception e) {
log.info("http请求异常");
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (Exception e) {
log.info(e.getMessage(), e);
}
}
return null;
}
/**
* 联联平台发送请求
*
* @param token 联联平台令牌
* @param data 要传输的JsonString格式数据
* @param url 请求地址
* @param dataSecret 消息密钥
* @param dataSecretIV 消息密钥初始化向量
* @param operatorId 运营商id
* @param sigSecret 签名密钥
* @return
*/
public static String sendPost(String token, String data, String url, String dataSecret,
String dataSecretIV, String operatorId, String sigSecret){
//加密
byte[] encryptText = Cryptos.aesEncrypt(data.getBytes(),
dataSecret.getBytes(), dataSecretIV.getBytes());
String encryptData = Encodes.encodeBase64(encryptText);
System.out.println("加密数据:" + encryptData);
Map<String, String> params = Maps.newLinkedHashMap();
params.put("OperatorID", operatorId);
params.put("Data", encryptData);
params.put("TimeStamp", DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS, new Date()));
params.put("Seq", "001");
String sign = GBSignUtils.sign(params, sigSecret);
params.put("Sig", sign);
String postData = JSON.toJSONString(params);
System.out.println("最终提交数据:" + postData);
String hutoolRequest = HttpRequest.post(url).header("Authorization", "Bearer " + token).body(postData).execute().body();
System.out.println("接收到返回数据:" + hutoolRequest);
Map<String, String> map = (Map<String, String>) JSON.parse(hutoolRequest);
String rData = map.get("Data");
String resultMsg = map.get("Msg");
byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(rData),
dataSecret.getBytes(), dataSecretIV.getBytes());
String plainData = "";
try {
plainData = new String(plainText, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("解密数据:" + plainData);
return resultMsg;
}
}

View File

@@ -1,48 +0,0 @@
package com.jsowell.common.lianlian;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.util.BytesUtil;
import com.jsowell.common.util.DateUtils;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Locale;
/**
* 联联平台工具类
*
* @author JS-ZZA
* @date 2023/5/6 14:22
*/
public class LianLianUtils {
static final String ALGORITHM_MAC = "HmacMD5";
/** 密钥 **/
static final String MAC_KEY = "TmsdVaFVTtjzZbLi";
/**
* HMAC加密
* @return
* @throws Exception
*/
public static String encryptionHMAC(String source) throws Exception {
SecretKey secretKey = new SecretKeySpec(MAC_KEY.getBytes("UTF-8"), ALGORITHM_MAC);
Mac mac = Mac.getInstance(ALGORITHM_MAC);
mac.init(secretKey);
mac.update(source.getBytes("UTF-8"));
return BytesUtil.binary(mac.doFinal(), 16).toUpperCase(Locale.ROOT);
}
/**
* 拼接参数
* @param Data
* @return
*/
public static String connectData(String Data){
String timeStamp = DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
String number = "0001";
return Constants.OPERATORID_LIANLIAN + Data + timeStamp + number;
}
}

View File

@@ -1,116 +0,0 @@
package com.jsowell.common.lianlian;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;
public class SignUtils {
private static String UTF_8 = "UTF-8";
/**
* 使用<code>secret</code>对paramValues按以下算法进行签名 <br/>
* uppercase(hex(sha1(secretkey1value1key2value2...secret))
*
* @param paramValues
* 参数列表
* @param secret
* @return
*/
public static String sign(Map<String, String> paramValues, String secret) {
return sign(paramValues, null, secret);
}
/**
* 对paramValues进行签名其中ignoreParamNames这些参数不参与签名
*
* @param paramValues
* @param ignoreParamNames
* @param secret
* @return
*/
public static String sign(Map<String, String> paramValues, List<String> ignoreParamNames, String secret) {
try {
StringBuilder sb = new StringBuilder();
List<String> paramNames = new ArrayList<String>(paramValues.size());
paramNames.addAll(paramValues.keySet());
if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
for (String ignoreParamName : ignoreParamNames) {
paramNames.remove(ignoreParamName);
}
}
Collections.sort(paramNames);
sb.append(secret);
for (String paramName : paramNames) {
sb.append(paramName).append(paramValues.get(paramName));
}
sb.append(secret);
System.out.println("原始的签名:" + sb.toString());
byte[] sha1Digest = getSHA1Digest(sb.toString());
System.out.println("sha-1的二进制码" + String.valueOf(sha1Digest));
return byte2hex(sha1Digest);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String utf8Encoding(String value, String sourceCharsetName) {
try {
return new String(value.getBytes(sourceCharsetName), UTF_8);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
private static byte[] getSHA1Digest(String data) throws IOException {
byte[] bytes = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
bytes = md.digest(data.getBytes(UTF_8));
} catch (GeneralSecurityException gse) {
throw new IOException(gse.getMessage()) ;
}
return bytes;
}
// private static byte[] getMD5Digest(String data) throws IOException {
// byte[] bytes = null;
// try {
// MessageDigest md = MessageDigest.getInstance("MD5");
// bytes = md.digest(data.getBytes(UTF_8));
// } catch (GeneralSecurityException gse) {
// throw new IOException(gse.getMessage());
// }
// return bytes;
// }
/**
* 二进制转十六进制字符串
*
* @param bytes
* @return
*/
private static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
System.out.println("最终的签名:" + sign);
return sign.toString();
}
public static String getUUID() {
UUID uuid = UUID.randomUUID();
return uuid.toString().toUpperCase();
}
}

View File

@@ -1,144 +0,0 @@
package com.jsowell.common.lianlian.common;
import com.jsowell.common.lianlian.common.enums.ResultCode;
/**
* 接口返回类
*
* @author 联联充电
*/
public class CommonResult<T> {
/**
* 状态码
*/
private long ret;
/**
* 响应信息
*/
private String msg;
/**
* 返回数据
*/
private T data;
private String sig;
protected CommonResult() {
}
protected CommonResult(long ret, String msg, T data, String sig) {
this.ret = ret;
this.msg = msg;
this.data = data;
this.sig = sig;
}
/**
* 成功返回结果
*
* @param data 获取的数据
* @param <T>
* @return
*/
public static <T> CommonResult<T> success(T data) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), data, null);
}
/**
* 成功返回结果
*
* @param data 获取的数据
* @param message 提示的信息
* @param <T>
* @return
*/
public static <T> CommonResult<T> success(T data, String message) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data, null);
}
public static <T> CommonResult<T> success(Integer ret, String msg, T data, String sig) {
return new CommonResult<T>(ret, msg, data, sig);
}
/**
* 失败返回结果
*
* @param resultCode 错误码
* @param <T>
* @return
*/
public static <T> CommonResult<T> failed(ResultCode resultCode) {
return new CommonResult<T>(resultCode.getCode(), resultCode.getMsg(), null, null);
}
/**
* 失败返回
*
* @param code 错误码
* @param msg 提示信息
* @param <T>
* @return
*/
public static <T> CommonResult<T> failed(long code, String msg) {
return new CommonResult<T>(code, msg, null, null);
}
/**
* 失败返回结果
*
* @param msg 提示信息
* @param <T>
* @return
*/
public static <T> CommonResult<T> failed(String msg) {
return failed(ResultCode.ERROR.getCode(), msg);
}
/**
* 失败返回结果
*
* @param <T>
* @return
*/
public static <T> CommonResult<T> failed() {
return failed(ResultCode.ERROR);
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public long getRet() {
return ret;
}
public void setRet(long ret) {
this.ret = ret;
}
public String getSig() {
return sig;
}
public void setSig(String sig) {
this.sig = sig;
}
}

View File

@@ -1,30 +0,0 @@
package com.jsowell.common.lianlian.common.enums;
/**
* 返回结果枚举
*/
public enum ResultCode {
/**
* 接口返回枚举
*/
SUCCESS(200, "成功"),
ERROR(-1, "失败");
private int code;
private String msg;
ResultCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}