| | |
| | | // ==================== HMAC-SHA256 签名 ==================== |
| | | |
| | | public static String signWebsocket(String timestamp, String secretKey) { |
| | | return sign(timestamp, "GET", "/users/self/verify", "", secretKey); |
| | | } |
| | | |
| | | public static String signRest(String timestamp, String method, String path, String body, String secretKey) { |
| | | return sign(timestamp, method.toUpperCase(), path, body, secretKey); |
| | | } |
| | | |
| | | private static String sign(String timestamp, String method, String path, String body, String secretKey) { |
| | | try { |
| | | String message = String.format("%s%s%s", timestamp, "GET", "/users/self/verify"); |
| | | String message = String.format("%s%s%s%s", timestamp, method, path, body); |
| | | Mac mac = Mac.getInstance("HmacSHA256"); |
| | | SecretKeySpec spec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256"); |
| | | mac.init(spec); |
| | |
| | | |
| | | // ==================== 订单ID ==================== |
| | | |
| | | private static final ThreadLocal<SimpleDateFormat> ORDER_ID_DF = |
| | | ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss")); |
| | | |
| | | private static final ThreadLocal<Random> RANDOM = |
| | | ThreadLocal.withInitial(Random::new); |
| | | |
| | | public static String getOrderNum(String prefix) { |
| | | SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); |
| | | String dd = df.format(new Date()); |
| | | String dd = ORDER_ID_DF.get().format(new Date()); |
| | | if (prefix != null && !prefix.isEmpty()) { |
| | | return prefix + dd + getRandomNum(5); |
| | | } |
| | |
| | | |
| | | private static String getRandomNum(int length) { |
| | | String str = "0123456789"; |
| | | Random random = new Random(); |
| | | Random random = RANDOM.get(); |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (int i = 0; i < length; ++i) { |
| | | sb.append(str.charAt(random.nextInt(str.length()))); |
| | |
| | | |
| | | // ==================== 日期格式化 ==================== |
| | | |
| | | private static final ThreadLocal<SimpleDateFormat> DATE_TIME_DF = |
| | | ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); |
| | | |
| | | private static final ThreadLocal<SimpleDateFormat> ISO8601_DF = |
| | | ThreadLocal.withInitial(() -> { |
| | | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); |
| | | sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC")); |
| | | return sdf; |
| | | }); |
| | | |
| | | public static String getIso8601Timestamp() { |
| | | return ISO8601_DF.get().format(new Date()); |
| | | } |
| | | |
| | | public static String timestampToDateTime(long timestamp) { |
| | | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); |
| | | return sdf.format(new Date(timestamp)); |
| | | return DATE_TIME_DF.get().format(new Date(timestamp)); |
| | | } |
| | | } |