1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.microemu.cldc.ssl;
21
22 import java.io.IOException;
23 import java.security.KeyManagementException;
24 import java.security.NoSuchAlgorithmException;
25 import java.security.SecureRandom;
26 import java.security.cert.Certificate;
27 import java.security.cert.X509Certificate;
28
29 import javax.microedition.io.SecureConnection;
30 import javax.microedition.io.SecurityInfo;
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.SSLSession;
33 import javax.net.ssl.SSLSocket;
34 import javax.net.ssl.SSLSocketFactory;
35 import javax.net.ssl.TrustManager;
36 import javax.net.ssl.X509TrustManager;
37
38 import org.microemu.cldc.CertificateImpl;
39 import org.microemu.cldc.ClosedConnection;
40 import org.microemu.cldc.SecurityInfoImpl;
41
42 public class Connection extends org.microemu.cldc.socket.SocketConnection implements SecureConnection, ClosedConnection {
43
44 private SecurityInfo securityInfo;
45
46 public Connection() {
47 securityInfo = null;
48 }
49
50 public javax.microedition.io.Connection open(String name) throws IOException {
51
52 if (!org.microemu.cldc.http.Connection.isAllowNetworkConnection()) {
53 throw new IOException("No network");
54 }
55
56 int portSepIndex = name.lastIndexOf(':');
57 int port = Integer.parseInt(name.substring(portSepIndex + 1));
58 String host = name.substring("ssl://".length(), portSepIndex);
59
60
61 TrustManager[] trustAllCerts = new TrustManager[]{
62 new X509TrustManager() {
63 public X509Certificate[] getAcceptedIssuers() {
64 return null;
65 }
66 public void checkClientTrusted(
67 X509Certificate[] certs, String authType) {
68 }
69 public void checkServerTrusted(
70 X509Certificate[] certs, String authType) {
71 }
72 }
73 };
74
75 try {
76 SSLContext sc = SSLContext.getInstance("SSL");
77 sc.init(null, trustAllCerts, new SecureRandom());
78 SSLSocketFactory factory = sc.getSocketFactory();
79 socket = factory.createSocket(host, port);
80 } catch (NoSuchAlgorithmException ex) {
81 throw new IOException(ex.toString());
82 } catch (KeyManagementException ex) {
83 throw new IOException(ex.toString());
84 }
85
86 return this;
87 }
88
89 public void close() throws IOException {
90
91
92 socket.close();
93 }
94
95 public SecurityInfo getSecurityInfo() throws IOException {
96 if (securityInfo == null) {
97 SSLSession session = ((SSLSocket) socket).getSession();
98
99 Certificate[] certs = session.getPeerCertificates();
100 if (certs.length == 0) {
101 throw new IOException();
102 }
103
104 securityInfo = new SecurityInfoImpl(
105 session.getCipherSuite(),
106 session.getProtocol(),
107 new CertificateImpl((X509Certificate) certs[0]));
108 }
109
110 return securityInfo;
111 }
112
113 }