|
|
|
package com.dky.security;
|
|
|
|
|
|
|
|
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
|
|
|
|
|
|
|
import javax.crypto.Cipher;
|
|
|
|
import javax.crypto.spec.SecretKeySpec;
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
import java.security.Security;
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.Base64;
|
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.Map;
|
|
|
|
|
|
|
|
public class SM4Utils {
|
|
|
|
static {
|
|
|
|
Security.addProvider(new BouncyCastleProvider());
|
|
|
|
}
|
|
|
|
|
|
|
|
private static final String SM4_KEY = "mxhXSDiPYFjYgzRb"; // 16 bytes key
|
|
|
|
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
|
|
|
|
|
|
|
|
public static String encrypt(Map<String, String> map) throws Exception {
|
|
|
|
|
|
|
|
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
|
|
|
|
SecretKeySpec secretKey = new SecretKeySpec(SM4_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
|
|
|
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
|
|
|
byte[] encrypted = cipher.doFinal(mapToString(map).getBytes(StandardCharsets.UTF_8));
|
|
|
|
return Base64.getEncoder().encodeToString(encrypted);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static Map<String, String> decrypt(String encrypted) throws Exception {
|
|
|
|
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
|
|
|
|
SecretKeySpec secretKey = new SecretKeySpec(SM4_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
|
|
|
cipher.init(Cipher.DECRYPT_MODE, secretKey);
|
|
|
|
byte[] decoded = Base64.getDecoder().decode(encrypted);
|
|
|
|
byte[] decrypted = cipher.doFinal(decoded);
|
|
|
|
return stringToMap(new String(decrypted, StandardCharsets.UTF_8));
|
|
|
|
}
|
|
|
|
|
|
|
|
private static String mapToString(Map<String, String> map) {
|
|
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
for (Map.Entry<String, String> entry : map.entrySet()) {
|
|
|
|
sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
|
|
|
|
}
|
|
|
|
return sb.toString();
|
|
|
|
}
|
|
|
|
|
|
|
|
private static Map<String, String> stringToMap(String str) {
|
|
|
|
Map<String, String> map = new HashMap<>();
|
|
|
|
String[] entries = str.split("&");
|
|
|
|
for (String entry : entries) {
|
|
|
|
String[] keyValue = entry.split("=", 2);
|
|
|
|
if (keyValue.length == 2) {
|
|
|
|
map.put(keyValue[0], keyValue[1]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return map;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
|
|
Map<String, String> decrypt = decrypt("GLFIphzZ2SnR6kVx0gz2JBenxKHv3OrkbBPgTEeUcH8dP1vewChAxuWBZI+YsQS3H+Sb5/YEiJ0ub3p0QjXaSgbwTTqD4puEE/UZ7Yd4H8MPXFrtL0VVXoAArSbOj7JH");
|
|
|
|
System.out.println(decrypt.toString());
|
|
|
|
}
|
|
|
|
}
|