#2
hwf2982024-11-27 14:59
回复 楼主 hwf298
|
package com.lou.springboot;
import
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Random;
public class SignUtil {
private SignUtil() {
}
public static void main(String[] args) {
String xRioNonce = getRandomString(32); //随机数
String xRioTimestamp = String.valueOf(getCurrentUnixSeconds()); //时间戳
String signature = getSHA256Str(xRioTimestamp + secretKey + xRioNonce + xRioTimestamp); //签名
}
/*** 获取随机数 */
private static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
int number = random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
/*** 获取当前时间戳 */
private static long getCurrentUnixSeconds() {
ZoneOffset zoneOffset = ZoneOffset.ofHours(8);
LocalDateTime localDateTime = LocalDateTime.now();
return localDateTime.toEpochSecond(zoneOffset);
}
/*** 使用SHA-256算法进行加密 */
private static String getSHA256Str(String str) {
String encodeStr = "";
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes("UTF-8"));
encodeStr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException var4) {
var4.printStackTrace();
} catch (UnsupportedEncodingException var5) {
var5.printStackTrace();
}
return encodeStr;
}
private static String byte2Hex(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i = 0; i < bytes.length; ++i) {
temp = Integer.toHexString(bytes[i] & 255);
if (temp.length() == 1) {
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
}
[此贴子已经被作者于2024-11-27 08:44编辑过]