在 Java 中,你可以使用 javax.crypto
包提供的 Cipher
类来进行 DES 加密和解密。下面是一个简单的示例:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
public class DesExample {
public static void main(String[] args) {
try {
// 1. 指定密钥
String keyString = "yourSecretKey"; // 替换为你的密钥,长度必须是8个字符
Key secretKey = generateKey(keyString);
// 2. 创建 Cipher 实例
Cipher cipher = Cipher.getInstance("DES");
// 3. 加密
String plaintext = "Hello, DES!";
byte[] encryptedBytes = encrypt(plaintext, secretKey, cipher);
System.out.println("Encrypted: " + bytesToHex(encryptedBytes));
// 4. 解密
String decryptedText = decrypt(encryptedBytes, secretKey, cipher);
System.out.println("Decrypted: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Key generateKey(String keyString) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(keyString.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(desKeySpec);
}
private static byte[] encrypt(String plaintext, Key secretKey, Cipher cipher) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
}
private static String decrypt(byte[] ciphertext, Key secretKey, Cipher cipher) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(ciphertext);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte aByte : bytes) {
result.append(String.format("%02X ", aByte));
}
return result.toString().trim();
}
}
在上述代码中,请将 yourSecretKey
替换为你的 8 字符密钥。这个例子中使用了 DES 加密算法,但需要注意 DES 已经被认为是不安全的,推荐使用更强大的算法,如 AES。