对称加密用于敏感个人数据加密
package com.example.demo.service;
import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import java.util.Arrays;
public class SM4CBCFixedKey {
// 固定密钥(16字节)
private static final byte[] FIXED_KEY = hexToBytes("11223344556677889900AABBCCDDEEFF");
// 固定 IV(16字节)
private static final byte[] FIXED_IV = hexToBytes("A1A2A3A4A5A6A7A8A9AAABACADAEAFB0");
// CBC 加密
public static byte[] encrypt(byte[] data) throws Exception {
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SM4Engine()), new PKCS7Padding());
cipher.init(true, new ParametersWithIV(new KeyParameter(FIXED_KEY), FIXED_IV));
return process(cipher, data);
}
// CBC 解密
public static byte[] decrypt(byte[] encrypted) throws Exception {
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SM4Engine()), new PKCS7Padding());
cipher.init(false, new ParametersWithIV(new KeyParameter(FIXED_KEY), FIXED_IV));
return process(cipher, encrypted);
}
// 加/解密公共逻辑
private static byte[] process(BufferedBlockCipher cipher, byte[] input) throws Exception {
byte[] output = new byte[cipher.getOutputSize(input.length)];
int len = cipher.processBytes(input, 0, input.length, output, 0);
len += cipher.doFinal(output, len);
return Arrays.copyOf(output, len);
}
// HEX 工具方法
public static byte[] hexToBytes(String hex) {
int len = hex.length();
byte[] result = new byte[len / 2];
for (int i = 0; i < len; i += 2)
result[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i+1), 16));
return result;
}
public static String bytesToHex(byte[] data) {
StringBuilder sb = new StringBuilder();
for (byte b : data)
sb.append(String.format("%02X", b));
return sb.toString();
}
public static void main(String[] args) throws Exception {
String plaintext = "这是 CBC 模式下的 SM4 加密测试。";
System.out.println("原文: " + plaintext);
byte[] encrypted = encrypt(plaintext.getBytes("UTF-8"));
System.out.println("密文 : " + bytesToHex(encrypted));
byte[] decrypted = decrypt(encrypted);
System.out.println("解密结果: " + new String(decrypted, "UTF-8"));
}
}