我需要一个java实现sm4加密的代码
时间: 2023-10-14 21:04:16 浏览: 100
SM2加密工具类前后端代码
以下是Java实现SM4加密的代码,需要使用Bouncy Castle加密库:
```java
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.nio.charset.StandardCharsets;
import java.security.Security;
public class SM4Util {
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
/**
* SM4加密
*
* @param plainText 明文
* @param key 密钥
* @param iv IV
* @return 密文
*/
public static String encrypt(String plainText, String key, String iv) {
try {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] ivBytes = iv.getBytes(StandardCharsets.UTF_8);
byte[] data = plainText.getBytes(StandardCharsets.UTF_8);
SM4Engine engine = new SM4Engine();
CBCBlockCipher cipher = new CBCBlockCipher(engine);
ParametersWithIV parameterIV = new ParametersWithIV(new KeyParameter(keyBytes), ivBytes);
cipher.init(true, parameterIV);
byte[] encrypted = new byte[cipher.getOutputSize(data.length)];
int len = cipher.processBytes(data, 0, data.length, encrypted, 0);
cipher.doFinal(encrypted, len);
return Hex.toHexString(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* SM4解密
*
* @param cipherText 密文
* @param key 密钥
* @param iv IV
* @return 明文
*/
public static String decrypt(String cipherText, String key, String iv) {
try {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] ivBytes = iv.getBytes(StandardCharsets.UTF_8);
byte[] data = Hex.decode(cipherText);
SM4Engine engine = new SM4Engine();
CBCBlockCipher cipher = new CBCBlockCipher(engine);
ParametersWithIV parameterIV = new ParametersWithIV(new KeyParameter(keyBytes), ivBytes);
cipher.init(false, parameterIV);
byte[] decrypted = new byte[cipher.getOutputSize(data.length)];
int len = cipher.processBytes(data, 0, data.length, decrypted, 0);
cipher.doFinal(decrypted, len);
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
使用示例:
```java
String plainText = "Hello, world!";
String key = "0123456789abcdef0123456789abcdef";
String iv = "0123456789abcdef";
String cipherText = SM4Util.encrypt(plainText, key, iv);
System.out.println("Cipher text: " + cipherText);
String decryptedText = SM4Util.decrypt(cipherText, key, iv);
System.out.println("Decrypted text: " + decryptedText);
```
注意:SM4算法使用的密钥长度为128位,即16个字节;IV长度为16个字节。在实际应用中,需要使用安全的随机数生成器生成密钥和IV。
阅读全文