之前文章介绍过SM2生成密钥和加解密的代码实现过程,这篇文章主要介绍下SM4对称加密算法的代码实现,依然还是引用的BC库。代码实现比较简单,直接上代码:
public final class Sm4Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Sm4Utils.class);
private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
private static volatile boolean initResult;
private static Object lock = new Object();
private static void init() {
if (!initResult) {
synchronized (lock) {
if (!initResult) {
try {
Security.addProvider(new BouncyCastleProvider());
initResult = true;
} catch (Exception e) {
LOGGER.error("init failed:{}", e.getMessage(), e);
}
}
}
}
}
/**
* 加密
* @param data 数据
* @param key 秘钥
* @return 密文
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
init();
SecretKey secretKey = new SecretKeySpec(key, "SM4");
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data);
return encryptedBytes;
}
/**
* 解密
* @param data 数据
* @param key 秘钥
* @return 明文
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
init();
SecretKey secretKey = new SecretKeySpec(key, "SM4");
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(data);
return decryptedBytes;
}
}
跑个测试用例试一下:文章来源:https://www.toymoban.com/news/detail-742648.html
public static void main(String args[]) throws Exception {
String key = "abcdefghigklmnop";
String data = "lenovo";
String ciphertext = Base64.encodeBase64String(Sm4Utils.encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8")));
System.out.println("ciphertext:" + ciphertext);
String plaintext = new String(Sm4Utils.decrypt(Base64.decodeBase64(ciphertext), key.getBytes("UTF-8")), "UTF-8");
System.out.println("plaintext:" + plaintext);
}
输出结果如下:文章来源地址https://www.toymoban.com/news/detail-742648.html
ciphertext:iqGwAR5ZHRPoPO78RmK6AQ==
plaintext:lenovo
到了这里,关于【Java加解密系列】- SM4加解密的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!