Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/macosx/classes/apple/security/KeychainStore.java
41133 views
1
/*
2
* Copyright (c) 2011, 2021, 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. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package apple.security;
27
28
import java.io.*;
29
import java.security.*;
30
import java.security.cert.*;
31
import java.security.cert.Certificate;
32
import java.security.spec.*;
33
import java.util.*;
34
35
import javax.crypto.*;
36
import javax.crypto.spec.*;
37
import javax.security.auth.x500.*;
38
39
import sun.security.pkcs.*;
40
import sun.security.pkcs.EncryptedPrivateKeyInfo;
41
import sun.security.util.*;
42
import sun.security.x509.*;
43
44
/**
45
* This class provides the keystore implementation referred to as "KeychainStore".
46
* It uses the current user's keychain as its backing storage, and does NOT support
47
* a file-based implementation.
48
*/
49
50
public final class KeychainStore extends KeyStoreSpi {
51
52
// Private keys and their supporting certificate chains
53
// If a key came from the keychain it has a SecKeyRef and one or more
54
// SecCertificateRef. When we delete the key we have to delete all of the corresponding
55
// native objects.
56
static class KeyEntry {
57
Date date; // the creation date of this entry
58
byte[] protectedPrivKey;
59
char[] password;
60
long keyRef; // SecKeyRef for this key
61
Certificate chain[];
62
long chainRefs[]; // SecCertificateRefs for this key's chain.
63
};
64
65
// Trusted certificates
66
static class TrustedCertEntry {
67
Date date; // the creation date of this entry
68
69
Certificate cert;
70
long certRef; // SecCertificateRef for this key
71
};
72
73
/**
74
* Entries that have been deleted. When something calls engineStore we'll
75
* remove them from the keychain.
76
*/
77
private Hashtable<String, Object> deletedEntries = new Hashtable<>();
78
79
/**
80
* Entries that have been added. When something calls engineStore we'll
81
* add them to the keychain.
82
*/
83
private Hashtable<String, Object> addedEntries = new Hashtable<>();
84
85
/**
86
* Private keys and certificates are stored in a hashtable.
87
* Hash entries are keyed by alias names.
88
*/
89
private Hashtable<String, Object> entries = new Hashtable<>();
90
91
/**
92
* Algorithm identifiers and corresponding OIDs for the contents of the
93
* PKCS12 bag we get from the Keychain.
94
*/
95
private static ObjectIdentifier PKCS8ShroudedKeyBag_OID =
96
ObjectIdentifier.of(KnownOIDs.PKCS8ShroudedKeyBag);
97
private static ObjectIdentifier pbeWithSHAAnd3KeyTripleDESCBC_OID =
98
ObjectIdentifier.of(KnownOIDs.PBEWithSHA1AndDESede);
99
100
/**
101
* Constnats used in PBE decryption.
102
*/
103
private static final int iterationCount = 1024;
104
private static final int SALT_LEN = 20;
105
106
private static final Debug debug = Debug.getInstance("keystore");
107
108
static {
109
jdk.internal.loader.BootLoader.loadLibrary("osxsecurity");
110
}
111
112
private static void permissionCheck() {
113
@SuppressWarnings("removal")
114
SecurityManager sec = System.getSecurityManager();
115
116
if (sec != null) {
117
sec.checkPermission(new RuntimePermission("useKeychainStore"));
118
}
119
}
120
121
122
/**
123
* Verify the Apple provider in the constructor.
124
*
125
* @exception SecurityException if fails to verify
126
* its own integrity
127
*/
128
public KeychainStore() { }
129
130
/**
131
* Returns the key associated with the given alias, using the given
132
* password to recover it.
133
*
134
* @param alias the alias name
135
* @param password the password for recovering the key. This password is
136
* used internally as the key is exported in a PKCS12 format.
137
*
138
* @return the requested key, or null if the given alias does not exist
139
* or does not identify a <i>key entry</i>.
140
*
141
* @exception NoSuchAlgorithmException if the algorithm for recovering the
142
* key cannot be found
143
* @exception UnrecoverableKeyException if the key cannot be recovered
144
* (e.g., the given password is wrong).
145
*/
146
public Key engineGetKey(String alias, char[] password)
147
throws NoSuchAlgorithmException, UnrecoverableKeyException
148
{
149
permissionCheck();
150
151
// An empty password is rejected by MacOS API, no private key data
152
// is exported. If no password is passed (as is the case when
153
// this implementation is used as browser keystore in various
154
// deployment scenarios like Webstart, JFX and applets), create
155
// a dummy password so MacOS API is happy.
156
if (password == null || password.length == 0) {
157
// Must not be a char array with only a 0, as this is an empty
158
// string.
159
if (random == null) {
160
random = new SecureRandom();
161
}
162
password = Long.toString(random.nextLong()).toCharArray();
163
}
164
165
Object entry = entries.get(alias.toLowerCase());
166
167
if (entry == null || !(entry instanceof KeyEntry)) {
168
return null;
169
}
170
171
// This call gives us a PKCS12 bag, with the key inside it.
172
byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry)entry).keyRef, password);
173
if (exportedKeyInfo == null) {
174
return null;
175
}
176
177
PrivateKey returnValue = null;
178
179
try {
180
byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);
181
byte[] encryptedKey;
182
AlgorithmParameters algParams;
183
ObjectIdentifier algOid;
184
try {
185
// get the encrypted private key
186
EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);
187
encryptedKey = encrInfo.getEncryptedData();
188
189
// parse Algorithm parameters
190
DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
191
DerInputStream in = val.toDerInputStream();
192
algOid = in.getOID();
193
algParams = parseAlgParameters(in);
194
195
} catch (IOException ioe) {
196
UnrecoverableKeyException uke =
197
new UnrecoverableKeyException("Private key not stored as "
198
+ "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
199
uke.initCause(ioe);
200
throw uke;
201
}
202
203
// Use JCE to decrypt the data using the supplied password.
204
SecretKey skey = getPBEKey(password);
205
Cipher cipher = Cipher.getInstance(algOid.toString());
206
cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
207
byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);
208
PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);
209
210
// Parse the key algorithm and then use a JCA key factory to create the private key.
211
DerValue val = new DerValue(decryptedPrivateKey);
212
DerInputStream in = val.toDerInputStream();
213
214
// Ignore this -- version should be 0.
215
int i = in.getInteger();
216
217
// Get the Algorithm ID next
218
DerValue[] value = in.getSequence(2);
219
if (value.length < 1 || value.length > 2) {
220
throw new IOException("Invalid length for AlgorithmIdentifier");
221
}
222
AlgorithmId algId = new AlgorithmId(value[0].getOID());
223
String algName = algId.getName();
224
225
// Get a key factory for this algorithm. It's likely to be 'RSA'.
226
KeyFactory kfac = KeyFactory.getInstance(algName);
227
returnValue = kfac.generatePrivate(kspec);
228
} catch (Exception e) {
229
UnrecoverableKeyException uke =
230
new UnrecoverableKeyException("Get Key failed: " +
231
e.getMessage());
232
uke.initCause(e);
233
throw uke;
234
}
235
236
return returnValue;
237
}
238
239
private native byte[] _getEncodedKeyData(long secKeyRef, char[] password);
240
241
/**
242
* Returns the certificate chain associated with the given alias.
243
*
244
* @param alias the alias name
245
*
246
* @return the certificate chain (ordered with the user's certificate first
247
* and the root certificate authority last), or null if the given alias
248
* does not exist or does not contain a certificate chain (i.e., the given
249
* alias identifies either a <i>trusted certificate entry</i> or a
250
* <i>key entry</i> without a certificate chain).
251
*/
252
public Certificate[] engineGetCertificateChain(String alias) {
253
permissionCheck();
254
255
Object entry = entries.get(alias.toLowerCase());
256
257
if (entry != null && entry instanceof KeyEntry) {
258
if (((KeyEntry)entry).chain == null) {
259
return null;
260
} else {
261
return ((KeyEntry)entry).chain.clone();
262
}
263
} else {
264
return null;
265
}
266
}
267
268
/**
269
* Returns the certificate associated with the given alias.
270
*
271
* <p>If the given alias name identifies a
272
* <i>trusted certificate entry</i>, the certificate associated with that
273
* entry is returned. If the given alias name identifies a
274
* <i>key entry</i>, the first element of the certificate chain of that
275
* entry is returned, or null if that entry does not have a certificate
276
* chain.
277
*
278
* @param alias the alias name
279
*
280
* @return the certificate, or null if the given alias does not exist or
281
* does not contain a certificate.
282
*/
283
public Certificate engineGetCertificate(String alias) {
284
permissionCheck();
285
286
Object entry = entries.get(alias.toLowerCase());
287
288
if (entry != null) {
289
if (entry instanceof TrustedCertEntry) {
290
return ((TrustedCertEntry)entry).cert;
291
} else {
292
KeyEntry ke = (KeyEntry)entry;
293
if (ke.chain == null || ke.chain.length == 0) {
294
return null;
295
}
296
return ke.chain[0];
297
}
298
} else {
299
return null;
300
}
301
}
302
303
/**
304
* Returns the creation date of the entry identified by the given alias.
305
*
306
* @param alias the alias name
307
*
308
* @return the creation date of this entry, or null if the given alias does
309
* not exist
310
*/
311
public Date engineGetCreationDate(String alias) {
312
permissionCheck();
313
314
Object entry = entries.get(alias.toLowerCase());
315
316
if (entry != null) {
317
if (entry instanceof TrustedCertEntry) {
318
return new Date(((TrustedCertEntry)entry).date.getTime());
319
} else {
320
return new Date(((KeyEntry)entry).date.getTime());
321
}
322
} else {
323
return null;
324
}
325
}
326
327
/**
328
* Assigns the given key to the given alias, protecting it with the given
329
* password.
330
*
331
* <p>If the given key is of type <code>java.security.PrivateKey</code>,
332
* it must be accompanied by a certificate chain certifying the
333
* corresponding public key.
334
*
335
* <p>If the given alias already exists, the keystore information
336
* associated with it is overridden by the given key (and possibly
337
* certificate chain).
338
*
339
* @param alias the alias name
340
* @param key the key to be associated with the alias
341
* @param password the password to protect the key
342
* @param chain the certificate chain for the corresponding public
343
* key (only required if the given key is of type
344
* <code>java.security.PrivateKey</code>).
345
*
346
* @exception KeyStoreException if the given key cannot be protected, or
347
* this operation fails for some other reason
348
*/
349
public void engineSetKeyEntry(String alias, Key key, char[] password,
350
Certificate[] chain)
351
throws KeyStoreException
352
{
353
permissionCheck();
354
355
synchronized(entries) {
356
try {
357
KeyEntry entry = new KeyEntry();
358
entry.date = new Date();
359
360
if (key instanceof PrivateKey) {
361
if ((key.getFormat().equals("PKCS#8")) ||
362
(key.getFormat().equals("PKCS8"))) {
363
entry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), password);
364
entry.password = password.clone();
365
} else {
366
throw new KeyStoreException("Private key is not encoded as PKCS#8");
367
}
368
} else {
369
throw new KeyStoreException("Key is not a PrivateKey");
370
}
371
372
// clone the chain
373
if (chain != null) {
374
if ((chain.length > 1) && !validateChain(chain)) {
375
throw new KeyStoreException("Certificate chain does not validate");
376
}
377
378
entry.chain = chain.clone();
379
entry.chainRefs = new long[entry.chain.length];
380
}
381
382
String lowerAlias = alias.toLowerCase();
383
if (entries.get(lowerAlias) != null) {
384
deletedEntries.put(lowerAlias, entries.get(lowerAlias));
385
}
386
387
entries.put(lowerAlias, entry);
388
addedEntries.put(lowerAlias, entry);
389
} catch (Exception nsae) {
390
KeyStoreException ke = new KeyStoreException("Key protection algorithm not found: " + nsae);
391
ke.initCause(nsae);
392
throw ke;
393
}
394
}
395
}
396
397
/**
398
* Assigns the given key (that has already been protected) to the given
399
* alias.
400
*
401
* <p>If the protected key is of type
402
* <code>java.security.PrivateKey</code>, it must be accompanied by a
403
* certificate chain certifying the corresponding public key. If the
404
* underlying keystore implementation is of type <code>jks</code>,
405
* <code>key</code> must be encoded as an
406
* <code>EncryptedPrivateKeyInfo</code> as defined in the PKCS #8 standard.
407
*
408
* <p>If the given alias already exists, the keystore information
409
* associated with it is overridden by the given key (and possibly
410
* certificate chain).
411
*
412
* @param alias the alias name
413
* @param key the key (in protected format) to be associated with the alias
414
* @param chain the certificate chain for the corresponding public
415
* key (only useful if the protected key is of type
416
* <code>java.security.PrivateKey</code>).
417
*
418
* @exception KeyStoreException if this operation fails.
419
*/
420
public void engineSetKeyEntry(String alias, byte[] key,
421
Certificate[] chain)
422
throws KeyStoreException
423
{
424
permissionCheck();
425
426
synchronized(entries) {
427
// key must be encoded as EncryptedPrivateKeyInfo as defined in
428
// PKCS#8
429
KeyEntry entry = new KeyEntry();
430
try {
431
EncryptedPrivateKeyInfo privateKey = new EncryptedPrivateKeyInfo(key);
432
entry.protectedPrivKey = privateKey.getEncoded();
433
} catch (IOException ioe) {
434
throw new KeyStoreException("key is not encoded as "
435
+ "EncryptedPrivateKeyInfo");
436
}
437
438
entry.date = new Date();
439
440
if ((chain != null) &&
441
(chain.length != 0)) {
442
entry.chain = chain.clone();
443
entry.chainRefs = new long[entry.chain.length];
444
}
445
446
String lowerAlias = alias.toLowerCase();
447
if (entries.get(lowerAlias) != null) {
448
deletedEntries.put(lowerAlias, entries.get(alias));
449
}
450
entries.put(lowerAlias, entry);
451
addedEntries.put(lowerAlias, entry);
452
}
453
}
454
455
/**
456
* Assigns the given certificate to the given alias.
457
*
458
* <p>If the given alias already exists in this keystore and identifies a
459
* <i>trusted certificate entry</i>, the certificate associated with it is
460
* overridden by the given certificate.
461
*
462
* @param alias the alias name
463
* @param cert the certificate
464
*
465
* @exception KeyStoreException if the given alias already exists and does
466
* not identify a <i>trusted certificate entry</i>, or this operation
467
* fails for some other reason.
468
*/
469
public void engineSetCertificateEntry(String alias, Certificate cert)
470
throws KeyStoreException
471
{
472
permissionCheck();
473
474
synchronized(entries) {
475
476
Object entry = entries.get(alias.toLowerCase());
477
if ((entry != null) && (entry instanceof KeyEntry)) {
478
throw new KeyStoreException
479
("Cannot overwrite key entry with certificate");
480
}
481
482
// This will be slow, but necessary. Enumerate the values and then see if the cert matches the one in the trusted cert entry.
483
// Security framework doesn't support the same certificate twice in a keychain.
484
Collection<Object> allValues = entries.values();
485
486
for (Object value : allValues) {
487
if (value instanceof TrustedCertEntry) {
488
TrustedCertEntry tce = (TrustedCertEntry)value;
489
if (tce.cert.equals(cert)) {
490
throw new KeyStoreException("Keychain does not support mulitple copies of same certificate.");
491
}
492
}
493
}
494
495
TrustedCertEntry trustedCertEntry = new TrustedCertEntry();
496
trustedCertEntry.cert = cert;
497
trustedCertEntry.date = new Date();
498
String lowerAlias = alias.toLowerCase();
499
if (entries.get(lowerAlias) != null) {
500
deletedEntries.put(lowerAlias, entries.get(lowerAlias));
501
}
502
entries.put(lowerAlias, trustedCertEntry);
503
addedEntries.put(lowerAlias, trustedCertEntry);
504
}
505
}
506
507
/**
508
* Deletes the entry identified by the given alias from this keystore.
509
*
510
* @param alias the alias name
511
*
512
* @exception KeyStoreException if the entry cannot be removed.
513
*/
514
public void engineDeleteEntry(String alias)
515
throws KeyStoreException
516
{
517
permissionCheck();
518
519
synchronized(entries) {
520
Object entry = entries.remove(alias.toLowerCase());
521
deletedEntries.put(alias.toLowerCase(), entry);
522
}
523
}
524
525
/**
526
* Lists all the alias names of this keystore.
527
*
528
* @return enumeration of the alias names
529
*/
530
public Enumeration<String> engineAliases() {
531
permissionCheck();
532
return entries.keys();
533
}
534
535
/**
536
* Checks if the given alias exists in this keystore.
537
*
538
* @param alias the alias name
539
*
540
* @return true if the alias exists, false otherwise
541
*/
542
public boolean engineContainsAlias(String alias) {
543
permissionCheck();
544
return entries.containsKey(alias.toLowerCase());
545
}
546
547
/**
548
* Retrieves the number of entries in this keystore.
549
*
550
* @return the number of entries in this keystore
551
*/
552
public int engineSize() {
553
permissionCheck();
554
return entries.size();
555
}
556
557
/**
558
* Returns true if the entry identified by the given alias is a
559
* <i>key entry</i>, and false otherwise.
560
*
561
* @return true if the entry identified by the given alias is a
562
* <i>key entry</i>, false otherwise.
563
*/
564
public boolean engineIsKeyEntry(String alias) {
565
permissionCheck();
566
Object entry = entries.get(alias.toLowerCase());
567
if ((entry != null) && (entry instanceof KeyEntry)) {
568
return true;
569
} else {
570
return false;
571
}
572
}
573
574
/**
575
* Returns true if the entry identified by the given alias is a
576
* <i>trusted certificate entry</i>, and false otherwise.
577
*
578
* @return true if the entry identified by the given alias is a
579
* <i>trusted certificate entry</i>, false otherwise.
580
*/
581
public boolean engineIsCertificateEntry(String alias) {
582
permissionCheck();
583
Object entry = entries.get(alias.toLowerCase());
584
if ((entry != null) && (entry instanceof TrustedCertEntry)) {
585
return true;
586
} else {
587
return false;
588
}
589
}
590
591
/**
592
* Returns the (alias) name of the first keystore entry whose certificate
593
* matches the given certificate.
594
*
595
* <p>This method attempts to match the given certificate with each
596
* keystore entry. If the entry being considered
597
* is a <i>trusted certificate entry</i>, the given certificate is
598
* compared to that entry's certificate. If the entry being considered is
599
* a <i>key entry</i>, the given certificate is compared to the first
600
* element of that entry's certificate chain (if a chain exists).
601
*
602
* @param cert the certificate to match with.
603
*
604
* @return the (alias) name of the first entry with matching certificate,
605
* or null if no such entry exists in this keystore.
606
*/
607
public String engineGetCertificateAlias(Certificate cert) {
608
permissionCheck();
609
Certificate certElem;
610
611
for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {
612
String alias = e.nextElement();
613
Object entry = entries.get(alias);
614
if (entry instanceof TrustedCertEntry) {
615
certElem = ((TrustedCertEntry)entry).cert;
616
} else {
617
KeyEntry ke = (KeyEntry)entry;
618
if (ke.chain == null || ke.chain.length == 0) {
619
continue;
620
}
621
certElem = ke.chain[0];
622
}
623
if (certElem.equals(cert)) {
624
return alias;
625
}
626
}
627
return null;
628
}
629
630
/**
631
* Stores this keystore to the given output stream, and protects its
632
* integrity with the given password.
633
*
634
* @param stream Ignored. the output stream to which this keystore is written.
635
* @param password the password to generate the keystore integrity check
636
*
637
* @exception IOException if there was an I/O problem with data
638
* @exception NoSuchAlgorithmException if the appropriate data integrity
639
* algorithm could not be found
640
* @exception CertificateException if any of the certificates included in
641
* the keystore data could not be stored
642
*/
643
public void engineStore(OutputStream stream, char[] password)
644
throws IOException, NoSuchAlgorithmException, CertificateException
645
{
646
permissionCheck();
647
648
// Delete items that do have a keychain item ref.
649
for (Enumeration<String> e = deletedEntries.keys(); e.hasMoreElements(); ) {
650
String alias = e.nextElement();
651
Object entry = deletedEntries.get(alias);
652
if (entry instanceof TrustedCertEntry) {
653
if (((TrustedCertEntry)entry).certRef != 0) {
654
_removeItemFromKeychain(((TrustedCertEntry)entry).certRef);
655
_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);
656
}
657
} else {
658
Certificate certElem;
659
KeyEntry keyEntry = (KeyEntry)entry;
660
661
if (keyEntry.chain != null) {
662
for (int i = 0; i < keyEntry.chain.length; i++) {
663
if (keyEntry.chainRefs[i] != 0) {
664
_removeItemFromKeychain(keyEntry.chainRefs[i]);
665
_releaseKeychainItemRef(keyEntry.chainRefs[i]);
666
}
667
}
668
669
if (keyEntry.keyRef != 0) {
670
_removeItemFromKeychain(keyEntry.keyRef);
671
_releaseKeychainItemRef(keyEntry.keyRef);
672
}
673
}
674
}
675
}
676
677
// Add all of the certs or keys in the added entries.
678
// No need to check for 0 refs, as they are in the added list.
679
for (Enumeration<String> e = addedEntries.keys(); e.hasMoreElements(); ) {
680
String alias = e.nextElement();
681
Object entry = addedEntries.get(alias);
682
if (entry instanceof TrustedCertEntry) {
683
TrustedCertEntry tce = (TrustedCertEntry)entry;
684
Certificate certElem;
685
certElem = tce.cert;
686
tce.certRef = addCertificateToKeychain(alias, certElem);
687
} else {
688
KeyEntry keyEntry = (KeyEntry)entry;
689
690
if (keyEntry.chain != null) {
691
for (int i = 0; i < keyEntry.chain.length; i++) {
692
keyEntry.chainRefs[i] = addCertificateToKeychain(alias, keyEntry.chain[i]);
693
}
694
695
keyEntry.keyRef = _addItemToKeychain(alias, false, keyEntry.protectedPrivKey, keyEntry.password);
696
}
697
}
698
}
699
700
// Clear the added and deletedEntries hashtables here, now that we're done with the updates.
701
// For the deleted entries, we freed up the native references above.
702
deletedEntries.clear();
703
addedEntries.clear();
704
}
705
706
private long addCertificateToKeychain(String alias, Certificate cert) {
707
byte[] certblob = null;
708
long returnValue = 0;
709
710
try {
711
certblob = cert.getEncoded();
712
returnValue = _addItemToKeychain(alias, true, certblob, null);
713
} catch (Exception e) {
714
e.printStackTrace();
715
}
716
717
return returnValue;
718
}
719
720
private native long _addItemToKeychain(String alias, boolean isCertificate, byte[] datablob, char[] password);
721
private native int _removeItemFromKeychain(long certRef);
722
private native void _releaseKeychainItemRef(long keychainItemRef);
723
724
/**
725
* Loads the keystore from the Keychain.
726
*
727
* @param stream Ignored - here for API compatibility.
728
* @param password Ignored - if user needs to unlock keychain Security
729
* framework will post any dialogs.
730
*
731
* @exception IOException if there is an I/O or format problem with the
732
* keystore data
733
* @exception NoSuchAlgorithmException if the algorithm used to check
734
* the integrity of the keystore cannot be found
735
* @exception CertificateException if any of the certificates in the
736
* keystore could not be loaded
737
*/
738
public void engineLoad(InputStream stream, char[] password)
739
throws IOException, NoSuchAlgorithmException, CertificateException
740
{
741
permissionCheck();
742
743
// Release any stray keychain references before clearing out the entries.
744
synchronized(entries) {
745
for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {
746
String alias = e.nextElement();
747
Object entry = entries.get(alias);
748
if (entry instanceof TrustedCertEntry) {
749
if (((TrustedCertEntry)entry).certRef != 0) {
750
_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);
751
}
752
} else {
753
KeyEntry keyEntry = (KeyEntry)entry;
754
755
if (keyEntry.chain != null) {
756
for (int i = 0; i < keyEntry.chain.length; i++) {
757
if (keyEntry.chainRefs[i] != 0) {
758
_releaseKeychainItemRef(keyEntry.chainRefs[i]);
759
}
760
}
761
762
if (keyEntry.keyRef != 0) {
763
_releaseKeychainItemRef(keyEntry.keyRef);
764
}
765
}
766
}
767
}
768
769
entries.clear();
770
_scanKeychain();
771
if (debug != null) {
772
debug.println("KeychainStore load entry count: " +
773
entries.size());
774
}
775
}
776
}
777
778
private native void _scanKeychain();
779
780
/**
781
* Callback method from _scanKeychain. If a trusted certificate is found, this method will be called.
782
*/
783
private void createTrustedCertEntry(String alias, long keychainItemRef, long creationDate, byte[] derStream) {
784
TrustedCertEntry tce = new TrustedCertEntry();
785
786
try {
787
CertificateFactory cf = CertificateFactory.getInstance("X.509");
788
InputStream input = new ByteArrayInputStream(derStream);
789
X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
790
input.close();
791
tce.cert = cert;
792
tce.certRef = keychainItemRef;
793
794
// Make a creation date.
795
if (creationDate != 0)
796
tce.date = new Date(creationDate);
797
else
798
tce.date = new Date();
799
800
int uniqueVal = 1;
801
String originalAlias = alias;
802
803
while (entries.containsKey(alias.toLowerCase())) {
804
alias = originalAlias + " " + uniqueVal;
805
uniqueVal++;
806
}
807
808
entries.put(alias.toLowerCase(), tce);
809
} catch (Exception e) {
810
// The certificate will be skipped.
811
System.err.println("KeychainStore Ignored Exception: " + e);
812
}
813
}
814
815
/**
816
* Callback method from _scanKeychain. If an identity is found, this method will be called to create Java certificate
817
* and private key objects from the keychain data.
818
*/
819
private void createKeyEntry(String alias, long creationDate, long secKeyRef,
820
long[] secCertificateRefs, byte[][] rawCertData) {
821
KeyEntry ke = new KeyEntry();
822
823
// First, store off the private key information. This is the easy part.
824
ke.protectedPrivKey = null;
825
ke.keyRef = secKeyRef;
826
827
// Make a creation date.
828
if (creationDate != 0)
829
ke.date = new Date(creationDate);
830
else
831
ke.date = new Date();
832
833
// Next, create X.509 Certificate objects from the raw data. This is complicated
834
// because a certificate's public key may be too long for Java's default encryption strength.
835
List<CertKeychainItemPair> createdCerts = new ArrayList<>();
836
837
try {
838
CertificateFactory cf = CertificateFactory.getInstance("X.509");
839
840
for (int i = 0; i < rawCertData.length; i++) {
841
try {
842
InputStream input = new ByteArrayInputStream(rawCertData[i]);
843
X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
844
input.close();
845
846
// We successfully created the certificate, so track it and its corresponding SecCertificateRef.
847
createdCerts.add(new CertKeychainItemPair(secCertificateRefs[i], cert));
848
} catch (CertificateException e) {
849
// The certificate will be skipped.
850
System.err.println("KeychainStore Ignored Exception: " + e);
851
}
852
}
853
} catch (CertificateException e) {
854
e.printStackTrace();
855
} catch (IOException ioe) {
856
ioe.printStackTrace(); // How would this happen?
857
}
858
859
// We have our certificates in the List, so now extract them into an array of
860
// Certificates and SecCertificateRefs.
861
CertKeychainItemPair[] objArray = createdCerts.toArray(new CertKeychainItemPair[0]);
862
Certificate[] certArray = new Certificate[objArray.length];
863
long[] certRefArray = new long[objArray.length];
864
865
for (int i = 0; i < objArray.length; i++) {
866
CertKeychainItemPair addedItem = objArray[i];
867
certArray[i] = addedItem.mCert;
868
certRefArray[i] = addedItem.mCertificateRef;
869
}
870
871
ke.chain = certArray;
872
ke.chainRefs = certRefArray;
873
874
// If we don't have already have an item with this item's alias
875
// create a new one for it.
876
int uniqueVal = 1;
877
String originalAlias = alias;
878
879
while (entries.containsKey(alias.toLowerCase())) {
880
alias = originalAlias + " " + uniqueVal;
881
uniqueVal++;
882
}
883
884
entries.put(alias.toLowerCase(), ke);
885
}
886
887
private static class CertKeychainItemPair {
888
long mCertificateRef;
889
Certificate mCert;
890
891
CertKeychainItemPair(long inCertRef, Certificate cert) {
892
mCertificateRef = inCertRef;
893
mCert = cert;
894
}
895
}
896
897
/*
898
* Validate Certificate Chain
899
*/
900
private boolean validateChain(Certificate[] certChain)
901
{
902
for (int i = 0; i < certChain.length-1; i++) {
903
X500Principal issuerDN =
904
((X509Certificate)certChain[i]).getIssuerX500Principal();
905
X500Principal subjectDN =
906
((X509Certificate)certChain[i+1]).getSubjectX500Principal();
907
if (!(issuerDN.equals(subjectDN)))
908
return false;
909
}
910
return true;
911
}
912
913
private byte[] fetchPrivateKeyFromBag(byte[] privateKeyInfo) throws IOException, NoSuchAlgorithmException, CertificateException
914
{
915
byte[] returnValue = null;
916
DerValue val = new DerValue(new ByteArrayInputStream(privateKeyInfo));
917
DerInputStream s = val.toDerInputStream();
918
int version = s.getInteger();
919
920
if (version != 3) {
921
throw new IOException("PKCS12 keystore not in version 3 format");
922
}
923
924
/*
925
* Read the authSafe.
926
*/
927
byte[] authSafeData;
928
ContentInfo authSafe = new ContentInfo(s);
929
ObjectIdentifier contentType = authSafe.getContentType();
930
931
if (contentType.equals(ContentInfo.DATA_OID)) {
932
authSafeData = authSafe.getData();
933
} else /* signed data */ {
934
throw new IOException("public key protected PKCS12 not supported");
935
}
936
937
DerInputStream as = new DerInputStream(authSafeData);
938
DerValue[] safeContentsArray = as.getSequence(2);
939
int count = safeContentsArray.length;
940
941
/*
942
* Spin over the ContentInfos.
943
*/
944
for (int i = 0; i < count; i++) {
945
byte[] safeContentsData;
946
ContentInfo safeContents;
947
DerInputStream sci;
948
byte[] eAlgId = null;
949
950
sci = new DerInputStream(safeContentsArray[i].toByteArray());
951
safeContents = new ContentInfo(sci);
952
contentType = safeContents.getContentType();
953
safeContentsData = null;
954
955
if (contentType.equals(ContentInfo.DATA_OID)) {
956
safeContentsData = safeContents.getData();
957
} else if (contentType.equals(ContentInfo.ENCRYPTED_DATA_OID)) {
958
// The password was used to export the private key from the keychain.
959
// The Keychain won't export the key with encrypted data, so we don't need
960
// to worry about it.
961
continue;
962
} else {
963
throw new IOException("public key protected PKCS12" +
964
" not supported");
965
}
966
DerInputStream sc = new DerInputStream(safeContentsData);
967
returnValue = extractKeyData(sc);
968
}
969
970
return returnValue;
971
}
972
973
private byte[] extractKeyData(DerInputStream stream)
974
throws IOException, NoSuchAlgorithmException, CertificateException
975
{
976
byte[] returnValue = null;
977
DerValue[] safeBags = stream.getSequence(2);
978
int count = safeBags.length;
979
980
/*
981
* Spin over the SafeBags.
982
*/
983
for (int i = 0; i < count; i++) {
984
ObjectIdentifier bagId;
985
DerInputStream sbi;
986
DerValue bagValue;
987
Object bagItem = null;
988
989
sbi = safeBags[i].toDerInputStream();
990
bagId = sbi.getOID();
991
bagValue = sbi.getDerValue();
992
if (!bagValue.isContextSpecific((byte)0)) {
993
throw new IOException("unsupported PKCS12 bag value type "
994
+ bagValue.tag);
995
}
996
bagValue = bagValue.data.getDerValue();
997
if (bagId.equals(PKCS8ShroudedKeyBag_OID)) {
998
// got what we were looking for. Return it.
999
returnValue = bagValue.toByteArray();
1000
} else {
1001
// log error message for "unsupported PKCS12 bag type"
1002
System.out.println("Unsupported bag type '" + bagId + "'");
1003
}
1004
}
1005
1006
return returnValue;
1007
}
1008
1009
/*
1010
* Generate PBE Algorithm Parameters
1011
*/
1012
private AlgorithmParameters getAlgorithmParameters(String algorithm)
1013
throws IOException
1014
{
1015
AlgorithmParameters algParams = null;
1016
1017
// create PBE parameters from salt and iteration count
1018
PBEParameterSpec paramSpec =
1019
new PBEParameterSpec(getSalt(), iterationCount);
1020
try {
1021
algParams = AlgorithmParameters.getInstance(algorithm);
1022
algParams.init(paramSpec);
1023
} catch (Exception e) {
1024
IOException ioe =
1025
new IOException("getAlgorithmParameters failed: " +
1026
e.getMessage());
1027
ioe.initCause(e);
1028
throw ioe;
1029
}
1030
return algParams;
1031
}
1032
1033
// the source of randomness
1034
private SecureRandom random;
1035
1036
/*
1037
* Generate random salt
1038
*/
1039
private byte[] getSalt()
1040
{
1041
// Generate a random salt.
1042
byte[] salt = new byte[SALT_LEN];
1043
if (random == null) {
1044
random = new SecureRandom();
1045
}
1046
random.nextBytes(salt);
1047
return salt;
1048
}
1049
1050
/*
1051
* parse Algorithm Parameters
1052
*/
1053
private AlgorithmParameters parseAlgParameters(DerInputStream in)
1054
throws IOException
1055
{
1056
AlgorithmParameters algParams = null;
1057
try {
1058
DerValue params;
1059
if (in.available() == 0) {
1060
params = null;
1061
} else {
1062
params = in.getDerValue();
1063
if (params.tag == DerValue.tag_Null) {
1064
params = null;
1065
}
1066
}
1067
if (params != null) {
1068
algParams = AlgorithmParameters.getInstance("PBE");
1069
algParams.init(params.toByteArray());
1070
}
1071
} catch (Exception e) {
1072
IOException ioe =
1073
new IOException("parseAlgParameters failed: " +
1074
e.getMessage());
1075
ioe.initCause(e);
1076
throw ioe;
1077
}
1078
return algParams;
1079
}
1080
1081
/*
1082
* Generate PBE key
1083
*/
1084
private SecretKey getPBEKey(char[] password) throws IOException
1085
{
1086
SecretKey skey = null;
1087
1088
try {
1089
PBEKeySpec keySpec = new PBEKeySpec(password);
1090
SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
1091
skey = skFac.generateSecret(keySpec);
1092
} catch (Exception e) {
1093
IOException ioe = new IOException("getSecretKey failed: " +
1094
e.getMessage());
1095
ioe.initCause(e);
1096
throw ioe;
1097
}
1098
return skey;
1099
}
1100
1101
/*
1102
* Encrypt private key using Password-based encryption (PBE)
1103
* as defined in PKCS#5.
1104
*
1105
* NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
1106
* used to derive the key and IV.
1107
*
1108
* @return encrypted private key encoded as EncryptedPrivateKeyInfo
1109
*/
1110
private byte[] encryptPrivateKey(byte[] data, char[] password)
1111
throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException
1112
{
1113
byte[] key = null;
1114
1115
try {
1116
// create AlgorithmParameters
1117
AlgorithmParameters algParams =
1118
getAlgorithmParameters("PBEWithSHA1AndDESede");
1119
1120
// Use JCE
1121
SecretKey skey = getPBEKey(password);
1122
Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
1123
cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
1124
byte[] encryptedKey = cipher.doFinal(data);
1125
1126
// wrap encrypted private key in EncryptedPrivateKeyInfo
1127
// as defined in PKCS#8
1128
AlgorithmId algid =
1129
new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams);
1130
EncryptedPrivateKeyInfo encrInfo =
1131
new EncryptedPrivateKeyInfo(algid, encryptedKey);
1132
key = encrInfo.getEncoded();
1133
} catch (Exception e) {
1134
UnrecoverableKeyException uke =
1135
new UnrecoverableKeyException("Encrypt Private Key failed: "
1136
+ e.getMessage());
1137
uke.initCause(e);
1138
throw uke;
1139
}
1140
1141
return key;
1142
}
1143
1144
1145
}
1146
1147
1148