package com.stylefeng.guns.modular.system.util.zhenglian;
|
|
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.KeyGenerator;
|
import javax.crypto.SecretKey;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.nio.charset.StandardCharsets;
|
import java.security.Security;
|
import java.util.Base64;
|
|
/**
|
* SM4国密工具类
|
* @author zhibing.pu
|
* @Date 2025/7/24 15:29
|
*/
|
public class SM4Util {
|
private static final String ALGORITHM_NAME = "SM4";
|
|
private static final String ALGORITHM_MODE = "SM4/ECB/PKCS5Padding";
|
|
|
static {
|
Security.addProvider(new BouncyCastleProvider());
|
}
|
|
/**
|
* 生成 SM4 密钥
|
* @return 密钥的 Base64 编码字符串
|
* @throws Exception 异常
|
*/
|
public static String generateKey() throws Exception {
|
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, "BC");
|
kg.init(128);
|
SecretKey secretKey = kg.generateKey();
|
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
|
}
|
|
/**
|
* SM4 加密
|
* @param plainText 明文
|
* @param key 密钥的 Base64 编码字符串
|
* @return 密文的 Base64 编码字符串
|
* @throws Exception 异常
|
*/
|
public static String encrypt(String plainText, String key) throws Exception {
|
byte[] keyBytes = Base64.getDecoder().decode(key);
|
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM_NAME);
|
Cipher cipher = Cipher.getInstance(ALGORITHM_MODE, "BC");
|
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
|
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
|
return Base64.getEncoder().encodeToString(encryptedBytes);
|
}
|
|
/**
|
* SM4 解密
|
* @param cipherText 密文的 Base64 编码字符串
|
* @param key 密钥的 Base64 编码字符串
|
* @return 明文
|
* @throws Exception 异常
|
*/
|
public static String decrypt(String cipherText, String key) throws Exception {
|
byte[] keyBytes = Base64.getDecoder().decode(key);
|
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM_NAME);
|
Cipher cipher = Cipher.getInstance(ALGORITHM_MODE, "BC");
|
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
|
byte[] cipherBytes = Base64.getDecoder().decode(cipherText);
|
byte[] decryptedBytes = cipher.doFinal(cipherBytes);
|
return new String(decryptedBytes, StandardCharsets.UTF_8);
|
}
|
|
public static void main(String[] args) {
|
try {
|
// 生成密钥
|
String key = generateKey();
|
System.out.println("生成的密钥: " + key);
|
|
// 明文
|
String plainText = "Hello, SM4!";
|
System.out.println("明文: " + plainText);
|
|
// 加密
|
String cipherText = encrypt(plainText, key);
|
System.out.println("密文: " + cipherText);
|
|
// 解密
|
String decryptedText = decrypt(cipherText, key);
|
System.out.println("解密后的明文: " + decryptedText);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
}
|