使用了Bouncy Castle库来实现SM4算法的加密和解密。其中,generateKey方法用于生成随机密钥,encrypt方法用于加密数据,decrypt方法用于解密数据,generateIV方法用于生成随机IV
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;
import java.security.SecureRandom;
public class SM2Util {
private static final int KEY_SIZE = 16;
private static final int IV_SIZE = 16;
/**
* 生成随机密钥
*
* @return 随机密钥
*/
public static byte[] generateKey() {
byte[] key = new byte[KEY_SIZE];
SecureRandom random = new SecureRandom();
random.nextBytes(key);
return key;
}
/**
* 加密
*
* @param key 密钥
* @param data 待加密数据
* @return 加密后的数据
*/
public static byte[] encrypt(byte[] key, byte[] data) {
byte[] iv = generateIV();
CipherParameters params = new ParametersWithIV(new KeyParameter(key), iv);
CBCBlockCipher cipher = new CBCBlockCipher(new SM4Engine());
cipher.init(true, params);
byte[] encrypted = new byte[cipher.getOutputSize(data.length)];
int len = cipher.processBytes(data, 0, data.length, encrypted, 0);
try {
cipher.doFinal(encrypted, len);
} catch (Exception e) {
throw new RuntimeException("Failed to encrypt data: " + e.getMessage());
}
return Hex.encode(encrypted);
}
/**
* 解密
*
* @param key 密钥
* @param data 待解密数据
* @return 解密后的数据
*/
public static byte[] decrypt(byte[] key, byte[] data) {
byte[] iv = generateIV();
CipherParameters params = new ParametersWithIV(new KeyParameter(key), iv);
CBCBlockCipher cipher = new CBCBlockCipher(new SM4Engine());
cipher.init(false, params);
byte[] decrypted = new byte[cipher.getOutputSize(data.length)];
int len = cipher.processBytes(data, 0, data.length, decrypted, 0);
try {
cipher.doFinal(decrypted, len);
} catch (Exception e) {
throw new RuntimeException("Failed to decrypt data: " + e.getMessage());
}
return decrypted;
}
/**
* 生成随机IV
*
* @return 随机IV
*/
private static byte[] generateIV() {
byte[] iv = new byte[IV_SIZE];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
return iv;
}
}```
/**
测试main
*/
public static void main(String[] args) {
byte[] key = SM2Util.generateKey();
// 加密数据
byte[] data = "Hello, world!".getBytes();
byte[] encrypted = SM2Util.encrypt(key, data);
// 解密数据
byte[] decrypted = SM2Util.decrypt(key, encrypted);
String message = new String(decrypted);
System.out.println(message);
}