用java写一段SM4-CBC加解密代码
时间: 2023-02-19 22:23:45 浏览: 100
这是一段SM4-CBC加密的java代码:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class SM4_CBC {
// 加密
public static byte[] encrypt(byte[] key, byte[] iv, byte[] data) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "SM4");
Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
byte[] encrypted = cipher.doFinal(data);
return encrypted;
}
// 解密
public static byte[] decrypt(byte[] key, byte[] iv, byte[] data) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "SM4");
Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] decrypted = cipher.doFinal(data);
return decrypted;
}
}
阅读全文