文旅相关逻辑集成

This commit is contained in:
2025-01-03 18:48:11 +08:00
parent 6dcc2800ae
commit 9037a8cbab
125 changed files with 2917 additions and 1616 deletions
@@ -16,4 +16,8 @@ public interface ServiceNameConstants {
* 搜索中心服务
*/
String SEARCH_SERVICE = "search-center";
String UAA_SERVICE = "uaa-center";
String DEVICE_SERVICE = "device-center";
}
@@ -0,0 +1,279 @@
package com.central.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* RSA加解密、创建与校验签名的工具类
*/
@Slf4j
public class RSAUtil {
public static final String PUBLIC_KEY = "PUBLIC_KEY";
public static final String PRIVATE_KEY = "PRIVATE_KEY";
private static final Base64.Encoder base64Encoder = Base64.getEncoder();
private static final Base64.Decoder base64Decoder = Base64.getDecoder();
private static final String ALGORITHM = "RSA/ECB/PKCS1Padding";
/**
* 签名算法
*/
private static final String SIGN_TYPE = "SHA1withRSA";
/**
* 密钥长度
*/
private static final Integer KEY_LENGTH = 1024;
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
public static PublicKey publicKey;
public static PrivateKey privateKey;
static {
Map<String, Key> map = null;
try {
map = genKeyPair();
publicKey = (PublicKey) map.get(PUBLIC_KEY);
privateKey = (PrivateKey) map.get(PRIVATE_KEY);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成秘钥对,公钥和私钥
*
* @return 秘钥键值对
* @throws Exception 创建秘钥对异常
*/
public static Map<String, Key> genKeyPair() throws Exception {
Map<String, Key> keyMap = new HashMap<>();
String pubKey =
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGu7lYGfEtMICO8kREJrObu0Hy" +
"pF7R9iEIefyxApmB6wJ/y3Rg/eBO6kLDCo18hYZ3ZNxKp5CMymZvXDh5j+sd7IHm" +
"tUh6sEZzpXExQJIzT8gA1SULd+iXe4V9zt2AcbROIi94vA6lOfmtON28Ex+uAlLK" +
"N/iJDXFFXdEOmfdqhwIDAQAB";
Base64.Decoder decoder = Base64.getDecoder();
byte[] keyBytes = decoder.decode(pubKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey publicKey = kf.generatePublic(spec);
String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIa7uVgZ8S0wgI7y" +
"REQms5u7QfKkXtH2IQh5/LECmYHrAn/LdGD94E7qQsMKjXyFhndk3EqnkIzKZm9c" +
"OHmP6x3sgea1SHqwRnOlcTFAkjNPyADVJQt36Jd7hX3O3YBxtE4iL3i8DqU5+a04" +
"3bwTH64CUso3+IkNcUVd0Q6Z92qHAgMBAAECgYAogZGkahA3DMjpsO5TKut+m1ql" +
"T0Nujje6K6qLsQNjqrrSnuE7M7hXIVi2+Jo24JHfnUQZca0klskbG7ei3GDL6eEb" +
"Qm3NlJ84bxDQUOy6SSiqZHYKP0Yvwgk3uR8OM6hjnv6c7b5HPlvp00DuMlwkw+ST" +
"Ng5ErJrgx6g7Dte1KQJBAN2Bp1HQ804cnqZyEfQLjx/uf1+BKGXsEjf25u5WZCZ5" +
"slxIbtkhtG61L4z7uOLxBKyixR37YvM94HNxLQ2+7E0CQQCbttyVTpnXRXrzhUT7" +
"W8ML8BE5jiCqbU/Y1VAm7Sp5D3SOLDbMZKG8lV6duUYSdoYY7ZrqO8qU6XWXbWxj" +
"r4wjAkA9lMobqOe7k6FXzObI3l3QFtI6jwHYNCVsgav6HvKA79xyY4DNxN0Q2jZ6" +
"D5F7Jl6SUD5U84qy7UT1U0WfSLERAkB3zv3v33dc/De60SqfYB41vDP0ndeiadMK" +
"2i3+lXKdjPe4QGq1XyRWjnMrVheFMy7AVWlhmjmn0+1HYskH9lUTAkBRlC0bbsMh" +
"ttwtWnWvTjgCynymlKYKmzakBllknkokCE3cjefS5BoG0yAavZUJ4bozaTBVRcs5" +
"JN1IsgxqgsOq";
byte[] decoded = decoder.decode(privateKey);
RSAPrivateKey rsaPrivateKey =
(RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, rsaPrivateKey);
return keyMap;
}
/**
* 公钥加密
*
* @param data 加密前数据
* @param publicKey 公钥
* @return 加密后数据
* @throws Exception 加密异常
*/
public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey) throws Exception {
// 加密数据,分段加密
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLength = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
while (inputLength - offset > 0) {
if (inputLength - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offset, inputLength - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
public static byte[] encryptByPublicKey(byte[] data, String publicKeyBase64Encoded) throws Exception {
return encryptByPublicKey(data, parseString2PublicKey(publicKeyBase64Encoded));
}
/**
* 私钥解密
*
* @param data 解密前数据
* @param privateKey 私钥
* @return 解密后数据
* @throws Exception 解密异常
*/
public static byte[] decryptByPrivateKey(byte[] data, PrivateKey privateKey) {
// 解密数据,分段解密
try{
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int inputLength = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
while (inputLength - offset > 0) {
if (inputLength - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offset, inputLength - offset);
}
out.write(cache);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}catch (Exception e){
log.info("解密异常:{}",e.getMessage());
e.printStackTrace();
return null;
}
}
public static byte[] decryptByPrivateKey(byte[] data, String privateKeyBase64Encoded) throws Exception {
return decryptByPrivateKey(data, parseString2PrivateKey(privateKeyBase64Encoded));
}
/**
* 创建签名
*
* @param source 要签名的信息
* @param privateKey 私钥
* @return 签名
* @throws Exception 签名异常
*/
public static byte[] createSign(String source, PrivateKey privateKey) throws Exception {
Signature signet = Signature.getInstance(SIGN_TYPE);
signet.initSign(privateKey);
signet.update(source.getBytes());
return signet.sign();
}
public static byte[] createSign(String source, String privateKeyBase64Encoded) throws Exception {
return createSign(source, parseString2PrivateKey(privateKeyBase64Encoded));
}
/**
* 校验签名
*
* @param expected 期望信息
* @param sign 签名
* @param publicKey 公钥
* @return 结果
* @throws Exception 校验异常
*/
public static boolean checkSign(String expected, byte[] sign, PublicKey publicKey) throws Exception {
Signature signetCheck = Signature.getInstance(SIGN_TYPE);
signetCheck.initVerify(publicKey);
signetCheck.update(expected.getBytes());
return signetCheck.verify(sign);
}
public static boolean checkSign(String expected, byte[] sign, String publicKeyBase64Encoded) throws Exception {
return checkSign(expected, sign, parseString2PublicKey(publicKeyBase64Encoded));
}
/**
* 将base64格式的公钥转换为对象
*
* @param publicKeyBase64Encoded base64的公钥
* @return 公钥
* @throws Exception 转换异常
*/
public static PublicKey parseString2PublicKey(String publicKeyBase64Encoded) throws Exception {
return KeyFactory.getInstance(ALGORITHM).generatePublic(
new X509EncodedKeySpec(base64Decoder.decode(publicKeyBase64Encoded)));
}
/**
* 将base64格式的私钥转换为对象
*
* @param privateKeyBase64Encoded base64的私钥
* @return 私钥
* @throws Exception 转换异常
*/
public static PrivateKey parseString2PrivateKey(String privateKeyBase64Encoded) throws Exception {
return KeyFactory.getInstance(ALGORITHM).generatePrivate(
new PKCS8EncodedKeySpec(base64Decoder.decode(privateKeyBase64Encoded)));
}
public static String getEncData(String data) throws Exception {
String enc = Base64.getEncoder().encodeToString(RSAUtil.encryptByPublicKey(data.getBytes(),
publicKey));
return StringUtils.replace(enc, "/", "%2F");
}
// 单个解密 私钥
public static String decryptOne(String des) {
String _imageName = StringUtils.replace(des, "%2F", "/");
try {
return new String(RSAUtil.decryptByPrivateKey(Base64.getDecoder().decode(_imageName), (PrivateKey) RSAUtil.genKeyPair().get(RSAUtil.PRIVATE_KEY)));
} catch (Exception e) {
log.info("解密异常:{}",e.getMessage());
e.printStackTrace();
return null;
}
}
// 单个加密 公钥加密
public static String encryptOne(String des) {
try {
return StringUtils.replace(Base64.getEncoder().encodeToString(RSAUtil.encryptByPublicKey(des.getBytes(), (PublicKey) RSAUtil.genKeyPair().get(RSAUtil.PUBLIC_KEY)))
, "/", "%2F");
} catch (Exception e) {
log.info("加密异常:{}",e.getMessage());
return null;
}
}
public static String getDecData(String data) throws Exception {
String replace = StringUtils.replace(data, "%2F", "/");
return new String(decryptByPrivateKey(Base64.getDecoder().decode(replace), privateKey));
}
public static void main(String[] args) {
System.out.println("公钥加密>>>>>>:" + encryptOne("慧谷测试"));
System.out.println("私钥解密>>>>>>:" + decryptOne("LBS9qzlDcBQeb+WLhGRKm5+zoQkPokrEdwejn1VZSmYPaLrAS2LUCbSHViZOfUcvql5j57dvMEXw5jhOu7775exptY%2FyHNTxld2PjmgTPg6If4EOFpD4z+YSuQQyTz4lWmKCQ7egP35qYvAyHUkG%2FyNEOSJUClQbrEfnj1OcL1s="));
}
}
@@ -0,0 +1,409 @@
package com.central.common.utils;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils extends org.apache.commons.lang.StringUtils {
static final String HEX_FORMAT = "%02x";
private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
public StringUtils() {
}
public static byte[] getBytes(String str) {
if (str != null) {
try {
return str.getBytes("UTF-8");
} catch (UnsupportedEncodingException var2) {
return null;
}
} else {
return null;
}
}
public static String toString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException var2) {
return "";
}
}
public static boolean inString(String str, String... strs) {
if (str != null) {
String[] var2 = strs;
int var3 = strs.length;
for(int var4 = 0; var4 < var3; ++var4) {
String s = var2[var4];
if (str.equals(trim(s))) {
return true;
}
}
}
return false;
}
public static String replaceHtml(String html) {
if (isBlank(html)) {
return "";
} else {
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}
}
public static String replaceMobileHtml(String html) {
return html == null ? "" : html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}
public static String toHtml(String txt) {
return txt == null ? "" : "";
}
public static String abbr(String str, int length) {
if (str == null) {
return "";
} else {
try {
StringBuilder sb = new StringBuilder();
int currentLength = 0;
char[] var4 = replaceHtml(StringEscapeUtils.unescapeHtml(str)).toCharArray();
int var5 = var4.length;
for(int var6 = 0; var6 < var5; ++var6) {
char c = var4[var6];
currentLength += String.valueOf(c).getBytes("GBK").length;
if (currentLength > length - 3) {
sb.append("...");
break;
}
sb.append(c);
}
return sb.toString();
} catch (UnsupportedEncodingException var8) {
logger.error("出现异常", var8);
return "";
}
}
}
public static String abbr2(String param, int length) {
if (param == null) {
return "";
} else {
StringBuffer result = new StringBuffer();
int n = 0;
boolean isCode = false;
boolean isHTML = false;
for(int i = 0; i < param.length(); ++i) {
char temp = param.charAt(i);
if (temp == '<') {
isCode = true;
} else if (temp == '&') {
isHTML = true;
} else if (temp == '>' && isCode) {
--n;
isCode = false;
} else if (temp == ';' && isHTML) {
isHTML = false;
}
try {
if (!isCode && !isHTML) {
n += String.valueOf(temp).getBytes("GBK").length;
}
} catch (UnsupportedEncodingException var12) {
logger.error("出现异常", var12);
}
if (n > length - 3) {
result.append("...");
break;
}
result.append(temp);
}
String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
temp_result = temp_result.replaceAll("</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", "");
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
Matcher m = p.matcher(temp_result);
ArrayList endHTML = new ArrayList();
while(m.find()) {
endHTML.add(m.group(1));
}
for(int i = endHTML.size() - 1; i >= 0; --i) {
result.append("</");
result.append((String)endHTML.get(i));
result.append(">");
}
return result.toString();
}
}
public static Double toDouble(Object val) {
if (val == null) {
return 0.0D;
} else {
try {
return Double.valueOf(trim(val.toString()));
} catch (Exception var2) {
return 0.0D;
}
}
}
public static Float toFloat(Object val) {
return toDouble(val).floatValue();
}
public static Long toLong(Object val) {
return toDouble(val).longValue();
}
public static Integer toInteger(Object val) {
return toLong(val).intValue();
}
public static boolean toBoolean(String val) {
return Boolean.parseBoolean(val);
}
public static String getMessage(String code, Object[] args) {
return "";
}
public static BigDecimal toBigDecimal(String str){
return new BigDecimal(str).setScale(7, BigDecimal.ROUND_HALF_UP);
}
public static String getRemoteAddr(HttpServletRequest request) {
String remoteAddr = request.getHeader("X-Real-IP");
if (isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("X-Forwarded-For");
} else if (isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("Proxy-Client-IP");
} else if (isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
}
return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
}
public static String toCamelCase(String s) {
if (s == null) {
return null;
} else {
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for(int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '_') {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
}
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
return null;
} else {
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
public static String toUnderScoreCase(String s) {
if (s == null) {
return null;
} else {
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for(int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < s.length() - 1) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if (i > 0 && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append('_');
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
}
public static String jsGetVal(String objectString) {
StringBuilder result = new StringBuilder();
StringBuilder val = new StringBuilder();
String[] vals = split(objectString, ".");
for(int i = 0; i < vals.length; ++i) {
val.append("." + vals[i]);
result.append("!" + val.substring(1) + "?'':");
}
result.append(val.substring(1));
return result.toString();
}
public static String string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for(int i = 0; i < string.length(); ++i) {
char c = string.charAt(i);
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for(int i = 1; i < hex.length; ++i) {
int data = Integer.parseInt(hex[i], 16);
string.append((char)data);
}
return string.toString();
}
public static String lengthFix(String text, int length, char ch, boolean end) {
if (text == null) {
text = "";
}
int tempLength = text.getBytes().length;
if (length == tempLength) {
return text;
} else if (length <= tempLength) {
return end ? new String(text.getBytes(), 0, length) : new String(text.getBytes(), tempLength - length, length);
} else {
char[] fix = new char[length - tempLength];
for(int i = 0; i < fix.length; ++i) {
fix[i] = ch;
}
StringBuffer buffer = new StringBuffer(text);
if (end) {
buffer = buffer.append(fix);
} else {
buffer = buffer.insert(0, fix);
}
return buffer.toString();
}
}
public static String lengthFix(String text, int length, String ch, boolean end) {
return lengthFix(text, length, ch.charAt(0), end);
}
public static String bytesToHexStr(byte[] b) {
return bytesToHexStr(b, 0, b.length);
}
public static String bytesToHexStr(byte[] b, int start, int len) {
if (start < b.length && b != null && b.length != 0) {
StringBuffer str = new StringBuffer();
for(int i = start; i < start + len; ++i) {
str.append(String.format("%02x", b[i]));
}
return str.toString();
} else {
return "";
}
}
public static byte[] hexStrToBytes(String str) {
if (str.length() % 2 != 0) {
str = "0" + str;
}
byte[] temp = new byte[str.length() / 2];
for(int i = 0; i < str.length(); i += 2) {
temp[i / 2] = (byte)(Byte.parseByte(str.substring(i, i + 1), 16) * 16 + Byte.parseByte(str.substring(i + 1, i + 2), 16));
}
return temp;
}
public static void hexStrToBytes(String str, byte[] b, int from) {
if (str.length() % 2 != 0) {
str = "0" + str;
}
hexStrToBytes(str, b, from, str.length() / 2);
}
public static void hexStrToBytes(String str, byte[] b, int from, int length) {
if (str.length() % 2 != 0) {
str = "0" + str;
}
for(int i = 0; i < Math.min(str.length(), length * 2) && from + i / 2 < b.length; i += 2) {
b[from + i / 2] = (byte)(Byte.parseByte(str.substring(i, i + 1), 16) * 16 + Byte.parseByte(str.substring(i + 1, i + 2), 16));
}
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}