1
回答
Sha1Util
华为云4核8G,高性能云服务器,免费试用   
package com.pawf.controller.base;


import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class Sha1Util {
private static Log logger = LogFactory.getLog(Sha1Util.class);


private static final String CLASS_NAME = "Sha1Util.";




/*
* Convert byte[] to hex
* string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。

* @param src byte[] data

* @return hex string
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}


/**
* 将需要签名的字段作为

* @param datas
* @param signature
* @return
*/
public static String getSignature(List<String> datas, String sha1Key) {
logger.info(CLASS_NAME + "checkSignature() datas:" + datas);


if (null == datas || datas.isEmpty() || StringUtils.isEmpty(sha1Key)) {
logger.warn(CLASS_NAME + "checkSignature() datas:" + datas
+ ",datas is null Or signature is null.");
return "";
}
datas.add(sha1Key);
Collections.sort(datas);
StringBuffer paicString = new StringBuffer(datas.size());
for (int i = 0; i < datas.size(); i++) {
paicString = paicString.append(datas.get(i));
}
String param = paicString.toString();
// 六个参数组成的字符串
logger.info("Sha1Util.checkSignature() param:" + param);
System.out.println(param);
MessageDigest md = null;
String signatureNew = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将六个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(param.getBytes());
// 将sha1加密后的字符串可与signature对比
signatureNew = bytesToHexString(digest);
// paServers算出的签名
logger.info(CLASS_NAME + "checkSignature() signatureNew:"
+ signatureNew);
return signatureNew;
} catch (Exception e) {
logger.error(CLASS_NAME + "checkSignature() is faild. e:"
+ e.toString());
}
return "";
}



/**
* 字典序排序测试
* @param args
*/
public static void main(String[] args) {
List<String> datas = new ArrayList<String>(5);
datas.add("100010");// jseesionid
datas.add("/5cgqHQ06m4iAlqy6R+E5fh3UkjFkowsBFKMxX/dx8vl+NfqAlsKCwq4g9yBSbQOSb2Vw26sx2MI1+EEHzM1XxMUONGOQm9RCVaZtf6uz81l/IftqBbabg=="); // 时间戳
datas.add("KF1431"); // 随机数
datas.add("1476353644198"); // 随机数
Collections.sort(datas);
System.out.println(datas);
}



}

<无标签>
举报
北极之北
发帖于2年前 1回/147阅
顶部