SHA1算法工具类

package com.sinosoft.cms.common.util;
import java.security.MessageDigest;
import org.apache.commons.lang3.StringUtils;

import net.sf.json.JSONObject;

import java.util.Arrays;
import java.util.Random;
public class SHA1 {
/**
* 用SHA1算法生成安全签名
*
* @param timestamp 时间
* @param nonce 随机字符
* @param encrypt 密文
* @return 安全签名
*/
public static String getSHA1( String timestamp, String nonce, String encrypt) {
try {
if (StringUtils.isAnyEmpty(key, timestamp, nonce, encrypt)) {
throw new IllegalArgumentException("SHA1签名参数不可为空");
}
String[] array = new String[]{key, timestamp, nonce, encrypt};
StringBuilder sb = new StringBuilder();
// 字符串排序
Arrays.sort(array);
for (String anArray : array) {
sb.append(anArray);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();

StringBuilder hexStr = new StringBuilder();
String shaHex;
for (byte aDigest : digest) {
shaHex = Integer.toHexString(aDigest & 0xFF);
if (shaHex.length() < 2) {
hexStr.append(0);
}
hexStr.append(shaHex);
}
return hexStr.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 生成6位随机字符串
* @return
*/
public static String getRandomStr() {
int length = 6;
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}

/**
* 生成时间戳
* @return
*/
public static String getTimeStamp() {
// return String.valueOf(System.currentTimeMillis()/10);//158400509458
return String.valueOf(System.currentTimeMillis()); //1584005148819
}


// public static void main(String[] args) throws Exception {
// String timestamp = SHA1.getTimeStamp();//生产时间戳
// String nonce = SHA1.getRandomStr();//随机生成6位数
// String encrypt = "6A987408D05B0CEE7FAF5FCB5E8796CE88558E8F6C12F1F9E2E85F";
// String sign = getSHA1(timestamp, nonce,encrypt);
// System.out.println("signature:" + timestamp);
// }

}

posted on 2020-03-12 17:33  多言  阅读(689)  评论(0编辑  收藏  举报

导航