pom:
org.bouncycastle bcprov-jdk15on1.68
Sm4Util:
package com.zy.platform.common.core.utils;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class Sm4Util {
private static final String ALGORITHM_NAME = "SM4";
private static final String ALGORITHM_ECB_PKCS5PADDING = "SM4/ECB/PKCS5Padding";
private static final int DEFAULT_KEY_SIZE = 128;
static {
// 防止内存中出现多次BouncyCastleProvider的实例
if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
Security.addProvider(new BouncyCastleProvider());
}
}
private Sm4Util() {
}
public static byte[] generateKey() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
kg.init(DEFAULT_KEY_SIZE, new SecureRandom());
return kg.generateKey().getEncoded();
}
public static byte[] hexTobytes(String hex) {
if (hex.length() < 1) {
return null;
} else {
byte[] result = new byte[hex.length() / 2];
int j = 0;
for(int i = 0; i < hex.length(); i+=2) {
result[j++] = (byte)Integer.parseInt(hex.substring(i,i+2), 16);
}
return result;
}
}
public static byte[] encryptEcbPkcs5Padding(byte[] data, byte[] key) throws Exception {
return sm4(data, key, ALGORITHM_ECB_PKCS5PADDING, null, Cipher.ENCRYPT_MODE);
}
public static byte[] decryptEcbPkcs5Padding(byte[] data, byte[] key) throws Exception {
return sm4(data, key, ALGORITHM_ECB_PKCS5PADDING, null, Cipher.DECRYPT_MODE);
}
private static byte[] sm4(byte[] input, byte[] key, String sm4mode, byte[] iv, int mode)
throws Exception {
IvParameterSpec ivParameterSpec = null;
if (null != iv) {
ivParameterSpec = new IvParameterSpec(iv);
}
SecretKeySpec sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
Cipher cipher = Cipher.getInstance(sm4mode, BouncyCastleProvider.PROVIDER_NAME);
if (null == ivParameterSpec) {
cipher.init(mode, sm4Key);
} else {
cipher.init(mode, sm4Key, ivParameterSpec);
}
return cipher.doFinal(input);
}
public static void main(String[] args) throws Exception {
String txt = "18253100000";
byte[] key = hexTobytes("51d95b1dc43a9faaad0570f81c755fcc");
byte[] output = Sm4Util.encryptEcbPkcs5Padding(txt.getBytes(StandardCharsets.UTF_8), key);
String hex = Hex.toHexString(output);
System.out.println("加密后结果 ==>"+hex);
// 解密
byte[] input = Hex.decode(hex);
output = Sm4Util.decryptEcbPkcs5Padding(input, key);
String s = new String(output, StandardCharsets.UTF_8);
System.out.println("解密后结果 ==>"+s);
System.out.println("key is ==>"+Hex.toHexString(key));
}
}
=====================================
安装依赖
npm install --save sm-crypto
test:



