Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/javax/xml/crypto/dsig/X509KeySelector.java
41152 views
1
/*
2
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
import java.io.InputStream;
25
import java.io.IOException;
26
import java.security.Key;
27
import java.security.KeyStore;
28
import java.security.KeyStoreException;
29
import java.security.PublicKey;
30
import java.security.cert.Certificate;
31
import java.security.cert.CertificateFactory;
32
import java.security.cert.CertSelector;
33
import java.security.cert.X509Certificate;
34
import java.security.cert.X509CertSelector;
35
import java.util.*;
36
import javax.security.auth.x500.X500Principal;
37
import javax.xml.crypto.*;
38
import javax.xml.crypto.dsig.*;
39
import javax.xml.crypto.dom.*;
40
import javax.xml.crypto.dsig.keyinfo.*;
41
42
import org.jcp.xml.dsig.internal.dom.DOMRetrievalMethod;
43
44
/**
45
* A <code>KeySelector</code> that returns {@link PublicKey}s. If the
46
* selector is created as trusted, it only returns public keys of trusted
47
* {@link X509Certificate}s stored in a {@link KeyStore}. Otherwise, it
48
* returns trusted or untrusted public keys (it doesn't care as long
49
* as it finds one).
50
*
51
* <p>This <code>KeySelector</code> uses the specified <code>KeyStore</code>
52
* to find a trusted <code>X509Certificate</code> that matches information
53
* specified in the {@link KeyInfo} passed to the {@link #select} method.
54
* The public key from the first match is returned. If no match,
55
* <code>null</code> is returned. See the <code>select</code> method for more
56
* information.
57
*
58
* @author Sean Mullan
59
*/
60
class X509KeySelector extends KeySelector {
61
62
private KeyStore ks;
63
private boolean trusted = true;
64
65
/**
66
* Creates a trusted <code>X509KeySelector</code>.
67
*
68
* @param keyStore the keystore
69
* @throws KeyStoreException if the keystore has not been initialized
70
* @throws NullPointerException if <code>keyStore</code> is
71
* <code>null</code>
72
*/
73
X509KeySelector(KeyStore keyStore) throws KeyStoreException {
74
this(keyStore, true);
75
}
76
77
X509KeySelector(KeyStore keyStore, boolean trusted)
78
throws KeyStoreException {
79
if (keyStore == null) {
80
throw new NullPointerException("keyStore is null");
81
}
82
this.trusted = trusted;
83
this.ks = keyStore;
84
// test to see if KeyStore has been initialized
85
this.ks.size();
86
}
87
88
/**
89
* Finds a key from the keystore satisfying the specified constraints.
90
*
91
* <p>This method compares data contained in {@link KeyInfo} entries
92
* with information stored in the <code>KeyStore</code>. The implementation
93
* iterates over the KeyInfo types and returns the first {@link PublicKey}
94
* of an X509Certificate in the keystore that is compatible with the
95
* specified AlgorithmMethod according to the following rules for each
96
* keyinfo type:
97
*
98
* X509Data X509Certificate: if it contains a <code>KeyUsage</code>
99
* extension that asserts the <code>digitalSignature</code> bit and
100
* matches an <code>X509Certificate</code> in the <code>KeyStore</code>.
101
* X509Data X509IssuerSerial: if the serial number and issuer DN match an
102
* <code>X509Certificate</code> in the <code>KeyStore</code>.
103
* X509Data X509SubjectName: if the subject DN matches an
104
* <code>X509Certificate</code> in the <code>KeyStore</code>.
105
* X509Data X509SKI: if the subject key identifier matches an
106
* <code>X509Certificate</code> in the <code>KeyStore</code>.
107
* KeyName: if the keyname matches an alias in the <code>KeyStore</code>.
108
* RetrievalMethod: supports rawX509Certificate and X509Data types. If
109
* rawX509Certificate type, it must match an <code>X509Certificate</code>
110
* in the <code>KeyStore</code>.
111
*
112
* @param keyInfo a <code>KeyInfo</code> (may be <code>null</code>)
113
* @param purpose the key's purpose
114
* @param method the algorithm method that this key is to be used for.
115
* Only keys that are compatible with the algorithm and meet the
116
* constraints of the specified algorithm should be returned.
117
* @param an <code>XMLCryptoContext</code> that may contain additional
118
* useful information for finding an appropriate key
119
* @return a key selector result
120
* @throws KeySelectorException if an exceptional condition occurs while
121
* attempting to find a key. Note that an inability to find a key is not
122
* considered an exception (<code>null</code> should be
123
* returned in that case). However, an error condition (ex: network
124
* communications failure) that prevented the <code>KeySelector</code>
125
* from finding a potential key should be considered an exception.
126
* @throws ClassCastException if the data type of <code>method</code>
127
* is not supported by this key selector
128
*/
129
public KeySelectorResult select(KeyInfo keyInfo,
130
KeySelector.Purpose purpose, AlgorithmMethod method,
131
XMLCryptoContext context) throws KeySelectorException {
132
133
SignatureMethod sm = (SignatureMethod) method;
134
135
try {
136
// return null if keyinfo is null or keystore is empty
137
if (keyInfo == null || ks.size() == 0) {
138
return new SimpleKeySelectorResult(null);
139
}
140
141
// Iterate through KeyInfo types
142
for (XMLStructure kiType : keyInfo.getContent()) {
143
// check X509Data
144
if (kiType instanceof X509Data) {
145
X509Data xd = (X509Data) kiType;
146
KeySelectorResult ksr = x509DataSelect(xd, sm);
147
if (ksr != null) {
148
return ksr;
149
}
150
// check KeyName
151
} else if (kiType instanceof KeyName) {
152
KeyName kn = (KeyName) kiType;
153
Certificate cert = ks.getCertificate(kn.getName());
154
if (cert != null && algEquals(sm.getAlgorithm(),
155
cert.getPublicKey().getAlgorithm())) {
156
return new SimpleKeySelectorResult(cert.getPublicKey());
157
}
158
// check RetrievalMethod
159
} else if (kiType instanceof RetrievalMethod) {
160
RetrievalMethod rm = (RetrievalMethod) kiType;
161
try {
162
KeySelectorResult ksr = null;
163
if (rm.getType().equals
164
(X509Data.RAW_X509_CERTIFICATE_TYPE)) {
165
OctetStreamData data = (OctetStreamData)
166
rm.dereference(context);
167
CertificateFactory cf =
168
CertificateFactory.getInstance("X.509");
169
X509Certificate cert = (X509Certificate)
170
cf.generateCertificate(data.getOctetStream());
171
ksr = certSelect(cert, sm);
172
} else if (rm.getType().equals(X509Data.TYPE)) {
173
X509Data xd = (X509Data) ((DOMRetrievalMethod) rm).
174
dereferenceAsXMLStructure(context);
175
ksr = x509DataSelect(xd, sm);
176
} else {
177
// skip; keyinfo type is not supported
178
continue;
179
}
180
if (ksr != null) {
181
return ksr;
182
}
183
} catch (Exception e) {
184
throw new KeySelectorException(e);
185
}
186
}
187
}
188
} catch (KeyStoreException kse) {
189
// throw exception if keystore is uninitialized
190
throw new KeySelectorException(kse);
191
}
192
193
// return null since no match could be found
194
return new SimpleKeySelectorResult(null);
195
}
196
197
/**
198
* Searches the specified keystore for a certificate that matches the
199
* criteria specified in the CertSelector.
200
*
201
* @return a KeySelectorResult containing the cert's public key if there
202
* is a match; otherwise null
203
*/
204
private KeySelectorResult keyStoreSelect(CertSelector cs)
205
throws KeyStoreException {
206
Enumeration<String> aliases = ks.aliases();
207
while (aliases.hasMoreElements()) {
208
String alias = aliases.nextElement();
209
Certificate cert = ks.getCertificate(alias);
210
if (cert != null && cs.match(cert)) {
211
return new SimpleKeySelectorResult(cert.getPublicKey());
212
}
213
}
214
return null;
215
}
216
217
/**
218
* Searches the specified keystore for a certificate that matches the
219
* specified X509Certificate and contains a public key that is compatible
220
* with the specified SignatureMethod.
221
*
222
* @return a KeySelectorResult containing the cert's public key if there
223
* is a match; otherwise null
224
*/
225
private KeySelectorResult certSelect(X509Certificate xcert,
226
SignatureMethod sm) throws KeyStoreException {
227
// skip non-signer certs
228
boolean[] keyUsage = xcert.getKeyUsage();
229
if (keyUsage != null && keyUsage[0] == false) {
230
return null;
231
}
232
String alias = ks.getCertificateAlias(xcert);
233
if (alias != null) {
234
PublicKey pk = ks.getCertificate(alias).getPublicKey();
235
// make sure algorithm is compatible with method
236
if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
237
return new SimpleKeySelectorResult(pk);
238
}
239
}
240
return null;
241
}
242
243
/**
244
* Returns an OID of a public-key algorithm compatible with the specified
245
* signature algorithm URI.
246
*/
247
private String getPKAlgorithmOID(String algURI) {
248
if (algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
249
return "1.2.840.10040.4.1";
250
} else if (algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
251
return "1.2.840.113549.1.1";
252
} else {
253
return null;
254
}
255
}
256
257
/**
258
* A simple KeySelectorResult containing a public key.
259
*/
260
private static class SimpleKeySelectorResult implements KeySelectorResult {
261
private final Key key;
262
SimpleKeySelectorResult(Key key) { this.key = key; }
263
public Key getKey() { return key; }
264
}
265
266
/**
267
* Checks if a JCA/JCE public key algorithm name is compatible with
268
* the specified signature algorithm URI.
269
*/
270
//@@@FIXME: this should also work for key types other than DSA/RSA
271
private boolean algEquals(String algURI, String algName) {
272
if (algName.equalsIgnoreCase("DSA") &&
273
algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
274
return true;
275
} else if (algName.equalsIgnoreCase("RSA") &&
276
algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
277
return true;
278
} else {
279
return false;
280
}
281
}
282
283
/**
284
* Searches the specified keystore for a certificate that matches an
285
* entry of the specified X509Data and contains a public key that is
286
* compatible with the specified SignatureMethod.
287
*
288
* @return a KeySelectorResult containing the cert's public key if there
289
* is a match; otherwise null
290
*/
291
private KeySelectorResult x509DataSelect(X509Data xd, SignatureMethod sm)
292
throws KeyStoreException, KeySelectorException {
293
294
// convert signature algorithm to compatible public-key alg OID
295
String algOID = getPKAlgorithmOID(sm.getAlgorithm());
296
X509CertSelector subjectcs = new X509CertSelector();
297
try {
298
subjectcs.setSubjectPublicKeyAlgID(algOID);
299
} catch (IOException ioe) {
300
throw new KeySelectorException(ioe);
301
}
302
Collection<X509Certificate> certs = new ArrayList<>();
303
304
for (Object o : xd.getContent()) {
305
// check X509IssuerSerial
306
if (o instanceof X509IssuerSerial) {
307
X509IssuerSerial xis = (X509IssuerSerial) o;
308
try {
309
subjectcs.setSerialNumber(xis.getSerialNumber());
310
String issuer = new X500Principal(xis.getIssuerName()).getName();
311
// strip off newline
312
if (issuer.endsWith("\n")) {
313
issuer = new String
314
(issuer.toCharArray(), 0, issuer.length()-1);
315
}
316
subjectcs.setIssuer(issuer);
317
} catch (IOException ioe) {
318
throw new KeySelectorException(ioe);
319
}
320
// check X509SubjectName
321
} else if (o instanceof String) {
322
String sn = (String) o;
323
try {
324
String subject = new X500Principal(sn).getName();
325
// strip off newline
326
if (subject.endsWith("\n")) {
327
subject = new String
328
(subject.toCharArray(), 0, subject.length()-1);
329
}
330
subjectcs.setSubject(subject);
331
} catch (IOException ioe) {
332
throw new KeySelectorException(ioe);
333
}
334
// check X509SKI
335
} else if (o instanceof byte[]) {
336
byte[] ski = (byte[]) o;
337
// DER-encode ski - required by X509CertSelector
338
byte[] encodedSki = new byte[ski.length+2];
339
encodedSki[0] = 0x04; // OCTET STRING tag value
340
encodedSki[1] = (byte) ski.length; // length
341
System.arraycopy(ski, 0, encodedSki, 2, ski.length);
342
subjectcs.setSubjectKeyIdentifier(encodedSki);
343
} else if (o instanceof X509Certificate) {
344
certs.add((X509Certificate)o);
345
// check X509CRL
346
// not supported: should use CertPath API
347
} else {
348
// skip all other entries
349
continue;
350
}
351
}
352
KeySelectorResult ksr = keyStoreSelect(subjectcs);
353
if (ksr != null) {
354
return ksr;
355
}
356
if (!certs.isEmpty() && !trusted) {
357
// try to find public key in certs in X509Data
358
for (X509Certificate cert : certs) {
359
if (subjectcs.match(cert)) {
360
return new SimpleKeySelectorResult(cert.getPublicKey());
361
}
362
}
363
}
364
return null;
365
}
366
}
367
368