sm4 加解密算法工具类( Java 版 )
sm4 加解密算法工具类(java)
说明:密钥是 hexString
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;/*** sm4 加解密算法工具类*/
public class Sm4Util {private static final String ENCODING = "UTF-8";private static final String ALGORITHM_NAME = "SM4";private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";private static final int DEFAULT_KEY_SIZE = 128;static {Security.addProvider(new BouncyCastleProvider());}public static void main(String[] args) throws Exception {}/*** sm4加密** @param data 待加密字符串* @param hexKey 16进制密钥(忽略大小写)* @return base64的字符串* @throws Exception*/public static String encryptEcb(String data, String hexKey) throws Exception {if (data == null || hexKey == null ) {return null;}byte[] keyData = ByteUtils.fromHexString(hexKey);byte[] srcData = data.getBytes(ENCODING);Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, keyData);byte[] cipherArray = cipher.doFinal(srcData);// String cipherText = ByteUtils.toHexString(cipherArray); // byte[] to hex StringString cipherText = Base64Encoder.encode(cipherArray); // byte[] to base64return cipherText;//}/*** sm4解密* @param cipherText 16进制的加密字符串(忽略大小写)* @param hexKey 16进制密钥* @return 解密后的字符串* @throws Exception*/public static String decryptEcb(String cipherText, String hexKey) throws Exception {if (cipherText == null || hexKey == null ) {return null;}// hexString --> byte[]byte[] keyData = ByteUtils.fromHexString(hexKey);byte[] cipherData = Base64Decoder.decode(cipherText);// 解密Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, keyData);byte[] srcData = cipher.doFinal(cipherData);// byte[] --> StringString decryptStr = new String(srcData, ENCODING);return decryptStr;}/*** get Cipher** @param algorithmName 算法名称* @param mode 模式* @param key* @return* @throws Exception*/private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);cipher.init(mode, sm4Key);return cipher;}}
依赖库
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version>
</dependency><dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.54</version>
</dependency>