请帮我用java写一个分组密码模式为CBC的加解密代码示例
时间: 2024-06-12 18:06:47 浏览: 16
以下是一个使用Java实现CBC分组密码模式的加解密代码示例:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class CBCEncryption {
private static final String KEY = "0123456789abcdef"; // 16位密钥
private static final String IV = "abcdef0123456789"; // 16位向量
public static String encrypt(String plainText) throws Exception {
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String cipherText) throws Exception {
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decrypted, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
String encryptedText = encrypt(plainText);
String decryptedText = decrypt(encryptedText);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted text: " + encryptedText);
System.out.println("Decrypted text: " + decryptedText);
}
}
```
在此示例中,我们使用AES算法和CBC分组密码模式进行加解密。密钥和向量都是16位,这里使用字符串表示。加密使用了`javax.crypto.Cipher`类,其中的`init`方法用于指定加密模式、密钥和向量。加密和解密分别调用`doFinal`方法,将明文或密文作为输入,输出相应的密文或明文。加密后的结果使用Base64编码进行输出,以便于传输和展示。最后,我们在主函数中测试了加解密的功能。