1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
public class X509Impl implements X509KeyManager {
private final String alias;
private final X509Certificate[] certChain;
private final PrivateKey privateKey;
public static SSLContext setForConnection(HttpsURLConnection con, Context context, String alias) throws CertificateException, KeyManagementException {
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
} catch(NoSuchAlgorithmException e){
throw new RuntimeException("Should not happen...", e);
}
sslContext.init(new KeyManager[] { fromAlias(context, alias)}, null, null);
con.setSSLSocketFactory(sslContext.getSocketFactory());
return sslContext;
}
public static X509Impl fromAlias(Context context, String alias) throws CertificateException {
X509Certificate[] certChain;
PrivateKey privateKey;
try {
certChain = KeyChain.getCertificateChain(context, alias);
privateKey = KeyChain.getPrivateKey(context, alias);
} catch (KeyChainException e) {
throw new CertificateException(e);
} catch (InterruptedException e) {
throw new CertificateException(e);
}
if(certChain == null || privateKey == null){
throw new CertificateException("Can't access certificate from keystore");
}
return new X509Impl(alias, certChain, privateKey);
}
public X509Impl(String alias, X509Certificate[] certChain, PrivateKey privateKey) throws CertificateException {
this.alias = alias;
this.certChain = certChain;
this.privateKey = privateKey;
}
@Override
public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
return alias;
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
if(this.alias.equals(alias)) return certChain;
return null;
}
@Override
public PrivateKey getPrivateKey(String alias) {
if(this.alias.equals(alias)) return privateKey;
return null;
}
// Methods unused (for client SSLSocket callbacks)
@Override public final String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
throw new UnsupportedOperationException();
}
@Override public final String[] getClientAliases(String keyType, Principal[] issuers) {
throw new UnsupportedOperationException();
}
@Override public final String[] getServerAliases(String keyType, Principal[] issuers) {
throw new UnsupportedOperationException();
}
}
|