Java 中可以使用 javax.crypto 包來實現 DES 加密和解密。
下面是一個例子,展示了如何用 DES 加密和解密字符串:
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
public class DESExample {
public static void main(String[] args) {
String originalText = "Hello, World!";
String secretKey = "SecretKey";
try {
// 創建一個 DES 密鑰
SecretKey key = generateKey(secretKey);
// 加密字符串
String encryptedText = encrypt(originalText, key);
System.out.println("Encrypted Text: " + encryptedText);
// 解密字符串
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成一個 DES 密鑰
private static SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
DESKeySpec desKeySpec = new DESKeySpec(secretKey.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(desKeySpec);
}
// 使用給定的密鑰加密字符串
private static String encrypt(String text, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(text.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 使用給定的密鑰解密字符串
private static String decrypt(String encryptedText, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
}
此代碼會輸出以下結果:
Encrypted Text: 2vqyQ/J1sIc=
Decrypted Text: Hello, World!
請注意,上述代碼只是一個示例,并沒有處理加密和解密的異常情況。在實際使用中,建議處理可能的異常情況,以保證代碼的健壯性。