import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
public class Sm4Util {
private static String key = "****";
private static String iv = "***";
public static String encrypt(String plainTxt) {
String cipherTxt = "";
SymmetricCrypto sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, key.getBytes(CharsetUtil.CHARSET_UTF_8), iv.getBytes(CharsetUtil.CHARSET_UTF_8));
byte[] encrypHex = sm4.encrypt(plainTxt);
cipherTxt = Base64.encode(encrypHex);
return cipherTxt;
}
public static String decrypt(String cipherTxt) {
String plainTxt = "";
try {
SymmetricCrypto sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, key.getBytes(CharsetUtil.CHARSET_UTF_8), iv.getBytes(CharsetUtil.CHARSET_UTF_8));
byte[] cipherHex = Base64.decode(cipherTxt.trim());
plainTxt = sm4.decryptStr(cipherHex, CharsetUtil.CHARSET_UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return plainTxt;
}
public static void main(String[] args) {
String content = "123";
String encryptHex = new Sm4Util().encrypt(content);
String decryptStr = new Sm4Util().decrypt(encryptHex);
String encrypt = new Sm4Util().encrypt("{\"aa\":\"111\",\"bb\":\"222\"}");
System.out.println("加密后=" + encrypt);
System.out.println("解密=" + decryptStr);
}
}
记得 maven 引入(要不然会报错)
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk15on -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.68</version>
</dependency>