在Java中使用DES加密和解密,你可以使用 Cipher
类。以下是一个简单的例子,使用16位密钥进行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DesExample {
public static void main(String[] args) throws Exception {
String key = "0101010101010101"; // 16位密钥
String originalText = "Hello, World!";
// 加密
String encryptedText = encrypt(originalText, key);
System.out.println("Encrypted Text: " + encryptedText);
// 解密
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
}
private static String encrypt(String text, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
SecretKey secretKey = generateKey(key);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
private static String decrypt(String encryptedText, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
SecretKey secretKey = generateKey(key);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
private static SecretKey generateKey(String key) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(desKeySpec);
}
}
这个例子中,encrypt
方法使用密钥对明文进行加密,decrypt
方法使用相同的密钥对密文进行解密。注意,由于DES的安全性问题,不推荐在实际应用中使用。如果可能的话,考虑更安全的加密算法,如AES。