SM4国密算法加解密工具类(JAVA版)
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.security.Security;
import java.util.Arrays;
public class SM4Utils {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] encrypt(byte[] key, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("SM4", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "SM4"));
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] key, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("SM4", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "SM4"));
return cipher.doFinal(data);
}
// 测试加解密
public static void main(String[] args) throws Exception {
byte[] key = new byte[16]; // 16字节的SM4密钥
byte[] data = "测试数据".getBytes("UTF-8");
// 加密
byte[] encryptedData = encrypt(key, data);
System.out.println("加密后的数据: " + bytesToHex(encryptedData));
// 解密
byte[] decryptedData = decrypt(key, encryptedData);
System.out.println("解密后的数据: " + new String(decryptedData, "UTF-8"));
}
// 字节数组转16进制字符串
private static String bytesToHex(byte[] bytes) {
StringBuilder hexBuilder = new StringBuilder();
for (byte b : bytes) {
hexBuilder.append(String.format("%02X", b));
}
return hexBuilder.toString();
}
}
这段代码提供了使用SM4加密算法进行加密和解密的方法,同时包含了密钥生成、加密、解密的简单示例。注意,在实际应用中,密钥生成方式应更安全,并确保密钥的安全存储。
评论已关闭