des 加密cbc模式java代码实现
时间: 2023-11-14 09:07:09 浏览: 36
以下是使用Java实现DES加密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 DesCbcEncryption {
public static void main(String[] args) throws Exception {
String key = "01234567"; // 8-byte key
String iv = "abcdefgh"; // 8-byte IV
String plaintext = "Hello world!";
byte[] encrypted = encrypt(plaintext, key, iv);
String encryptedBase64 = Base64.getEncoder().encodeToString(encrypted);
System.out.println("Encrypted: " + encryptedBase64);
String decrypted = decrypt(encrypted, key, iv);
System.out.println("Decrypted: " + decrypted);
}
public static byte[] encrypt(String plaintext, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
}
public static String decrypt(byte[] ciphertext, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decrypted = cipher.doFinal(ciphertext);
return new String(decrypted, StandardCharsets.UTF_8);
}
}
```
其中,`encrypt`方法用于加密明文,`decrypt`方法用于解密密文。在此示例中,使用了8字节的密钥和8字节的IV,使用了DES算法和CBC模式,并将结果进行了Base64编码。注意,CBC模式需要指定一个初始化向量(IV),它与密钥一样需要保密。在实际应用中,IV需要每次加密时都随机生成并保存,以增强安全性。