今天在对接乐企的时候,需要用到国密4算法对入参进行加密 之后对出参进行解密,乐企平台提供了算法实现,具体如下:
import org.apache.commons.lang3.ObjectUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;
public class SM4Util {
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final Charset ENCODING = StandardCharsets.UTF_8;
public static final String ALGORITHM_NAME = "SM4";
public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
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;
}
public static String encryptEcb(String hexKey, String paramStr) throws Exception {
byte[] keyData = ByteUtils.fromHexString(hexKey);
byte[] srcData = paramStr.getBytes(ENCODING);
byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
String cipherText = Base64.getEncoder().encodeToString(cipherArray);
return cipherText;
}
public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
@SuppressWarnings("UnnecessaryLocalVariable")
public static String decryptEcb(String hexKey, String cipherText) throws Exception {
byte[] keyData = ByteUtils.fromHexString(hexKey);
byte[] cipherData = Base64.getDecoder().decode(cipherText);
byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
String decryptStr = new String(srcData, ENCODING);
return decryptStr;
}
public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
return cipher.doFinal(cipherText);
}
}