import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Sm4Util {
public static final String ALGORITHM_NAME = "SM4";
public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";
//加密的key值->自己定义
public static final String key = "huangzy_yinnanxun";
//必须有本静态库,否则会报错
//java.security.NoSuchProviderException: no such provider: BC
static{
try{
Security.addProvider(new BouncyCastleProvider());
}catch(Exception e){
e.printStackTrace();
}
}
public static byte[] encryptCBC(byte[] key, byte[] data) {
try {
Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] decryptCBC(byte[] key, byte[] cipherText) {
try {
Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key);
//Cipher cipher = generateCBCCipher("SM4/CBC/NoPadding", Cipher.DECRYPT_MODE, key);
return cipher.doFinal(cipherText);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static Cipher generateCBCCipher(String algorithmName, int mode, byte[] key) {
try {
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);
cipher.init(mode, sm4Key, ivParameterSpec);
return cipher;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static final char HexCharArr[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F' };
public static String byteArrToHex(byte[] content) {
char[] strArr = new char[content.length * 2];
int i = 0;
for (byte bt : content) {
strArr[i++] = HexCharArr[bt >>> 4 & 0xf];
strArr[i++] = HexCharArr[bt & 0xf];
}
return new String(strArr);
}
public static byte[] hexString2Bytes(String content) {
int l = content.length() / 2;
byte[] result = new byte[l];
for (int i = 0; i < l; i++) {
result[i] = Integer.valueOf(content.substring(i * 2, i * 2 + 2), 16).byteValue();
}
return result;
}
public static String sm4Decode(String content) {
byte[] bytes2 = hexString2Bytes(content);
byte[] deBytes = decryptCBC(key.getBytes(),bytes2);
return new String(deBytes);
}
public static void main(String[] args) {
System.out.println("开始测试SM4加密解密====================");
String json = "123";
System.out.println("加密前:" + json);
byte[] bytes = encryptCBC(key.getBytes(), json.getBytes());
String s = byteArrToHex(bytes).toLowerCase();
System.out.println("加密后:" + s);
System.out.println("解密后:" +sm4Decode(s));
}
}