package com.dky.security; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.SM2; import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.nio.charset.StandardCharsets; import java.security.Security; import java.util.*; public class SM4Utils { static { Security.addProvider(new BouncyCastleProvider()); } public final static String SM4_KEY = "1100fba8ee67ddf1f6f4e37c500dc10eee1bf15827ae3837810e30f402fa0bc6"; private static final String ALGORITHM = "AES/ECB/PKCS5Padding"; public static String encrypt(Map 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 decrypt(String encrypted) throws FileNotFoundException { File file = new File("file.txt"); FileReader fileReader = new FileReader(file); try (BufferedReader reader = new BufferedReader(fileReader)) { String line; while ((line = reader.readLine()) != null) { try { 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); byte[] decrypted = cipher.doFinal(decoded); return stringToMap(new String(decrypted, StandardCharsets.UTF_8)); } catch (Exception e) { System.out.println("私钥:" + line + ",该私钥未认证"); e.printStackTrace(); } } } catch ( IOException e){ System.out.println("文件读取错误,请检查文件内容是否为空"); throw new RuntimeException(); } return null; } private static String mapToString(Map map) { StringBuilder sb = new StringBuilder(); for (Map.Entry entry : map.entrySet()) { sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&'); } return sb.toString(); } private static Map stringToMap(String str) { Map 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; } /** * SM2私钥解密 * * @param encryptStr SM2加密字符串 * @return */ public static String sm2DecryptBase64(String encryptStr) { SM2 sm2 = new SM2(SM4_KEY, null); return StrUtil.utf8Str(sm2.decrypt(encryptStr, KeyType.PrivateKey)); } }