import cn.hutool.crypto.symmetric.SymmetricCrypto;
/**
* @author : chenfan
* @className : SM4Utils
* @date : Created in 2022/11/3 13:55
* @description :国密算法SM4加解密工具类
*/
/**
* 国密SM4分组密码算法工具类(对称加密)
*/
public class SM4Utils {
//SM4-加密
public static String encryptSm4(String plaintext, String key) {
//指明加密算法和秘钥
SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", key.getBytes());
return sm4.encryptHex(plaintext);
}
//SM4-解密
public static String decryptSm4(String ciphertext, String key) {
//指明加密算法和秘钥
SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", key.getBytes());
return sm4.decryptStr(ciphertext);
}
public static void main(String[] args) {
String content = "Hello SM4 国密算法";
String key = "pGmo2jZkrR8JqlQn";
String plain = encryptSm4(content, key);
String cipher = decryptSm4(plain, key);
System.out.println(plain + "\n" + cipher);
}
}
运行结果: