jiava实现SM4加解密
时间: 2023-07-26 19:37:04 浏览: 41
以下是Java实现SM4加解密的示例代码:
```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.SecureRandom;
public class SM4Util {
public static byte[] encrypt(byte[] plainText, byte[] key) {
byte[] iv = generateRandomIV();
byte[] cipherText = null;
try {
SM4Engine engine = new SM4Engine();
CBCBlockCipher cipher = new CBCBlockCipher(engine);
ParametersWithIV params = new ParametersWithIV(new KeyParameter(key), iv);
cipher.init(true, params);
cipherText = new byte[cipher.getOutputSize(plainText.length)];
int outputLen = cipher.processBytes(plainText, 0, plainText.length, cipherText, 0);
cipher.doFinal(cipherText, outputLen);
// 将IV和密文拼接在一起返回
byte[] result = new byte[iv.length + cipherText.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(cipherText, 0, result, iv.length, cipherText.length);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
public static byte[] decrypt(byte[] cipherText, byte[] key) {
byte[] iv = new byte[16];
byte[] encryptedData = new byte[cipherText.length - iv.length];
System.arraycopy(cipherText, 0, iv, 0, iv.length);
System.arraycopy(cipherText, iv.length, encryptedData, 0, encryptedData.length);
byte[] plainText = null;
try {
SM4Engine engine = new SM4Engine();
CBCBlockCipher cipher = new CBCBlockCipher(engine);
ParametersWithIV params = new ParametersWithIV(new KeyParameter(key), iv);
cipher.init(false, params);
plainText = new byte[cipher.getOutputSize(encryptedData.length)];
int outputLen = cipher.processBytes(encryptedData, 0, encryptedData.length, plainText, 0);
cipher.doFinal(plainText, outputLen);
} catch (Exception e) {
e.printStackTrace();
}
return plainText;
}
private static byte[] generateRandomIV() {
byte[] iv = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
return iv;
}
public static void main(String[] args) {
String plainText = "Hello, world!";
byte[] key = Hex.decode("0123456789abcdeffedcba9876543210");
byte[] cipherText = encrypt(plainText.getBytes(StandardCharsets.UTF_8), key);
String decryptedText = new String(decrypt(cipherText, key), StandardCharsets.UTF_8);
System.out.println("Plain text: " + plainText);
System.out.println("Cipher text: " + Hex.toHexString(cipherText));
System.out.println("Decrypted text: " + decryptedText);
}
}
```
这个示例代码使用了Bouncy Castle加密库,需要先下载并添加到项目中。具体使用方法可以参考Bouncy Castle官方文档。在示例代码中,我们首先生成长度为16字节的随机IV,然后使用SM4算法和CBC模式进行加解密。加密时,我们将IV和密文拼接在一起返回;解密时,我们从密文中分离出IV,再使用IV进行解密。注意,在实际使用中,key和IV需要保密存储,不应该明文存储。