要在Java中使用Cipher類實現SSL/TLS,您需要遵循以下步驟:
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.SecureRandom;
import javax.crypto.Cipher;
SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(port);
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
SSLSession sslSession = sslSocket.getSession();
String cipherSuite = sslSession.getCipherSuite();
System.out.println("CipherSuite: " + cipherSuite);
Cipher cipher = Cipher.getInstance(cipherSuite);
sslSession.getPeerCertificates()
來完成:Certificate[] certificates = sslSession.getPeerCertificates();
X509Certificate peerCertificate = (X509Certificate) certificates[0];
PublicKey publicKey = peerCertificate.getPublicKey();
SecretKey secretKey = new SecretKeySpec(publicKey.getEncoded(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] plainTextBytes = "Hello, World!".getBytes();
byte[] encryptedBytes = cipher.doFinal(plainTextBytes);
System.out.println("Encrypted: " + new String(encryptedBytes));
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
System.out.println("Decrypted: " + new String(decryptedBytes));
sslSocket.close();
sslServerSocket.close();
請注意,這只是一個簡單的示例,實際應用程序可能需要更復雜的錯誤處理和安全性。此外,您還需要為客戶端實現類似的邏輯,以便與服務器進行通信。在實際應用中,您可能還需要考慮使用SSLContext和KeyManagerFactory來管理密鑰庫和信任庫。