在Android和Java之间建立一个SSL Socket连接,可以通过以下步骤实现:
// Create keystore to hold the server's private key
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
serverKeyStore.load(null, null);
// Generate keypair for the server
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair serverKeyPair = keyGen.generateKeyPair();
// Create and store server's private key
PrivateKey serverPrivateKey = serverKeyPair.getPrivate();
serverKeyStore.setKeyEntry("server", serverPrivateKey, "password".toCharArray(), new Certificate[] {});
// Create and store server's self-signed certificate
X509Certificate serverCertificate = generateSelfSignedCertificate(serverKeyPair);
serverKeyStore.setCertificateEntry("server", serverCertificate);
// Save keystore to disk
FileOutputStream out = new FileOutputStream("server_keystore.jks");
serverKeyStore.store(out, "password".toCharArray());
out.close();
SSLContext sslContext = SSLContext.getInstance("TLS");
// Load server's private key and certificate from keystore
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
FileInputStream in = new FileInputStream("server_keystore.jks");
serverKeyStore.load(in, "password".toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(serverKeyStore, "password".toCharArray());
// Create trust manager that accepts all client certificates
TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Allow all clients to connect
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Don't need to check server's certificate
}
public X509Certificate[] getAcceptedIssuers() {
return new X509