1. 数组&集合转逗号分割
public static void main(String[] args) {
String[] array = {"张三", "李四", "王五", "撒娇", "九点十几分", "没事", "圣诞节"};
String join = StringUtils.join(array, ",");
System.out.println(join);
// 集合
List<Integer> strings = Arrays.asList(array);
StringUtils.join(strings,",");
}
2. List转数组
List<XqqComplain> list = xqqComplainService.selectXqqComplainList(xqqComplain);
Long[] longs = list.stream().map(XqqComplain::getPostsId).toArray(Long[]::new);
3. 数组转集合
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5, 6};
List<Integer> strings = Arrays.asList(array);
}
4. 数组排序
public static void main(String[] args) {
Integer[] array = {1, 4, 5, 7, 9, 6};
List<Integer> strings = Arrays.asList(array);
// 默认顺序1->6
System.out.println(JSON.toJSONString(strings.stream().sorted().collect(Collectors.toList())));
// 逆序6->1
System.out.println(JSON.toJSONString(strings.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList())));
System.out.println(JSON.toJSONString(strings.stream().sorted(Integer::compareTo).collect(Collectors.toList())));
}
5. RSA 加&验签
什么是RSA加密?
RSA加密是一种非对称加密算法,RSA加密算法包括公钥和私钥两部分,公钥用于加密数据,私钥用于解密数据。公钥可以公开给任何人使用,而私钥必须严密保管,不对外公开。
5.1. 生成公私钥
## 生成私钥
openssl genrsa -out private.pem 2048
## 生成公钥
openssl rsa -in private.pem -pubout -out public.pem
## 私钥转成PKCS8格式的密钥
openssl pkcs8 -topk8 -inform PEM -in private.pem -out private_pkcs8.pem -nocrypt
5.2. 加签&验签
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
public class Demo {
/**
* name and value separator
*/
private static final String NAME_VALUE_SEPARATOR = "=";
/**
* comma
*/
private static final String COMMA = ",";
/**
* algorithm
*/
private static final String ALGORITHM = "algorithm";
/**
* signature
*/
private static final String SIGNATURE = "signature";
/**
* keyVersion
*/
private static final String KEY_VERSION = "keyVersion";
/**
* RSA256
*/
private static final String RSA_256 = "RSA256";
private static String genRequestTime() {
OffsetDateTime offsetDateTime = OffsetDateTime.now();
// 定义日期时间格式化器
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
// 格式化日期时间
String formattedDateTime = offsetDateTime.format(formatter);
return formattedDateTime;
}
public static void main(String[] args) throws Exception {
String httpMethod = "POST";
String uriWithQueryString = "/createPayout";
String clientId = "123456";
String timeString = "2023-09-14T10:49:47.231+08:00";
String content = "{"transferRequestId":"ae-payment-test-12345678","transferFromDetail":{"transferFromAmount":{"currency":"USD","value":12255},"
+ ""transferFromMethod":{"paymentMethodType":"BALANCE","customerId":"2121120024412736"}},"transferToDetail":{"transferToAmount":{"currency":"USD"},"
+ ""transferToMethod":{"paymentMethodType":"BANK_ACCOUNT_DETAIL","paymentMethodMetaData":{"bankAccountNo":"4442340002","beneficiaryAddress":"bene "
+ "address","routingNumber":"071006651","bankName":"bank test name","bankCountryCode":"US","bankAccountName":"english name"}},"
+ ""transferMemo":"test memo","transferRemark":"test remark","transferNotifyUrl":"https://sit-aepay-finnet-sg-b10.aliexpress.com/callback/B10_SG_001/ipay"
+ ".account.payoutNotification/ip_33.59.224.177","purposeCode":"GDS","isFVT":"N","chargeType":"OUR"}}";
String signature = sign(httpMethod, uriWithQueryString, clientId, timeString, content, signPrivateKey);
String signatureHeaderPayload = ALGORITHM +
NAME_VALUE_SEPARATOR +
RSA_256 +
COMMA +
KEY_VERSION +
NAME_VALUE_SEPARATOR +
1 +
COMMA +
SIGNATURE +
NAME_VALUE_SEPARATOR +
signature;
//System.out.println("signatureHeaderPayload:\n" + signatureHeaderPayload);
boolean res = verify(httpMethod, uriWithQueryString, clientId, timeString, content, signature, verifyPublicKey);
if (res) {
System.out.println("verify success.");
}
}
/**
* Sign the contents of the merchant request
*
* @param httpMethod http method e.g., POST, GET
* @param uriWithQueryString query string in url e.g., if your request url is https://{domain_name}.com/ams/api/pay/query uriWithQueryString should be /ams/api/pay/query not https://{domain_name}.com/ams/api/pay/query
* @param clientId clientId issued by WorldFirst e.g., *****
* @param timeString "request-time" in request e.g., 2020-01-03T14:36:27+08:00
* @param reqBody json format request e.g., "{"paymentRequestId":"*****","refundRequestId":"*****","refundAmount":{"currency":"USD","value":"123"},"extendInfo":{"":""}}"
* @param merchantPrivateKey your private key
*/
public static String sign(
String httpMethod,
String uriWithQueryString,
String clientId,
String timeString,
String reqBody,
String merchantPrivateKey) throws Exception {
// 1. construct the request content
String reqContent = httpMethod + " " + uriWithQueryString + "\n" + clientId + "." + timeString + "." + reqBody;
StringBuilder stringBuilder = new StringBuilder();
String reqContent2 = stringBuilder
.append(httpMethod)
.append(" ")
.append(uriWithQueryString)
.append("\n")
.append(clientId)
.append(".")
.append(timeString)
.append(".")
.append(reqBody).toString();
//System.out.println("reqContent2 is " + "\n" + reqContent2);
// 2. sign with your private key
String originalString = signWithSHA256RSA(reqContent, merchantPrivateKey);
// System.out.println("originalString is " + originalString);
// 4. return the encoded String
return URLEncoder.encode(originalString, "UTF-8");
}
/**
* Check the response of WorldFirst
*
* @param httpMethod http method e.g., POST, GET
* @param uriWithQueryString query string in url e.g., if your request url is https://{domain_name}.com/ams/api/pay/query uriWithQueryString should be /ams/api/pay/query not https://{domain_name}.com/ams/api/pay/query
* @param clientId clientId issued by WorldFirst e.g., *****
* @param timeString "response-time" in response e.g., 2020-01-02T22:36:32-08:00
* @param rspBody json format response e.g., "{"acquirerId":"xxx","refundAmount":{"currency":"CNY","value":"123"},"refundFromAmount":{"currency":"JPY","value":"234"},"refundId":"xxx","refundTime":"2020-01-03T14:36:32+08:00","result":{"resultCode":"SUCCESS","resultMessage":"success","resultStatus":"S"}}"
* @param worldfirstPublicKey public key from WorldFirst
*/
public static boolean verify(
String httpMethod,
String uriWithQueryString,
String clientId,
String timeString,
String rspBody,
String signature,
String worldfirstPublicKey) throws Exception {
// 1. construct the response content
String responseContent = httpMethod + " " + uriWithQueryString + "\n" + clientId + "." + timeString + "." + rspBody;
// 2. decode the signature string
String decodedString = URLDecoder.decode(signature, "UTF-8");
// 3. verify the response with WorldFirst's public key
return verifySignatureWithSHA256RSA(responseContent, decodedString, worldfirstPublicKey);
}
/**
* Generate base64 encoded signature using the sender's private key
*
* @param reqContent: the original content to be signed by the sender
* @param strPrivateKey: the private key which should be base64 encoded
*/
private static String signWithSHA256RSA(String reqContent, String strPrivateKey) throws Exception {
Signature privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initSign(getPrivateKeyFromBase64String(strPrivateKey));
privateSignature.update(reqContent.getBytes(StandardCharsets.UTF_8));
byte[] bytes = privateSignature.sign();
return Base64.getEncoder().encodeToString(bytes);
}
private static PrivateKey getPrivateKeyFromBase64String(String privateKeyString) throws Exception {
String privateKeyPath = "/Users/cole/ipay/private_pkcs8.pem";
StringBuilder publicKeyBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(privateKeyPath))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("-----BEGIN") || line.startsWith("-----END")) {
continue;
}
publicKeyBuilder.append(line);
}
}
System.out.println("私钥为:"+ publicKeyBuilder);
privateKeyString=publicKeyBuilder.toString();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
/**
* Verify if the received signature is correctly generated with the sender's public key
*
* @param rspContent: the original content signed by the sender and to be verified by the receiver.
* @param signature: the signature generated by the sender
* @param strPk: the public key string-base64 encoded
*/
private static boolean verifySignatureWithSHA256RSA(String rspContent, String signature, String strPk) throws Exception {
PublicKey publicKey = getPublicKeyFromBase64String(strPk);
Signature publicSignature = Signature.getInstance("SHA256withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(rspContent.getBytes(StandardCharsets.UTF_8));
byte[] signatureBytes = Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
}
private static PublicKey getPublicKeyFromBase64String(String publicKeyString) throws Exception {
String privateKeyPath = "/Users/cole/ipay/public.pem";
StringBuilder publicKeyBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(privateKeyPath))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("-----BEGIN") || line.startsWith("-----END")) {
continue;
}
publicKeyBuilder.append(line);
}
}
System.out.println("公钥为:"+ publicKeyBuilder);
byte[] b1 = Base64.getDecoder().decode(publicKeyBuilder.toString());
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(b1);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(X509publicKey);
//byte[] b1 = Base64.getDecoder().decode(publicKeyString);
//X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(b1);
//KeyFactory kf = KeyFactory.getInstance("RSA");
//return kf.generatePublic(X509publicKey);
}
}
6. md5加密
public static void main(String[] args) {
String input = "112590028883300242xwfp96dn93i6fakl0h";
System.out.println(input);
String encrypted = encryptWithMD5(input);
System.out.println("Encrypted String: " + encrypted);
}
public static String encryptWithMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
持续更新ing........