package com.dky.security; import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.nio.charset.StandardCharsets; import java.security.Security; import java.util.*; 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 List<Map<String, String>> decrypt(String encrypted) throws Exception { List<Map<String, String>> ary = new ArrayList<>(); File file = new File("file.txt"); FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(fileReader); String line; while ((line = reader.readLine()) != null) { Cipher cipher = Cipher.getInstance(ALGORITHM, "BC"); SecretKeySpec secretKey = new SecretKeySpec(line.getBytes(StandardCharsets.UTF_8), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decoded = Base64.getDecoder().decode(encrypted); try { byte[] decrypted = cipher.doFinal(decoded); ary.add(stringToMap(new String(decrypted, StandardCharsets.UTF_8))); } catch (Exception e) { // e.printStackTrace(); } } return ary; } 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 { String s = "GWnQ4RqqTc8n1Uj59xLoUtv975fmQsRWuvsk1zRmQu9TwIvlc6FTekndKMh+vMuRbI2bxdmuIxyZndYcg9u5xVa+HaiBZRP8OZFYIAo+66vDVlkBf47Nh2srjFyIXlLH"; List<Map<String, String>> decryptList = decrypt(s); decryptList.forEach(System.out::println); /* File file = new File("file.txt"); try { FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(fileReader); String line; while ((line = reader.readLine()) != null) { // 处理每一行的数据 System.out.println(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); }*/ } }