diff --git a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/constant/YiliWpsConst.java b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/constant/YiliWpsConst.java new file mode 100644 index 00000000..f44c3f52 --- /dev/null +++ b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/constant/YiliWpsConst.java @@ -0,0 +1,28 @@ +package com.actionsoft.apps.coe.pal.constant; + +import com.actionsoft.sdk.local.SDK; + +public class YiliWpsConst { + public static final String APPID = "com.awspaas.user.apps.yiliwps"; + public static final String FILE_APPID = "com.actionsoft.apps.coe.pal"; + public static final String COE_UPFILE = "COE_Upfile"; + public static final String HOST = SDK.getAppAPI().getProperty(APPID,"host_config"); + public static final String CONTENT_TYPE = "application/json"; + public static final String AK = SDK.getAppAPI().getProperty(APPID,"AK"); + public static final String SK = SDK.getAppAPI().getProperty(APPID,"SK"); + + public static final String WPS_FILETYPE_W="w"; + public static final String WPS_FILETYPE_S="s"; + public static final String WPS_FILETYPE_P="p"; + public static final String WPS_FILETYPE_F="f"; + public static final String SUPPORTTYPE_W = "doc, dot, wps, wpt, docx, dotx, docm, dotm"; + public static final String SUPPORTTYPE_S = "xls, xlt, et, xlsx, xltx, csv, xlsm, xltm"; + public static final String SUPPORTTYPE_P = "ppt,pptx,pptm,ppsx,ppsm,pps,potx,potm,dpt,dps"; + public static final String SUPPORTTYPE_F = "pdf"; + + //bo相关 + public static final String BO_EU_SYSTEM_DEMO_FILE = "BO_EU_SYSTEM_DEMO_FILE"; + public static final String APP_ACT_COE_PAL_UPFILE = "APP_ACT_COE_PAL_UPFILE"; + + +} diff --git a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/EncryptionUtil.java b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/EncryptionUtil.java new file mode 100644 index 00000000..2f00289a --- /dev/null +++ b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/EncryptionUtil.java @@ -0,0 +1,268 @@ +package com.actionsoft.apps.coe.pal.util; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class EncryptionUtil { + + /** + * 加密算法 + */ + private static final String ENCRY_ALGORITHM = "AES"; + + /** + * 加密算法/加密模式/填充类型 + * 本例采用AES加密,ECB加密模式,PKCS5Padding填充 + */ + private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding"; + + + public static String md5(String plainText) { + byte[] secretBytes = null; + try { + secretBytes = MessageDigest.getInstance("md5").digest( + plainText.getBytes()); + } catch (NoSuchAlgorithmException e) { + return null; + } + String md5code = new BigInteger(1, secretBytes).toString(16); + for (int i = 0; i < 32 - md5code.length(); i++) { + md5code = "0" + md5code; + } + return md5code; + } + + public static String HMACSHA256(String data, String key) throws Exception { + Mac sha256HMAC = Mac.getInstance("HmacSHA256"); + SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + sha256HMAC.init(secret_key); + byte[] array = sha256HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for (byte item : array) { + sb.append(Integer.toHexString((item & 0xFF) | + 0x100).substring(1, 3)); + } + return sb.toString(); + } + + /** + * 利用java原生的摘要实现SHA256加密 + * + * @param str 加密后的报文 + * @return + */ + public static String getSHA256StrJava(byte[] str) { + MessageDigest messageDigest; + String encodeStr = ""; + try { + messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str); + encodeStr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return encodeStr; + } + + /** + * 将 + * byte转为16进制 + * + * @param bytes + * @return + */ + 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] & 0xFF); + if (temp.length() == 1) { + //1得到一位的进行补0操作 + stringBuffer.append("0"); + } + stringBuffer.append(temp); + } + return stringBuffer.toString(); + } + + + /** + * 设置iv偏移量 + * 本例采用ECB加密模式,不需要设置iv偏移量 + */ + private static final String IV_ = null; + + /** + * 设置加密字符集 + * 本例采用 UTF-8 字符集 + */ + private static final String CHARACTER = "UTF-8"; + + /** + * 设置加密密码处理长度。 + * 不足此长度补0; + */ + private static final int PWD_SIZE = 16; + + /** + * 密码处理方法 + * 如果加解密出问题, + * 请先查看本方法,排除密码长度不足填充0字节,导致密码不一致 + * @param password 待处理的密码 + * @return + * @throws UnsupportedEncodingException + */ + private static byte[] pwdHandler(String password) throws UnsupportedEncodingException { + byte[] data = null; + if (password != null) { + byte[] bytes = password.getBytes(CHARACTER); + if (password.length() < PWD_SIZE) { + System.arraycopy(bytes, 0, data = new byte[PWD_SIZE], 0, bytes.length); + } else { + data = bytes; + } + } + return data; + } + + //======================>原始加密<====================== + + /** + * 原始加密 + * @param clearTextBytes 明文字节数组,待加密的字节数组 + * @param pwdBytes 加密密码字节数组 + * @return 返回加密后的密文字节数组,加密错误返回null + */ + public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) { + try { + // 1 获取加密密钥 + SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM); + + // 2 获取Cipher实例 + Cipher cipher = Cipher.getInstance(CIPHER_MODE); + + // 查看数据块位数 默认为16(byte) * 8 =128 bit +// System.out.println("数据块位数(byte):" + cipher.getBlockSize()); + + // 3 初始化Cipher实例。设置执行模式以及加密密钥 + cipher.init(Cipher.ENCRYPT_MODE, keySpec); + + // 4 执行 + byte[] cipherTextBytes = cipher.doFinal(clearTextBytes); + + // 5 返回密文字符集 + return cipherTextBytes; + + }catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 原始解密 + * @param cipherTextBytes 密文字节数组,待解密的字节数组 + * @param pwdBytes 解密密码字节数组 + * @return 返回解密后的明文字节数组,解密错误返回null + */ + public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) { + + try { + // 1 获取解密密钥 + SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM); + + // 2 获取Cipher实例 + Cipher cipher = Cipher.getInstance(CIPHER_MODE); + + // 查看数据块位数 默认为16(byte) * 8 =128 bit +// System.out.println("数据块位数(byte):" + cipher.getBlockSize()); + + // 3 初始化Cipher实例。设置执行模式以及加密密钥 + cipher.init(Cipher.DECRYPT_MODE, keySpec); + + // 4 执行 + byte[] clearTextBytes = cipher.doFinal(cipherTextBytes); + + // 5 返回明文字符集 + return clearTextBytes; + + } catch (Exception e) { + e.printStackTrace(); + } + // 解密错误 返回null + return null; + } + + //======================>BASE64<====================== + + /** + * BASE64加密 + * @param clearText 明文,待加密的内容 + * @param password 密码,加密的密码 + * @return 返回密文,加密后得到的内容。加密错误返回null + */ + public static String aesEncryptBase64(String clearText, String password) { + try { + // 1 获取加密密文字节数组 + byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password)); + + // 2 对密文字节数组进行BASE64 encoder 得到 BASE6输出的密文 + BASE64Encoder base64Encoder = new BASE64Encoder(); + + // 3 返回BASE64输出的密文 + return base64Encoder.encode(cipherTextBytes); + } catch (Exception e) { + e.printStackTrace(); + } + // 加密错误 返回null + return null; + } + + /** + * BASE64解密 + * @param cipherText 密文,带解密的内容 + * @param password 密码,解密的密码 + * @return 返回明文,解密后得到的内容。解密错误返回null + */ + public static String aesDecryptBase64(String cipherText, String password) { + try { + // 1 对 BASE64输出的密文进行BASE64 decodebuffer 得到密文字节数组 + BASE64Decoder base64Decoder = new BASE64Decoder(); + byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText); + + // 2 对密文字节数组进行解密 得到明文字节数组 + byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password)); + + // 3 根据 CHARACTER 转码,返回明文字符串 + return new String(clearTextBytes, CHARACTER); + } catch (Exception e) { + e.printStackTrace(); + } + // 解密错误返回null + return null; + } + + public static void main(String[] args) throws Exception { +// System.out.println(DigestUtils.sha256Hex("".getBytes())); +// String result = getSHA256StrJava("".getBytes()); +// System.out.println(result); +// String hamacstr = HMACSHA256("WPS-4POST/callback/path/demoapplication/jsonWed, 20 Apr 2022 01:33:07 GMTfc005f51a6e75586d2d5d078b657dxxxdf9c1dfa6a7c0c0ba38c715daeb6ede9","cc2e3878f68e003347da63f9dbaee5a8"); +// System.out.println(hamacstr); + + //1.输出设置为base64时 + String encryptedStr = aesEncryptBase64("123", "XDWe0nNGxTg2yD8Gb3uUapkoA8XtKvq3");//参数:明文,加密字符串 + System.out.println("加密后的base64字符串为:"+encryptedStr); + String decrypt = aesDecryptBase64(encryptedStr,"XDWe0nNGxTg2yD8Gb3uUapkoA8XtKvq3");//参数:密文,加密字符串 + System.out.println("解密后的字符串为:" + decrypt); + } +} + diff --git a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/HttpPostUtil.java b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/HttpPostUtil.java new file mode 100644 index 00000000..f0e8c78d --- /dev/null +++ b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/HttpPostUtil.java @@ -0,0 +1,305 @@ +package com.actionsoft.apps.coe.pal.util; + +import com.alibaba.fastjson.JSON; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.AuthSchemes; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.*; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.BasicHttpEntity; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Map; + +public class HttpPostUtil { + /** + * 下载请求 + * + * @param url + * @param headers + * @return + * @throws IOException + */ + public static void sendGetDownloadRequest(String url, Map headers,String savePath) throws IOException { + // 设置请求头 + HttpGet request = new HttpGet(url); + if (null != headers) { + for (Map.Entry entry : headers.entrySet()) { + request.addHeader(entry.getKey(), entry.getValue()); + } + } + + // 发送http请求 + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(request)) { + HttpEntity entity = response.getEntity(); + if (null != entity) { + InputStream in = entity.getContent(); + File file = new File(savePath);//这里为存储路径/xx/xx.. + FileOutputStream fout = new FileOutputStream(file); + int a = -1; + byte[] tmp = new byte[1024]; + while ((a = in.read(tmp)) != -1) { + fout.write(tmp, 0, a); + } + fout.flush(); + fout.close(); + in.close(); + httpClient.close(); + return; + } + throw new IOException("No response"); + } catch (IOException e) { + throw e; + } + } + /** + * 发送Get请求(如果https请求需要忽略证书检测,需自己实现) + * + * @param url + * @param headers + * @return + * @throws IOException + */ + public static String sendGetRequest(String url, Map headers) throws IOException { + // 设置请求头 + HttpGet request = new HttpGet(url); + if (null != headers) { + for (Map.Entry entry : headers.entrySet()) { + request.addHeader(entry.getKey(), entry.getValue()); + } + } + // 发送http请求 + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(request)) { + HttpEntity entity = response.getEntity(); + if (null != entity) { + String content = EntityUtils.toString(entity, StandardCharsets.UTF_8); + System.out.println(">>>输出"+content); + EntityUtils.consume(entity); // 关闭content stream + return content; + } + throw new IOException("No response"); + } catch (IOException e) { + throw e; + } + } + + /** + * 发送Get请求(如果https请求需要忽略证书检测,需自己实现) + */ + public static T sendPostRequest(String url, String body, Map headers,Class classes) throws IOException { + // 设置请求头 + HttpPost request = new HttpPost(url); + if (headers != null) { + for (Map.Entry entry : headers.entrySet()) { + request.addHeader(entry.getKey(), entry.getValue()); + } + } + // 设置请求body + if (body != null) { + request.setEntity(new StringEntity(body, StandardCharsets.UTF_8)); + } + try { + // 发送http请求 + CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(request); + HttpEntity entity = response.getEntity(); + if (null != entity) { + String content = EntityUtils.toString(entity); + httpClient.close(); + response.close(); + return JSON.parseObject(content,classes); + } + return null; + } catch (IOException e) { + throw e; + } + } + + /** + * 发送Put请求(如果https请求需要忽略证书检测,需自己实现) + * + * @param url + * @param headers + * @return + * @throws IOException + */ + public static CloseableHttpResponse sendPutRequest(String url, InputStream body, Map headers) throws IOException { + // 设置请求头 + HttpPut request = new HttpPut(url); + if (headers != null) { + for (Map.Entry entry : headers.entrySet()) { + request.addHeader(entry.getKey(), entry.getValue()); + } + } + // 设置请求body + if (body != null) { + InputStreamEntity entity = new InputStreamEntity(body); + entity.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString()); + request.setEntity(entity); + } + + // 发送http请求 + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + return httpClient.execute(request); + } catch (ClientProtocolException e) { + throw e; + } catch (IOException e) { + throw e; + } + } + + public static CloseableHttpResponse doPutUpload(String url, File file, Map headers) { + FileInputStream fileInputStream = null; + CloseableHttpResponse response = null; + try { + // file + fileInputStream = new FileInputStream(file); + + HttpPut httpput = new HttpPut(url); + addHeader(httpput, headers); + + BasicHttpEntity basicHttpEntity = new BasicHttpEntity(); + basicHttpEntity.setChunked(false); + basicHttpEntity.setContent(fileInputStream); + basicHttpEntity.setContentLength(file.length()); + + httpput.setEntity(basicHttpEntity); + response = executeRequest(url, httpput); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + }catch (Exception e1){ + e1.printStackTrace(); + } + } + } + return response; + } + private static void addHeader(HttpRequestBase httpRequestBase, Map header) { + if (header != null && !header.isEmpty()) { + for (Map.Entry entry : header.entrySet()) { + httpRequestBase.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + private static CloseableHttpResponse executeRequest(String url, HttpUriRequest request) throws Exception { + return getInstance(url).execute(request); + } + + private static CloseableHttpClient getInstance(String url) { + if (!StringUtils.isEmpty(url) && url.startsWith("https")) { + return sslClient(); + } else { + return HttpClients.createDefault(); + } + } + + private static CloseableHttpClient sslClient() { + try { + // 在调用SSL之前需要重写验证方法,取消检测SSL + X509TrustManager trustManager = new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(X509Certificate[] xcs, String str) { + } + + @Override + public void checkServerTrusted(X509Certificate[] xcs, String str) { + } + }; + SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS); + ctx.init(null, new TrustManager[]{trustManager}, null); + SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE); + // 创建Registry + RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT) + .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) + .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); + Registry socketFactoryRegistry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", socketFactory).build(); + // 创建ConnectionManager,添加Connection配置信息 + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager) + .setDefaultRequestConfig(requestConfig).build(); + return closeableHttpClient; + } catch (KeyManagementException ex) { + throw new RuntimeException(ex); + } catch (NoSuchAlgorithmException ex) { + throw new RuntimeException(ex); + } + } + + /** + * 发送Post请求(如果https请求需要忽略证书检测,需自己实现) + * + * @param url + * @param headers + * @return + * @throws IOException + */ + public static Pair sendPostRequest3(String url, String body, Map headers) throws IOException { + // 设置请求头 + HttpPost request = new HttpPost(url); + if (headers != null) { + for (Map.Entry entry : headers.entrySet()) { + request.addHeader(entry.getKey(), entry.getValue()); + } + } + // 设置请求body + if (body != null) { + request.setEntity(new StringEntity(body, StandardCharsets.UTF_8)); + } + + // 发送http请求 + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(request)) { + HttpEntity entity = response.getEntity(); + if (null != entity) { + String content = EntityUtils.toString(entity, StandardCharsets.UTF_8); + EntityUtils.consume(entity); // 关闭content stream + return Pair.of(response.getStatusLine(), content); + } + throw new IOException("No response"); + } catch (ClientProtocolException e) { + throw e; + } catch (IOException e) { + throw e; + } + } + +} diff --git a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/WPS4Util.java b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/WPS4Util.java new file mode 100644 index 00000000..cfc79e4e --- /dev/null +++ b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/WPS4Util.java @@ -0,0 +1,167 @@ +package com.actionsoft.apps.coe.pal.util; + +import com.actionsoft.sdk.local.SDK; +import com.actionsoft.sdk.local.api.LogAPI; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; + +import java.text.SimpleDateFormat; +import java.util.*; + +public class WPS4Util { + public final static LogAPI log =SDK.getLogAPI(); + public final static String HTTP_HEADER_WPS_DOCS_DATE = "Wps-Docs-Date"; + public final static String HTTP_HEADER_WPS_DOCS_AUTHORIZATION = "Wps-Docs-Authorization"; + public final static String HTTP_HEADER_CONTENT_TYPE = "Content-Type"; + public final static String WPS_SIGNATURE_VERSION = "WPS-4"; + + public final static String[] WORD_EXT = {"doc","dot","wps","wpt","docx","dotx","docm","dotm","rtf","txt"}; + public final static String[] EXCEL_EXT = {"xls","xlt","et","xlsx","xltx","xlsm","xltm","csv"}; + public final static String[] PPT_EXT = {"ppt","pptx","pptm","ppsx","ppsm","pps","potx","potm","dpt","dps"}; + public final static String[] PDF_EXT = {"pdf", "ofd"}; + + public final static String[] X_EXT = {"jpeg","jpg","png","gif","bmp","tif","tiff","svg","psd", + "tar","zip","7z","gz","rar", + "md", + "c","cpp","java","js","css","lrc","h","asm","s","asp","bat","bas","prg","cmd","xml"}; + private static String appId; // 应用id + private static String secretKey; // 应用秘钥 + + public static void initAppInfo(String appId, String secretKey) { + WPS4Util.appId = appId; + WPS4Util.secretKey = secretKey; + } + + /** + * 根据文件名,获取文件类型 + * @param filename 文件名 + * @return 文件类型 w p s f + */ + public static String getFileType(String filename){ + if(StringUtils.isEmpty(filename)){ + return null; + } + int index = filename.lastIndexOf('.'); + if (index == -1){ + return null; + } + String ext = filename.substring(index+1); + for (String element : WORD_EXT) { + if (StringUtils.equalsIgnoreCase(ext, element)) { + return "w"; + } + } + for (String item : EXCEL_EXT) { + if (StringUtils.equalsIgnoreCase(ext, item)) { + return "s"; + } + } + for (String value : PPT_EXT) { + if (StringUtils.equalsIgnoreCase(ext, value)) { + return "p"; + } + } + for (String s : PDF_EXT) { + if (StringUtils.equalsIgnoreCase(ext, s)) { + return "f"; + } + } + for (String s : X_EXT) { + if (StringUtils.equalsIgnoreCase(ext, s)) { + return "x"; + } + } + return null; + } + + /** + * 获取请求body MD5 + * @param content 请求body + * @return + */ + private static String getContentSha256(String content) { + if (StringUtils.isBlank(content)) { + return ""; + } else { + return DigestUtils.sha256Hex(content); + } + } + + /** + * 获取日期字符串 + * + * @param date + * @return + */ + private static String getGMTDateString(Date date) { + SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss [GMT]", Locale.US); + format.setTimeZone(TimeZone.getTimeZone("GMT")); + return format.format(date) + " GMT"; + } + + /** + * 获取WPS Authorization + * @param ver + * @param httpMethod + * @param uriWithQuerystring + * @param contentSha256 + * @param dateString + * @param contentType + * @return + */ + private static String getWpsAuthorization(String ver,String httpMethod,String uriWithQuerystring, String contentSha256, String dateString, String contentType) throws Exception { + String signatureStr = String.format("%s%s%s%s%s%s",ver,httpMethod, + uriWithQuerystring,contentType,dateString,contentSha256); + //log.info("要签名的值:{}",signatureStr); + return String.format("WPS-4 %s:%s",appId,EncryptionUtil.HMACSHA256(signatureStr,secretKey)); + } + + public static String getRfc1123Date() { + SimpleDateFormat sdf4 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); + sdf4.setTimeZone(TimeZone.getTimeZone("GMT")); + return sdf4.format(new Date()); + } + + + public static Map getSignatureHeaders(String uriWithQuerystring,String httpMethod, String content, String contentType) throws Exception { + if (uriWithQuerystring == null) { + uriWithQuerystring = ""; + } + if (contentType == null) { + contentType = "application/json"; + } + String contentSha256 = getContentSha256(content); + + String dateString = getRfc1123Date();//getGMTDateString(new Date()); + String authorization = getWpsAuthorization(WPS_SIGNATURE_VERSION,httpMethod, + uriWithQuerystring,contentSha256, dateString, contentType); + + Map headers = new HashMap<>(); + headers.put(WPS4Util.HTTP_HEADER_WPS_DOCS_AUTHORIZATION, authorization); + headers.put(WPS4Util.HTTP_HEADER_CONTENT_TYPE, contentType); + headers.put(WPS4Util.HTTP_HEADER_WPS_DOCS_DATE, dateString); + log.consoleInfo("签名结果: {} -> {}"+WPS4Util.HTTP_HEADER_WPS_DOCS_AUTHORIZATION+authorization); + //log.info("签名结果: {} -> {}",WPS4Util.HTTP_HEADER_CONTENT_TYPE,contentType); + //log.info("签名结果: {} -> {}",WPS4Util.HTTP_HEADER_WPS_DOCS_DATE,dateString); + return headers; + } + + public static void main(String[] args) throws Exception { + String contentType = "application/json"; + String uriWithQuerystring = "/api/edit/v1/files/1661841425405/link?type=w"; + String body = ""; + // 获取签名请求头 + String appId = "AKyAYlPgfRjnFBGV"; + String secretKey = "FPLVEBJfEsNVrBkBIShJAmwiufvJIqZy"; + WPS4Util.initAppInfo(appId, secretKey); + Map headers = WPS4Util.getSignatureHeaders(uriWithQuerystring, "GET",body, contentType); + for (Map.Entry entry : headers.entrySet()) { + System.out.println(entry.getKey() + " = " + entry.getValue()); + } + + SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); + format.setTimeZone(TimeZone.getTimeZone("GMT")); + System.out.println(format.format(new Date())); + } +} +