一、SM4介紹
SM4.0(原名SMS4.0)是中華人民共和國政府采用的一種分組密碼標準,由國家密碼管理局于2012年3月21日發(fā)布。相關(guān)標準為“GM/T 0002-2012《SM4分組密碼算法》(原SMS4分組密碼算法)”。
在商用密碼體系中,SM4主要用于數(shù)據(jù)加密,其算法公開,分組長度與密鑰長度均為128bit,加密算法與密鑰擴展算法都采用32輪非線性迭代結(jié)構(gòu),S盒為固定的8比特輸入8比特輸出。
SM4.0中的指令長度被提升到大于64K(即64×1024)的水平,這是SM 3.0規(guī)格(渲染指令長度允許大于512)的128倍。
二、引入Hutool工具類
POM文件引入下面兩個依賴文章來源:http://www.zghlxwxcb.cn/news/detail-722527.html
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.69</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.5</version>
</dependency>
三、新建SM4Util
package org.demo.utils;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.core.util.StrUtil;
public class SM4Utils {
//key必須是16字節(jié),即128位
final static String key = "testsm4key123456";
//指明加密算法和秘鑰
static SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", key.getBytes());
/**
* 加密為16進制,也可以加密成base64/字節(jié)數(shù)組
*
* @param plaintext
* @return
*/
public static String encryptSm4(String plaintext) {
if (StrUtil.isBlank(plaintext)) {
return "";
}
return sm4.encryptHex(plaintext);
}
/**
* 解密
*
* @param ciphertext
* @return
*/
public static String decryptSm4(String ciphertext) {
if (StrUtil.isBlank(ciphertext)) {
return "";
}
return sm4.decryptStr(ciphertext);
}
}
四、使用
public static void main(String[] args) {
String str = SM4Utils.encryptSm4("測試加密");
System.out.println("加密后的字符串為"+str);
System.out.println("解密后的字符串為"+SM4Utils.decryptSm4(str));
}
以上內(nèi)容就是使用Hutools實現(xiàn)國密算法SM4的全過程,有問題可以私信博主文章來源地址http://www.zghlxwxcb.cn/news/detail-722527.html
到了這里,關(guān)于SpringBoot實現(xiàn)國密SM4加密、解密的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!