#chabaodao-1# 北森、飞书等集成开发
This commit is contained in:
parent
7a1e8655bd
commit
142f89c8be
|
|
@ -0,0 +1,72 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
public class HmacSHA256Example {
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
// 密钥(在CryptoJS中通常称为secret key)
|
||||
String secretKey = "7f067a08f5c675137e6e72aa298e2c07"; // 替换为你的密钥
|
||||
// 要签名的数据
|
||||
String data = "{\"templateId\": \"JMHT-ZXSJ\"}"; // 替换为你要签名的数据
|
||||
data = data
|
||||
.replaceAll("\\\\.", Matcher.quoteReplacement("$0"));
|
||||
System.out.println(data);
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("templateId","JMHT-ZXSJ");
|
||||
|
||||
// 初始化Mac对象
|
||||
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
|
||||
sha256Hmac.init(secretKeySpec);
|
||||
|
||||
// 执行HmacSHA256操作
|
||||
byte[] result = sha256Hmac.doFinal(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
String data99 = bytesToHex(result);
|
||||
System.out.println("HMAC-data99: " + data99);
|
||||
// 将结果转换为Base64编码的字符串(与CryptoJS输出的格式一致)
|
||||
String hmacResult = Base64.getEncoder().encodeToString(result);
|
||||
|
||||
String data2 = Hex.encodeHexString(result);
|
||||
|
||||
String hash = Base64.getEncoder().encodeToString(result);
|
||||
|
||||
String hash2 = Base64.getUrlEncoder().withoutPadding().encodeToString(result);
|
||||
|
||||
StringBuilder hexSignature = new StringBuilder();
|
||||
for (byte b : result) {
|
||||
String hex = Integer.toHexString(b & 0xFF);
|
||||
if (hex.length() == 1) {
|
||||
hexSignature.append("0");
|
||||
}
|
||||
hexSignature.append(hex);
|
||||
}
|
||||
System.out.println("HMAC-SHA256签名: " + hexSignature.toString());
|
||||
|
||||
|
||||
System.out.println("HMAC SHA256 Result: " + hmacResult);
|
||||
System.out.println("HMAC SHA256 Result2: " + data2);
|
||||
System.out.println("HMAC SHA256 hash: " + hash);
|
||||
System.out.println("HMAC SHA256 hash2: " + hash2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
result.append(String.format("%02x", b));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,417 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
import org.apache.http.client.methods.*;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.entity.ByteArrayEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.apache.http.entity.ContentType;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* signature demo
|
||||
*/
|
||||
public class SignatureDemo {
|
||||
|
||||
/**
|
||||
* 日期格式化工具,用于将日期时间字符串格式化为"yyyy-MM-dd'T'HH:mm:ss'Z'"的格式。
|
||||
*/
|
||||
private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
|
||||
|
||||
private static class SignatureRequest {
|
||||
// HTTP Method
|
||||
private final String httpMethod;
|
||||
// 请求路径,当资源路径为空时,使用正斜杠(/)作为CanonicalURI
|
||||
private final String canonicalUri;
|
||||
// endpoint
|
||||
private final String host;
|
||||
// API name
|
||||
private final String xAcsAction;
|
||||
// API version
|
||||
private final String xAcsVersion;
|
||||
// headers
|
||||
TreeMap<String, String> headers = new TreeMap<>();
|
||||
// body参数对应的字节数组,请求参数在元数据中显示"in":"body"或"in": "formData",表示参数放在body中
|
||||
byte[] body;
|
||||
// query参数,请求参数在元数据中显示"in":"query",表示参数拼接在请求URL上
|
||||
TreeMap<String, Object> queryParam = new TreeMap<>();
|
||||
|
||||
public SignatureRequest(String httpMethod, String canonicalUri, String host, String xAcsAction, String xAcsVersion) {
|
||||
this.httpMethod = httpMethod;
|
||||
this.canonicalUri = canonicalUri;
|
||||
this.host = host;
|
||||
this.xAcsAction = xAcsAction;
|
||||
this.xAcsVersion = xAcsVersion;
|
||||
initHeader();
|
||||
}
|
||||
|
||||
// init headers
|
||||
private void initHeader() {
|
||||
headers.put("host", host);
|
||||
headers.put("x-acs-action", xAcsAction);
|
||||
headers.put("x-acs-version", xAcsVersion);
|
||||
SDF.setTimeZone(new SimpleTimeZone(0, "GMT")); // 设置日期格式化时区为GMT
|
||||
headers.put("x-acs-date", SDF.format(new Date()));
|
||||
headers.put("x-acs-signature-nonce", UUID.randomUUID().toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* System.getenv()表示通过环境变量获取Access Key ID和Access Key Secret。
|
||||
*/
|
||||
private final static String ACCESS_KEY_ID = System.getenv("LTAI5tC2WxpLdtEdg1wLaaYp");
|
||||
private final static String ACCESS_KEY_SECRET = System.getenv("iPXi2unHR643PcKRkT89jg8aNrocPD");
|
||||
|
||||
/**
|
||||
* 签名协议
|
||||
*/
|
||||
private static final String ALGORITHM = "ACS3-HMAC-SHA256";
|
||||
|
||||
/**
|
||||
* 签名示例,您需要根据实际情况替换main方法中的示例参数。
|
||||
* ROA接口和RPC接口只有canonicalUri取值逻辑是完全不同,其余内容都是相似的。
|
||||
* <p>
|
||||
* 通过API元数据获取请求方法(methods)、请求参数名称(name)、请求参数类型(type)、请求参数位置(in),并将参数封装到SignatureRequest中。
|
||||
* 1. 请求参数在元数据中显示"in":"query",通过queryParam传参。
|
||||
* 2. 请求参数在元数据中显示"in": "body",通过body传参。
|
||||
* 3. 请求参数在元数据中显示"in": "formData",通过body传参。
|
||||
*/
|
||||
public static void main(String[] args) throws IOException {
|
||||
// RPC接口请求示例一:请求参数"in":"query"
|
||||
String httpMethod = "POST"; // 请求方式,从元数据中可以获取,建议使用POST。
|
||||
String canonicalUri = "/"; // RPC接口无资源路径,故使用正斜杠(/)作为CanonicalURI
|
||||
String host = "ecs.cn-hangzhou.aliyuncs.com"; // 云产品服务接入点
|
||||
String xAcsAction = "DescribeInstanceStatus"; // API名称
|
||||
String xAcsVersion = "2014-05-26"; // API版本号
|
||||
SignatureRequest signatureRequest = new SignatureRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);
|
||||
// DescribeInstanceStatus请求参数如下:
|
||||
// RegionId在元数据中显示的类型是String,"in":"query",必填
|
||||
signatureRequest.queryParam.put("RegionId", "cn-hangzhou");
|
||||
// InstanceId的在元数据中显示的类型是array,"in":"query",非必填
|
||||
// String[] instanceIds = {"i-bp10igfmnyttXXXXXXXX", "i-bp1incuofvzxXXXXXXXX", "i-bp1incuofvzxXXXXXXXX"};
|
||||
// signatureRequest.queryParam.put("InstanceId", Arrays.asList(instanceIds));
|
||||
|
||||
/*// RPC接口请求示例二:请求参数"in":"body"
|
||||
String httpMethod = "POST";
|
||||
String canonicalUri = "/";
|
||||
String host = "ocr-api.cn-hangzhou.aliyuncs.com";
|
||||
String xAcsAction = "RecognizeGeneral";
|
||||
String xAcsVersion = "2021-07-07";
|
||||
SignatureRequest signatureRequest = new SignatureRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);
|
||||
// 请求参数在元数据中显示"in": "body",通过body传参。
|
||||
signatureRequest.body = Files.readAllBytes(Paths.get("D:\\test.png"));
|
||||
signatureRequest.headers.put("content-type", "application/octet-stream");*/
|
||||
|
||||
/*// RPC接口请求示例三:请求参数"in": "formData"
|
||||
String httpMethod = "POST";
|
||||
String canonicalUri = "/";
|
||||
String host = "mt.aliyuncs.com";
|
||||
String xAcsAction = "TranslateGeneral";
|
||||
String xAcsVersion = "2018-10-12";
|
||||
SignatureRequest signatureRequest = new SignatureRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);
|
||||
// TranslateGeneral请求参数如下:
|
||||
// Context在元数据中显示的类型是String,"in":"query",非必填
|
||||
signatureRequest.queryParam.put("Context", "早上");
|
||||
// FormatType、SourceLanguage、TargetLanguage等参数,在元数据中显示"in":"formData"
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("FormatType", "text");
|
||||
body.put("SourceLanguage", "zh");
|
||||
body.put("TargetLanguage", "en");
|
||||
body.put("SourceText", "你好");
|
||||
body.put("Scene", "general");
|
||||
String formDataToString = formDataToString(body);
|
||||
signatureRequest.body = formDataToString.getBytes(StandardCharsets.UTF_8);
|
||||
signatureRequest.headers.put("content-type", "application/x-www-form-urlencoded");*/
|
||||
|
||||
/*// ROA接口POST请求
|
||||
String httpMethod = "POST";
|
||||
String canonicalUri = "/clusters"; // 从元数据中获取:"path": "/clusters"
|
||||
String host = "cs.cn-beijing.aliyuncs.com"; // endpoint
|
||||
String xAcsAction= "CreateCluster"; // API名称
|
||||
String xAcsVersion= "2015-12-15"; // API版本号
|
||||
SignatureRequest signatureRequest = new SignatureRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);
|
||||
// 调用API所需要的参数,请求参数在元数据中显示"in": "body",表示参数放在body中
|
||||
TreeMap<String, Object> body = new TreeMap<>();
|
||||
body.put("name", "测试");
|
||||
body.put("region_id", "cn-beijing");
|
||||
body.put("cluster_type", "ExternalKubernetes");
|
||||
body.put("vpcid", "vpc-2zeou1uod4ylaXXXXXXXX");
|
||||
body.put("container_cidr","10.0.0.0/8");
|
||||
body.put("service_cidr", "10.2.0.0/24");
|
||||
body.put("security_group_id", "sg-2ze1a0rlgeo7XXXXXXXX");
|
||||
body.put("vswitch_ids", Collections.singletonList(
|
||||
"vsw-2zei30dhfldu8XXXXXXXX"
|
||||
));
|
||||
Gson gson = (new GsonBuilder()).disableHtmlEscaping().create();
|
||||
signatureRequest.body = gson.toJson(body).getBytes(StandardCharsets.UTF_8);
|
||||
signatureRequest.headers.put("content-type", "application/json");*/
|
||||
|
||||
/*// ROA接口GET请求
|
||||
String httpMethod = "GET";
|
||||
// canonicalUri如果存在path参数,需要对path参数encode,percentCode({path参数})
|
||||
String canonicalUri = "/clusters/" + percentCode("cdb14b4f85130407da748fd3fXXXXXXXX") + "/resources";
|
||||
String host = "cs.cn-beijing.aliyuncs.com"; // endpoint
|
||||
String xAcsAction = "DescribeClusterResources"; // API名称
|
||||
String xAcsVersion = "2015-12-15"; // API版本号
|
||||
SignatureRequest signatureRequest = new SignatureRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);
|
||||
signatureRequest.queryParam.put("with_addon_resources", true);*/
|
||||
|
||||
/*// ROA接口DELETE请求
|
||||
String httpMethod = "DELETE";
|
||||
String canonicalUri = "/clusters/" + percentCode("cdb14b4f85130407da748fd3fXXXXXXXX");
|
||||
String host = "cs.cn-beijing.aliyuncs.com";
|
||||
String xAcsAction = "DeleteCluster";
|
||||
String xAcsVersion = "2015-12-15";
|
||||
SignatureRequest signatureRequest = new SignatureRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);*/
|
||||
|
||||
// 签名过程
|
||||
getAuthorization(signatureRequest);
|
||||
// 调用API
|
||||
callApi(signatureRequest);
|
||||
}
|
||||
|
||||
private static void callApi(SignatureRequest signatureRequest) {
|
||||
try {
|
||||
// 通过HttpClient发送请求
|
||||
String url = "https://" + signatureRequest.host + signatureRequest.canonicalUri;
|
||||
URIBuilder uriBuilder = new URIBuilder(url);
|
||||
// 添加请求参数
|
||||
for (Map.Entry<String, Object> entry : signatureRequest.queryParam.entrySet()) {
|
||||
uriBuilder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
|
||||
}
|
||||
System.out.println(uriBuilder.build());
|
||||
HttpUriRequest httpRequest;
|
||||
switch (signatureRequest.httpMethod) {
|
||||
case "GET":
|
||||
httpRequest = new HttpGet(uriBuilder.build());
|
||||
break;
|
||||
case "POST":
|
||||
HttpPost httpPost = new HttpPost(uriBuilder.build());
|
||||
if (signatureRequest.body != null) {
|
||||
httpPost.setEntity(new ByteArrayEntity(signatureRequest.body, ContentType.create(signatureRequest.headers.get("content-type"))));
|
||||
}
|
||||
httpRequest = httpPost;
|
||||
break;
|
||||
case "DELETE":
|
||||
httpRequest = new HttpDelete(uriBuilder.build());
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unsupported HTTP method: " + signatureRequest.httpMethod);
|
||||
throw new IllegalArgumentException("Unsupported HTTP method");
|
||||
}
|
||||
|
||||
// 添加http请求头
|
||||
for (Map.Entry<String, String> entry : signatureRequest.headers.entrySet()) {
|
||||
httpRequest.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
|
||||
}
|
||||
// 发送请求
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpRequest)) {
|
||||
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
System.out.println(result);
|
||||
} catch (IOException e) {
|
||||
// 异常处理
|
||||
System.out.println("Failed to send request");
|
||||
e.printStackTrace();
|
||||
}
|
||||
} catch (URISyntaxException e) {
|
||||
// 异常处理
|
||||
System.out.println("Invalid URI syntax");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 该方法用于根据传入的HTTP请求方法、规范化的URI、查询参数等,计算并生成授权信息。
|
||||
*/
|
||||
private static void getAuthorization(SignatureRequest signatureRequest) {
|
||||
try {
|
||||
// 处理queryParam中参数值为List、Map类型的参数,将参数平铺
|
||||
TreeMap<String, Object> newQueryParam = new TreeMap<>();
|
||||
processObject(newQueryParam, "", signatureRequest.queryParam);
|
||||
signatureRequest.queryParam = newQueryParam;
|
||||
// 步骤 1:拼接规范请求串
|
||||
// 请求参数,当请求的查询字符串为空时,使用空字符串作为规范化查询字符串
|
||||
StringBuilder canonicalQueryString = new StringBuilder();
|
||||
signatureRequest.queryParam.entrySet().stream().map(entry -> percentCode(entry.getKey()) + "="
|
||||
+ percentCode(String.valueOf(entry.getValue()))).forEachOrdered(queryPart -> {
|
||||
// 如果canonicalQueryString已经不是空的,则在查询参数前添加"&"
|
||||
if (canonicalQueryString.length() > 0) {
|
||||
canonicalQueryString.append("&");
|
||||
}
|
||||
canonicalQueryString.append(queryPart);
|
||||
});
|
||||
|
||||
// 计算请求体的哈希值
|
||||
String requestPayload = ""; // 请求体,当请求正文为空时,比如GET请求,RequestPayload固定为空字符串
|
||||
String hashedRequestPayload = signatureRequest.body != null ? sha256Hex(signatureRequest.body) : sha256Hex(requestPayload.getBytes(StandardCharsets.UTF_8));
|
||||
signatureRequest.headers.put("x-acs-content-sha256", hashedRequestPayload);
|
||||
// 构造请求头,多个规范化消息头,按照消息头名称(小写)的字符代码顺序以升序排列后拼接在一起
|
||||
StringBuilder canonicalHeaders = new StringBuilder();
|
||||
// 已签名消息头列表,多个请求头名称(小写)按首字母升序排列并以英文分号(;)分隔
|
||||
StringBuilder signedHeadersSb = new StringBuilder();
|
||||
signatureRequest.headers.entrySet().stream().filter(entry -> entry.getKey().toLowerCase().startsWith("x-acs-") || "host".equalsIgnoreCase(entry.getKey()) || "content-type".equalsIgnoreCase(entry.getKey())).sorted(Map.Entry.comparingByKey()).forEach(entry -> {
|
||||
String lowerKey = entry.getKey().toLowerCase();
|
||||
String value = String.valueOf(entry.getValue()).trim();
|
||||
canonicalHeaders.append(lowerKey).append(":").append(value).append("\n");
|
||||
signedHeadersSb.append(lowerKey).append(";");
|
||||
});
|
||||
String signedHeaders = signedHeadersSb.substring(0, signedHeadersSb.length() - 1);
|
||||
String canonicalRequest = signatureRequest.httpMethod + "\n" + signatureRequest.canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestPayload;
|
||||
System.out.println("canonicalRequest=========>\n" + canonicalRequest);
|
||||
|
||||
// 步骤 2:拼接待签名字符串
|
||||
String hashedCanonicalRequest = sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); // 计算规范化请求的哈希值
|
||||
String stringToSign = ALGORITHM + "\n" + hashedCanonicalRequest;
|
||||
System.out.println("stringToSign=========>\n" + stringToSign);
|
||||
|
||||
// 步骤 3:计算签名
|
||||
String signature = DatatypeConverter.printHexBinary(hmac256(ACCESS_KEY_SECRET.getBytes(StandardCharsets.UTF_8), stringToSign)).toLowerCase();
|
||||
System.out.println("signature=========>" + signature);
|
||||
|
||||
// 步骤 4:拼接 Authorization
|
||||
String authorization = ALGORITHM + " " + "Credential=" + ACCESS_KEY_ID + ",SignedHeaders=" + signedHeaders + ",Signature=" + signature;
|
||||
System.out.println("authorization=========>" + authorization);
|
||||
signatureRequest.headers.put("Authorization", authorization);
|
||||
} catch (Exception e) {
|
||||
// 异常处理
|
||||
System.out.println("Failed to get authorization");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理请求参数类型为formData的参数。
|
||||
*
|
||||
* @param formData formData类型参数
|
||||
* @return String
|
||||
*/
|
||||
private static String formDataToString(Map<String, Object> formData) {
|
||||
Map<String, Object> tileMap = new HashMap<>();
|
||||
processObject(tileMap, "", formData);
|
||||
StringBuilder result = new StringBuilder();
|
||||
boolean first = true;
|
||||
String symbol = "&";
|
||||
for (Map.Entry<String, Object> entry : tileMap.entrySet()) {
|
||||
String value = String.valueOf(entry.getValue());
|
||||
if (value != null && !value.isEmpty()) {
|
||||
if (first) {
|
||||
first = false;
|
||||
} else {
|
||||
result.append(symbol);
|
||||
}
|
||||
result.append(percentCode(entry.getKey()));
|
||||
result.append("=");
|
||||
result.append(percentCode(value));
|
||||
}
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归处理对象,将复杂对象(如Map和List)展开为平面的键值对
|
||||
*
|
||||
* @param map 原始的键值对集合,将被递归地更新
|
||||
* @param key 当前处理的键,随着递归的深入,键会带有嵌套路径信息
|
||||
* @param value 对应于键的值,可以是嵌套的Map、List或其他类型
|
||||
*/
|
||||
private static void processObject(Map<String, Object> map, String key, Object value) {
|
||||
// 如果值为空,则无需进一步处理
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
if (key == null) {
|
||||
key = "";
|
||||
}
|
||||
// 当值为List类型时,遍历List中的每个元素,并递归处理
|
||||
if (value instanceof List<?>) {
|
||||
List<?> list = (List<?>) value;
|
||||
for (int i = 0; i < list.size(); ++i) {
|
||||
processObject(map, key + "." + (i + 1), list.get(i));
|
||||
}
|
||||
} else if (value instanceof Map<?, ?>) {
|
||||
// 当值为Map类型时,遍历Map中的每个键值对,并递归处理
|
||||
Map<?, ?> subMap = (Map<?, ?>) value;
|
||||
for (Map.Entry<?, ?> entry : subMap.entrySet()) {
|
||||
processObject(map, key + "." + entry.getKey().toString(), entry.getValue());
|
||||
}
|
||||
} else {
|
||||
// 对于以"."开头的键,移除开头的"."以保持键的连续性
|
||||
if (key.startsWith(".")) {
|
||||
key = key.substring(1);
|
||||
}
|
||||
// 对于byte[]类型的值,将其转换为UTF-8编码的字符串
|
||||
if (value instanceof byte[]) {
|
||||
map.put(key, new String((byte[]) value, StandardCharsets.UTF_8));
|
||||
} else {
|
||||
// 对于其他类型的值,直接转换为字符串
|
||||
map.put(key, String.valueOf(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用HmacSHA256算法生成消息认证码(MAC)。
|
||||
*
|
||||
* @param secretKey 密钥,用于生成MAC的密钥,必须保密。
|
||||
* @param str 需要进行MAC认证的消息。
|
||||
* @return 返回使用HmacSHA256算法计算出的消息认证码。
|
||||
* @throws Exception 如果初始化MAC或计算MAC过程中遇到错误,则抛出异常。
|
||||
*/
|
||||
public static byte[] hmac256(byte[] secretKey, String str) throws Exception {
|
||||
// 实例化HmacSHA256消息认证码生成器
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
// 创建密钥规范,用于初始化MAC生成器
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, mac.getAlgorithm());
|
||||
// 初始化MAC生成器
|
||||
mac.init(secretKeySpec);
|
||||
// 计算消息认证码并返回
|
||||
return mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用SHA-256算法计算字符串的哈希值并以十六进制字符串形式返回。
|
||||
*
|
||||
* @param input 需要进行SHA-256哈希计算的字节数组。
|
||||
* @return 计算结果为小写十六进制字符串。
|
||||
* @throws Exception 如果在获取SHA-256消息摘要实例时发生错误。
|
||||
*/
|
||||
public static String sha256Hex(byte[] input) throws Exception {
|
||||
// 获取SHA-256消息摘要实例
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
// 计算字符串s的SHA-256哈希值
|
||||
byte[] d = md.digest(input);
|
||||
// 将哈希值转换为小写十六进制字符串并返回
|
||||
return DatatypeConverter.printHexBinary(d).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对指定的字符串进行URL编码。
|
||||
* 使用UTF-8编码字符集对字符串进行编码,并对特定的字符进行替换,以符合URL编码规范。
|
||||
*
|
||||
* @param str 需要进行URL编码的字符串。
|
||||
* @return 编码后的字符串。其中,加号"+"被替换为"%20",星号"*"被替换为"%2A",波浪号"%7E"被替换为"~"。
|
||||
*/
|
||||
public static String percentCode(String str) {
|
||||
if (str == null) {
|
||||
throw new IllegalArgumentException("输入字符串不可为null");
|
||||
}
|
||||
try {
|
||||
return URLEncoder.encode(str, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException("UTF-8编码不被支持", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
|
||||
import cn.hutool.json.JSONArray;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import com.weaver.seconddev.chapanda.beisen.entity.BeisenStaffDepartmentDto;
|
||||
import com.weaver.seconddev.chapanda.beisen.entity.BeisenStaffDto;
|
||||
import com.weaver.seconddev.chapanda.beisen.entity.BeisenStaffPositionDto;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class Test88 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String bodyData = "{\"total\":1,\"code\":200,\"message\":\"操作成功\",\"sortCursor\":null,\"lastData\":false,\"items\":[{\"staffDto\":{\"avatar\":null,\"departmentId\":836572,\"departmentName\":\"人力资源中心\",\"employedDate\":\"2022-02-17T00:00:00.0000\",\"jobCode\":\"\",\"lineManagerId\":0,\"staffCode\":\"1000003111\",\"staffStatus\":0,\"isDelete\":0,\"allowLogin\":0,\"userId\":404156367,\"tenantId\":431582,\"email\":\"testwangbo@chabaidao.com\",\"userType\":3,\"userStatus\":0,\"origin\":8,\"originalId\":\"404156367\",\"name\":\"测试王波\",\"englishName\":\"\",\"sex\":\"\",\"educationBackground\":\"\",\"mobile\":\"\",\"workPhone\":\"\",\"homePhone\":\"\",\"idCardType\":\"\",\"idCardNumber\":\"\",\"maritalStatus\":\"\",\"nation\":\"\",\"backupMail\":\"\",\"address\":\"\",\"nativePlace\":\"\",\"personalHomePage\":\"\",\"politicalStatus\":\"\",\"speciality\":\"\",\"graduateFrom\":\"\",\"major\":\"\",\"positionCategory\":\"\",\"msn\":\"\",\"qq\":\"\",\"skype\":\"\",\"blog\":\"\",\"gTalk\":\"\",\"aboutMe\":\"\",\"bindMsn\":\"\",\"officeLocation\":\"\",\"bizTitleId\":\"00000000-0000-0000-0000-000000000000\",\"weChat\":\"\",\"modifiedBy\":10000,\"createBy\":402172443,\"bu\":0,\"version\":0},\"departmentDto\":{\"id\":836572,\"name\":\"人力资源中心\",\"code\":\"07\",\"description\":null,\"abbreviation\":\"人力资源中心\",\"parentId\":836553,\"path\":\"/1676228/836553/836572\",\"level\":3,\"status\":1,\"originalId\":\"428102\",\"staffNumber\":4,\"isDelete\":0,\"orderId\":12,\"orgLeaders\":[{\"lids\":[404155397],\"type\":1}],\"modifiedTime\":\"2025-07-10T07:27:41.4690\",\"createTime\":\"2022-07-01T01:44:57.0500\",\"modifiedBy\":10000,\"createBy\":10000,\"languageDic\":{\"name_srp\":\"\",\"shortName_zh_TW\":\"\",\"name_ru\":\"\",\"name_in\":\"\",\"name_en_US\":\"\",\"shortName_bn\":\"\",\"shortName_ko\":\"\",\"name_de\":\"\",\"shortName_it\":\"\",\"shortName_ru\":\"\",\"shortName_km\":\"\",\"shortName_tr\":\"\",\"name_bur\":\"\",\"name_zh_TW\":\"\",\"name_lo\":\"\",\"shortName_pl\":\"\",\"name_ja\":\"\",\"name_km\":\"\",\"name_fr\":\"\",\"shortName_tl\":\"\",\"shortName_fr\":\"\",\"name_tl\":\"\",\"name_it\":\"\",\"shortName_de\":\"\",\"shortName_en_US\":\"\",\"name_pl\":\"\",\"shortName_pt\":\"\",\"name_ko\":\"\",\"shortName_lo\":\"\",\"shortName_ms\":\"\",\"name_tr\":\"\",\"name_es\":\"\",\"name_bn\":\"\",\"shortName_th\":\"\",\"name_th\":\"\",\"name_ms\":\"\",\"name_vi\":\"\",\"shortName_bur\":\"\",\"name_pt\":\"\",\"shortName_vi\":\"\",\"shortName_in\":\"\",\"shortName_srp\":\"\",\"shortName_es\":\"\",\"shortName_ja\":\"\"},\"version\":2},\"positionDto\":{\"status\":null,\"isDelete\":0,\"setID\":null,\"version\":0},\"reportings\":[]}]}";
|
||||
|
||||
BeisenStaffDto beisenStaffDto = new BeisenStaffDto();
|
||||
|
||||
if(StringUtils.isNotBlank(bodyData)){
|
||||
JSONObject bodyJson = new JSONObject(bodyData);
|
||||
if(bodyJson.containsKey("code")){
|
||||
String code = bodyJson.getStr("code");
|
||||
System.out.println("code:{}"+code);
|
||||
if("200".equals(code)){
|
||||
JSONArray itemsArray = bodyJson.getJSONArray("items");
|
||||
System.out.println("itemsArray:{}"+itemsArray.size());
|
||||
if(!itemsArray.isEmpty()){
|
||||
|
||||
JSONObject itemObject = itemsArray.getJSONObject(0);
|
||||
System.out.println(("itemObject:{}"+itemObject.size()));
|
||||
|
||||
if(itemObject.containsKey("staffDto")){
|
||||
JSONObject staffDto = itemObject.getJSONObject("staffDto");
|
||||
System.out.println("staffDto:{}"+staffDto.size());
|
||||
beisenStaffDto.setDepartmentId(staffDto.getStr("departmentId"));
|
||||
beisenStaffDto.setDepartmentName(staffDto.getStr("departmentName"));
|
||||
String employedDate = staffDto.getStr("employedDate");
|
||||
System.out.println("employedDate:{}"+employedDate);
|
||||
|
||||
if(employedDate !=null && !"".equals(employedDate) && !"null".equals(employedDate)){
|
||||
if(employedDate.contains("T")){
|
||||
employedDate = employedDate.substring(0,employedDate.indexOf("T"));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("employedDate:{}"+employedDate);
|
||||
|
||||
beisenStaffDto.setEmployedDate(employedDate);
|
||||
|
||||
beisenStaffDto.setJobCode(staffDto.getStr("jobCode"));
|
||||
beisenStaffDto.setPositionName(staffDto.getStr("positionName"));
|
||||
beisenStaffDto.setLineManagerId(staffDto.getStr("lineManagerId"));
|
||||
beisenStaffDto.setStaffCode(staffDto.getStr("staffCode"));
|
||||
beisenStaffDto.setStaffStatus(staffDto.getStr("staffStatus"));
|
||||
|
||||
System.out.println("staffStatus:{}"+staffDto.getStr("staffStatus"));
|
||||
|
||||
beisenStaffDto.setIsDelete(staffDto.getStr("isDelete"));
|
||||
// beisenStaffDto.setUserId(staffDto.getStr("userId"));
|
||||
beisenStaffDto.setTenantId(staffDto.getStr("tenantId"));
|
||||
beisenStaffDto.setEmail(staffDto.getStr("email"));
|
||||
beisenStaffDto.setUserType(staffDto.getStr("userType"));
|
||||
beisenStaffDto.setUserStatus(staffDto.getStr("userStatus"));
|
||||
System.out.println("userStatus:{}"+staffDto.getStr("userStatus"));
|
||||
beisenStaffDto.setOrigin(staffDto.getStr("origin"));
|
||||
beisenStaffDto.setOriginalId(staffDto.getStr("originalId"));
|
||||
beisenStaffDto.setName(staffDto.getStr("name"));
|
||||
beisenStaffDto.setEnglishName(staffDto.getStr("englishName"));
|
||||
beisenStaffDto.setSex(staffDto.getStr("sex"));
|
||||
String birthday = staffDto.getStr("birthday");
|
||||
System.out.println("birthday:{}"+staffDto.getStr("birthday"));
|
||||
|
||||
if(!"null".equals(birthday) && birthday !=null ){
|
||||
if(birthday.contains("T")){
|
||||
birthday = birthday.substring(0,birthday.indexOf("T"));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("birthday:{}"+staffDto.getStr("birthday"));
|
||||
beisenStaffDto.setBirthday(birthday);
|
||||
beisenStaffDto.setMobile(staffDto.getStr("mobile"));
|
||||
beisenStaffDto.setIdCardType(staffDto.getStr("idCardType"));
|
||||
|
||||
String graduateDate = staffDto.getStr("graduateDate");
|
||||
|
||||
if(!"null".equals(graduateDate) && graduateDate !=null ){
|
||||
if(graduateDate.contains("T")){
|
||||
graduateDate = graduateDate.substring(0,graduateDate.indexOf("T"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
System.out.println("graduateDate:{}"+graduateDate);
|
||||
beisenStaffDto.setGraduateDate(graduateDate);
|
||||
|
||||
beisenStaffDto.setNativePlace(staffDto.getStr("nativePlace"));
|
||||
String beganWorkDate = staffDto.getStr("beganWorkDate");
|
||||
if(!"null".equals(beganWorkDate) && beganWorkDate !=null ){
|
||||
if(beganWorkDate.contains("T")){
|
||||
beganWorkDate = beganWorkDate.substring(0,beganWorkDate.indexOf("T"));
|
||||
}
|
||||
}
|
||||
System.out.println("graduateDate:{}"+graduateDate);
|
||||
beisenStaffDto.setBeganWorkDate(beganWorkDate);
|
||||
beisenStaffDto.setGraduateFrom(staffDto.getStr("graduateFrom"));
|
||||
beisenStaffDto.setMajor(staffDto.getStr("major"));
|
||||
beisenStaffDto.setPositionCategory(staffDto.getStr("positionCategory"));
|
||||
}
|
||||
|
||||
BeisenStaffDepartmentDto beisenStaffDepartmentDto = new BeisenStaffDepartmentDto();
|
||||
if(itemObject.containsKey("departmentDto")){
|
||||
JSONObject departmentDto = itemObject.getJSONObject("departmentDto");
|
||||
beisenStaffDepartmentDto.setId(departmentDto.getStr("id"));
|
||||
beisenStaffDepartmentDto.setName(departmentDto.getStr("name"));
|
||||
beisenStaffDepartmentDto.setCode(departmentDto.getStr("code"));
|
||||
beisenStaffDepartmentDto.setAbbreviation(departmentDto.getStr("abbreviation"));
|
||||
beisenStaffDepartmentDto.setParentId(departmentDto.getStr("parentId"));
|
||||
beisenStaffDepartmentDto.setLevel(departmentDto.getStr("level"));
|
||||
beisenStaffDepartmentDto.setStatus(departmentDto.getStr("status"));
|
||||
beisenStaffDepartmentDto.setIsDelete(departmentDto.getStr("isDelete"));
|
||||
beisenStaffDepartmentDto.setOriginalId(departmentDto.getStr("originalId"));
|
||||
}
|
||||
beisenStaffDto.setBeisenStaffDepartmentDto(beisenStaffDepartmentDto);
|
||||
|
||||
BeisenStaffPositionDto beisenStaffPositionDto = new BeisenStaffPositionDto();
|
||||
if(itemObject.containsKey("positionDto")){
|
||||
JSONObject positionDto = itemObject.getJSONObject("positionDto");
|
||||
|
||||
beisenStaffPositionDto.setId(positionDto.getStr("id"));
|
||||
beisenStaffPositionDto.setName(positionDto.getStr("name"));
|
||||
beisenStaffPositionDto.setCode(positionDto.getStr("code"));
|
||||
beisenStaffPositionDto.setStatus(positionDto.getStr("status"));
|
||||
beisenStaffPositionDto.setIsDelete(positionDto.getStr("isDelete"));
|
||||
}
|
||||
beisenStaffDto.setBeisenStaffPositionDto(beisenStaffPositionDto);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,44 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import okhttp3.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class main899 {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
OkHttpClient client = new OkHttpClient().newBuilder()
|
||||
.build();
|
||||
MediaType mediaType = MediaType.parse("application/json");
|
||||
|
||||
JSONObject dataJson = new JSONObject();
|
||||
dataJson.put("departmentId",2335561);
|
||||
dataJson.put("kind",1);
|
||||
dataJson.put("requirementType",2);
|
||||
dataJson.put("isSecrecy",false);
|
||||
dataJson.put("arivalTime","2025-07-17T00:00:00");
|
||||
dataJson.put("createBy",402189433);
|
||||
dataJson.put("educationInfo","2");
|
||||
dataJson.put("requirementCount",2);
|
||||
dataJson.put("name","HR001-招聘需求申请流程-sysadmin-2025-07-08");
|
||||
dataJson.put("category",2);
|
||||
dataJson.put("requirementStatus",10);
|
||||
dataJson.put("createDate","2025-07-08T00:00:00");
|
||||
|
||||
//"\n{\n\n\"departmentId\":2335561,\n \"kind\": 1,\n \"requirementType\": 2,\n \"isSecrecy\": false,\n \"arivalTime\": \"2025-07-17T00:00:00\",\n \"createBy\": 402189433,\n \"educationInfo\": \"2\",\n \"requirementCount\": 2,\n \"name\": \"HR001-招聘需求申请流程-sysadmin-2025-07-08\",\n \"category\": 2,\n \"requirementStatus\": 10,\n \"createDate\": \"2025-07-08T00:00:00\"\n}\n"
|
||||
|
||||
RequestBody body = RequestBody.create(mediaType, dataJson.toJSONString());
|
||||
Request request = new Request.Builder()
|
||||
.url("https://openapi.italent.cn/RecruitV6/api/v1/Requirement/CreateRequirement")
|
||||
.method("POST", body)
|
||||
.addHeader("Authorization", "Bearer X4eTEiMr-9cg3Du4KXRjpkoQda4-74c-5YxSrRDsakpp1pyZyn5zhFESSuTKAc793LcZeDKpX")
|
||||
.addHeader("Content-Type", "application/json")
|
||||
.build();
|
||||
Response response = client.newCall(request).execute();
|
||||
int code = response.code();
|
||||
String bodyData = response.body().string();
|
||||
System.out.println("code:"+code);
|
||||
System.out.println("bodyData:"+bodyData);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class mainTest2 {
|
||||
public static void main(String[] args) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
System.out.println("uid:"+uuid);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class test7 {
|
||||
public static void main(String[] args) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
System.out.println("uid:"+uuid);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
|
||||
import com.lsy.baselib.crypto.util.Base64;
|
||||
import com.lsy.baselib.crypto.util.CryptUtil;
|
||||
import com.lsy.baselib.crypto.util.FileUtil;
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.PrivateKey;
|
||||
|
||||
public class test8 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// String hiredate = "2024-08-09 00:00:00";
|
||||
// if(StringUtils.isNotBlank(hiredate)){
|
||||
// hiredate = hiredate.substring(0,10);
|
||||
// }
|
||||
// System.out.println(hiredate);
|
||||
// System.out.println(hiredate);
|
||||
//
|
||||
// String lzrq = "2025-08-09";
|
||||
// String lznf = "2025";
|
||||
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
//
|
||||
// LocalDate rzDate = LocalDate.parse(lznf+"-01-01", formatter);
|
||||
// LocalDate lzDate = LocalDate.parse(lzrq, formatter);
|
||||
// long workDays = ChronoUnit.DAYS.between(rzDate,lzDate);
|
||||
// System.out.println(workDays);
|
||||
//
|
||||
|
||||
// String jsonStr = "{\"templateId\": \"JMHT-ZXSJ\"}";
|
||||
// try {
|
||||
// String secret = "7f067a08f5c675137e6e72aa298e2c07";
|
||||
// String processed = jsonStr
|
||||
// .replaceAll("\\\\.", Matcher.quoteReplacement("$0"));
|
||||
//
|
||||
// System.out.println(processed);
|
||||
// Mac sha256 = Mac.getInstance("HmacSHA256");
|
||||
// sha256.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));
|
||||
// byte[] hash = sha256.doFinal(processed.getBytes());
|
||||
// String data = Hex.encodeHexString(hash);
|
||||
// System.out.println(data);
|
||||
// } catch (Exception e) {
|
||||
// throw new RuntimeException("加密失败", e);
|
||||
// }
|
||||
|
||||
// String date ="2025-06-10";
|
||||
// System.out.println(date.length());
|
||||
// String uuid = UUID.randomUUID().toString();
|
||||
// System.out.println(uuid);
|
||||
//
|
||||
// String message = "{\"code\":0,\"data\":{\"calendars\":[{\"calendar\":{\"calendar_id\":\"feishu.cn_CyZB7DD34hJrcBwosRTtDf@group.calendar.feishu.cn\",\"color\":-11034625,\"description\":\"\",\"permissions\":\"private\",\"role\":\"owner\",\"summary\":\"聚才林HR\",\"summary_alias\":\"\",\"type\":\"primary\"},\"user_id\":\"ou_f102af8c3620c64b37077cc949bcc8fe\"}]},\"msg\":\"success\"}";
|
||||
// if(StringUtils.isNotBlank(message)){
|
||||
// JSONObject returnData = JSONObject.parseObject(message);
|
||||
// if(returnData.containsKey("code")){
|
||||
// String code = returnData.getString("code");
|
||||
// if("0".equals(code)){
|
||||
// JSONObject dataJson = returnData.getJSONObject("data");
|
||||
// JSONArray calendarsArray = dataJson.getJSONArray("calendars");
|
||||
// for(int i=0;i<calendarsArray.size();i++){
|
||||
// JSONObject calendarJson = calendarsArray.getJSONObject(i);
|
||||
// System.out.println(calendarJson.toJSONString());
|
||||
//
|
||||
// JSONObject calendarData = calendarJson.getJSONObject("calendar");
|
||||
//
|
||||
// String type = calendarData.getString("type");
|
||||
// System.out.println(type);
|
||||
// if("primary".equals(type)){
|
||||
// String calendar_id = calendarData.getString("calendar_id");
|
||||
// System.out.println(calendar_id);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// String keyfile = test8.class.getClassLoader().getResource("signkey/server_sign.key").getPath();
|
||||
// System.out.println(keyfile);
|
||||
//// byte[] base64EncodedPrivatekey = FileUtil.read4file(keyfile);
|
||||
//
|
||||
// byte[] base64EncodedPrivatekey = read4file(keyfile);
|
||||
//
|
||||
// //私钥密码文件路径
|
||||
// String pwdfile = test8.class.getClassLoader().getResource("signkey/server_sign.pwd")
|
||||
// .getPath();
|
||||
// byte[] base64EncodedPrivatekeyPass = read4file(pwdfile);
|
||||
//
|
||||
// char[] keyPassword = new char[0];
|
||||
// try {
|
||||
// keyPassword = new String(base64EncodedPrivatekeyPass, "UTF-8").toCharArray();
|
||||
// } catch (UnsupportedEncodingException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
//
|
||||
// PrivateKey signerPrivatekey = CryptUtil.decryptPrivateKey(Base64.decode(base64EncodedPrivatekey), keyPassword);
|
||||
|
||||
|
||||
// Path path = Paths.get(keyfile);
|
||||
// byte[] data = new byte[0];
|
||||
// try {
|
||||
// data = Files.readAllBytes(path);
|
||||
// } catch (IOException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
// try {
|
||||
// String result = new String(data, "utf-8");
|
||||
// System.out.println(result);
|
||||
// } catch (UnsupportedEncodingException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
|
||||
System.out.println(System.currentTimeMillis()+"");
|
||||
|
||||
}
|
||||
|
||||
private PrivateKey getPrivateKey() throws Exception {
|
||||
//私钥文件路径
|
||||
String keyfile = test8.class.getClassLoader().getResource("signkey/server_sign.key")
|
||||
.getPath();
|
||||
byte[] base64EncodedPrivatekey = FileUtil.read4file(keyfile);
|
||||
|
||||
//私钥密码文件路径
|
||||
String pwdfile = test8.class.getClassLoader().getResource("signkey/server_sign.pwd")
|
||||
.getPath();
|
||||
byte[] base64EncodedPrivatekeyPass = FileUtil.read4file(pwdfile);
|
||||
|
||||
char[] keyPassword = new String(base64EncodedPrivatekeyPass, "UTF-8").toCharArray();
|
||||
|
||||
PrivateKey signerPrivatekey = CryptUtil.decryptPrivateKey(
|
||||
Base64.decode(base64EncodedPrivatekey), keyPassword);
|
||||
return signerPrivatekey;
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
package com.weaver.seconddev.chapanda.test;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
public class test9 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
// 密钥(在CryptoJS中通常称为secret key)
|
||||
String secretKey = "7f067a08f5c675137e6e72aa298e2c07"; // 替换为你的密钥
|
||||
// 要签名的数据
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("templateId","JMHT-ZXSJ");
|
||||
|
||||
// String data = jsonObject.toJSONString();
|
||||
// data = data.replaceAll("\\\\.", Matcher.quoteReplacement("$0"));
|
||||
// System.out.println(data);
|
||||
|
||||
String data = "{\"templateId\":\"JMHT-ZXSJ\"}" ;
|
||||
// 初始化Mac对象
|
||||
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
|
||||
sha256Hmac.init(secretKeySpec);
|
||||
|
||||
// 执行HmacSHA256操作
|
||||
byte[] result = sha256Hmac.doFinal(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
String data99 = bytesToHex(result);
|
||||
System.out.println("HMAC-data99: " + data99);
|
||||
// 将结果转换为Base64编码的字符串(与CryptoJS输出的格式一致)
|
||||
String hmacResult = Base64.getEncoder().encodeToString(result);
|
||||
|
||||
String data2 = Hex.encodeHexString(result);
|
||||
|
||||
String hash = Base64.getEncoder().encodeToString(result);
|
||||
|
||||
String hash2 = Base64.getUrlEncoder().withoutPadding().encodeToString(result);
|
||||
|
||||
StringBuilder hexSignature = new StringBuilder();
|
||||
for (byte b : result) {
|
||||
String hex = Integer.toHexString(b & 0xFF);
|
||||
if (hex.length() == 1) {
|
||||
hexSignature.append("0");
|
||||
}
|
||||
hexSignature.append(hex);
|
||||
}
|
||||
System.out.println("HMAC-SHA256签名: " + hexSignature.toString());
|
||||
|
||||
|
||||
System.out.println("HMAC SHA256 Result: " + hmacResult);
|
||||
System.out.println("HMAC SHA256 Result2: " + data2);
|
||||
System.out.println("HMAC SHA256 hash: " + hash);
|
||||
System.out.println("HMAC SHA256 hash2: " + hash2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
result.append(String.format("%02x", b));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue