电科院-电能替代模型工具开发
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
3.3 KiB

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<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 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<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;
}
/**
* 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));
}
}