一、国密SM4加密
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
1.1 工具类
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Arrays;
public class Sm4Util {
private static final String ALGORITHM = "SM4";
private static final String TRANSFORMATION_ECB = ALGORITHM + "/ECB/PKCS7Padding";
private static final String TRANSFORMATION_CBC = ALGORITHM + "/CBC/PKCS7Padding";
private static final String TRANSFORMATION_ECB_NoPADDING = ALGORITHM + "/ECB/NoPadding";
private static final String TRANSFORMATION_CBC_NoPADDING = ALGORITHM + "/CBC/NoPadding";
private static final String ALGORITHM_HMAC_SM4 = "HmacSHA256";
private static final String PROVIDER_NAME = "BC";
static {
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] sign(byte[] key, byte[] data) throws Exception {
Mac mac = Mac.getInstance(ALGORITHM_HMAC_SM4, PROVIDER_NAME);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM_HMAC_SM4);
mac.init(secretKeySpec);
return mac.doFinal(data);
}
public static boolean verify(byte[] key, byte[] data, byte[] signature) throws Exception {
Mac mac = Mac.getInstance(ALGORITHM_HMAC_SM4, PROVIDER_NAME);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM_HMAC_SM4);
mac.init(secretKeySpec);
byte[] computedSignature = mac.doFinal(data);
return Arrays.equals(computedSignature, signature);
}
public static byte[] encryptByCbcPkcs7Padding(byte[] key, byte[] data) throws Exception{
Cipher cipher = Cipher.getInstance(TRANSFORMATION_CBC , "BC");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM);
byte[] iv = new byte[16];
Arrays.fill(iv, (byte) 0x00);
IvParameterSpec ivParameterSpec = new IvParam