SM4加密算法实现java代码示例
时间: 2023-12-13 13:32:16 浏览: 159
以下是SM4加密算法的Java代码示例:
```java
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
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.SecureRandom;
public class SM4Util {
private static final int KEY_LENGTH = 16;
private static final int IV_LENGTH = 16;
/**
* 生成随机密钥
*
* @return 随机密钥的十六进制字符串表示
*/
public static String generateKey() {
byte[] key = new byte[KEY_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(key);
return Hex.toHexString(key);
}
/**
* 加密
*
* @param plainText 明文
* @param key 密钥的十六进制字符串表示
* @return 密文的十六进制字符串表示
*/
public static String encrypt(String plainText, String key) throws Exception {
byte[] keyBytes = Hex.decode(key);
byte[] ivBytes = new byte[IV_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(ivBytes);
BlockCipher engine = new SM4Engine();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
cipher.init(true, new ParametersWithIV(new KeyParameter(keyBytes), ivBytes));
byte[] input = plainText.getBytes(StandardCharsets.UTF_8);
byte[] output = new byte[cipher.getOutputSize(input.length)];
int outputLen = cipher.processBytes(input, 0, input.length, output, 0);
outputLen += cipher.doFinal(output, outputLen);
byte[] result = new byte[IV_LENGTH + outputLen];
System.arraycopy(ivBytes, 0, result, 0, IV_LENGTH);
System.arraycopy(output, 0, result, IV_LENGTH, outputLen);
return Hex.toHexString(result);
}
/**
* 解密
*
* @param cipherText 密文的十六进制字符串表示
* @param key 密钥的十六进制字符串表示
* @return 明文
*/
public static String decrypt(String cipherText, String key) throws Exception {
byte[] keyBytes = Hex.decode(key);
byte[] input = Hex.decode(cipherText);
byte[] ivBytes = new byte[IV_LENGTH];
System.arraycopy(input, 0, ivBytes, 0, IV_LENGTH);
BlockCipher engine = new SM4Engine();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
cipher.init(false, new ParametersWithIV(new KeyParameter(keyBytes), ivBytes));
byte[] output = new byte[cipher.getOutputSize(input.length - IV_LENGTH)];
int outputLen = cipher.processBytes(input, IV_LENGTH, input.length - IV_LENGTH, output, 0);
outputLen += cipher.doFinal(output, outputLen);
return new String(output, 0, outputLen, StandardCharsets.UTF_8);
}
}
```
阅读全文