Java SM4 国密算法使用
引入maven依赖
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
生成秘钥
// 生成SM4秘钥
BouncyCastleProvider provider = new BouncyCastleProvider();
KeyGenerator generator = KeyGenerator.getInstance("SM4", provider);
SecretKey secretKey = generator.generateKey();
// 保存秘钥为文本
String key = Hex.toHexString(secretKey.getEncoded());
System.out.println("SM4 Key: " + key);
加载秘钥
// 从文本加载秘钥
secretKey = new SecretKeySpec(Hex.decodeStrict(key), "SM4");
加解密
// SM4加密方式与AES/DES差不多,加密模式可选ECB、CBC、CFB、OFB、CTR,填充方式NoPadding、PKCS5Padding/PKCS7Padding等
Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding", provider);
// 采用CBC加密模式需要提供iv向量参数,参数长度不能少于16个字节
IvParameterSpec iv = new IvParameterSpec(Hex.decodeStrict(key));
// 加密
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] bytes = cipher.doFinal("Hello".getBytes());
System.out.println("Encrypt word: " + Base64.getEncoder().encodeToString(bytes));
// 解密
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
bytes = cipher.doFinal(bytes);
System.out.println("Decrypt word: " + new String(bytes, StandardCharsets.UTF_8));
以上就是全部内容。