Cipher 類是 Java 加密體系(Java Cryptography Architecture,JCA)的一部分,用于實現加密和解密操作。它提供了對多種加密算法的訪問,包括對稱加密算法(如 AES、DES)和非對稱加密算法(如 RSA、DSA)。
公鑰基礎設施(Public Key Infrastructure,PKI)是一種基于公鑰加密技術的安全基礎設施,用于在不安全的網絡環境中實現安全通信。PKI 主要包括以下組件:
在 Java 中,你可以使用 Cipher 類和相關的類(如 KeyPairGenerator、KeyStore、CertificateFactory 等)來實現 PKI。以下是一個簡單的示例,展示了如何使用 Cipher 類和 PKI 實現加密和解密:
import javax.crypto.Cipher;
import java.security.*;
import java.security.cert.Certificate;
import java.util.Base64;
public class PKICipherExample {
public static void main(String[] args) throws Exception {
// 生成密鑰對
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// 加密數據
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
String plainText = "Hello, PKI!";
byte[] encryptedData = encryptCipher.doFinal(plainText.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedData);
System.out.println("Encrypted text: " + encryptedText);
// 解密數據
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decryptedData);
System.out.println("Decrypted text: " + decryptedText);
}
}
這個示例中,我們首先生成了一個 RSA 密鑰對,然后使用公鑰對數據進行加密,再使用私鑰對數據進行解密。請注意,這個示例僅用于演示目的,實際應用中你需要使用更安全的密鑰存儲和管理方式。