Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/security/provider/JavaKeyStore.java
41159 views
1
/*
2
* Copyright (c) 1997, 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 sun.security.provider;
27
28
import java.io.*;
29
import java.security.*;
30
import java.security.cert.Certificate;
31
import java.security.cert.CertificateFactory;
32
import java.security.cert.CertificateException;
33
import java.util.*;
34
35
import static java.nio.charset.StandardCharsets.UTF_8;
36
37
import sun.security.pkcs.EncryptedPrivateKeyInfo;
38
import sun.security.pkcs12.PKCS12KeyStore;
39
import sun.security.util.Debug;
40
import sun.security.util.IOUtils;
41
import sun.security.util.KeyStoreDelegator;
42
43
/**
44
* This class provides the keystore implementation referred to as "JKS".
45
*
46
* @author Jan Luehe
47
* @author David Brownell
48
*
49
*
50
* @see KeyProtector
51
* @see java.security.KeyStoreSpi
52
* @see KeyTool
53
*
54
* @since 1.2
55
*/
56
57
public abstract class JavaKeyStore extends KeyStoreSpi {
58
59
// regular JKS
60
public static final class JKS extends JavaKeyStore {
61
String convertAlias(String alias) {
62
return alias.toLowerCase(Locale.ENGLISH);
63
}
64
}
65
66
// special JKS that uses case sensitive aliases
67
public static final class CaseExactJKS extends JavaKeyStore {
68
String convertAlias(String alias) {
69
return alias;
70
}
71
}
72
73
// special JKS that supports JKS and PKCS12 file formats
74
public static final class DualFormatJKS extends KeyStoreDelegator {
75
public DualFormatJKS() {
76
super("JKS", JKS.class, "PKCS12", PKCS12KeyStore.class);
77
}
78
79
/**
80
* Probe the first few bytes of the keystore data stream for a valid
81
* JKS keystore encoding.
82
*/
83
@Override
84
public boolean engineProbe(InputStream stream) throws IOException {
85
DataInputStream dataStream;
86
if (stream instanceof DataInputStream) {
87
dataStream = (DataInputStream)stream;
88
} else {
89
dataStream = new DataInputStream(stream);
90
}
91
92
return MAGIC == dataStream.readInt();
93
}
94
}
95
96
private static final Debug debug = Debug.getInstance("keystore");
97
private static final int MAGIC = 0xfeedfeed;
98
private static final int VERSION_1 = 0x01;
99
private static final int VERSION_2 = 0x02;
100
101
// Private keys and their supporting certificate chains
102
private static class KeyEntry {
103
Date date; // the creation date of this entry
104
byte[] protectedPrivKey;
105
Certificate[] chain;
106
};
107
108
// Trusted certificates
109
private static class TrustedCertEntry {
110
Date date; // the creation date of this entry
111
Certificate cert;
112
};
113
114
/**
115
* Private keys and certificates are stored in a hashtable.
116
* Hash entries are keyed by alias names.
117
*/
118
private final Hashtable<String, Object> entries;
119
120
JavaKeyStore() {
121
entries = new Hashtable<String, Object>();
122
}
123
124
// convert an alias to internal form, overridden in subclasses:
125
// lower case for regular JKS
126
// original string for CaseExactJKS
127
abstract String convertAlias(String alias);
128
129
/**
130
* Returns the key associated with the given alias, using the given
131
* password to recover it.
132
*
133
* @param alias the alias name
134
* @param password the password for recovering the key
135
*
136
* @return the requested key, or null if the given alias does not exist
137
* or does not identify a <i>key entry</i>.
138
*
139
* @exception NoSuchAlgorithmException if the algorithm for recovering the
140
* key cannot be found
141
* @exception UnrecoverableKeyException if the key cannot be recovered
142
* (e.g., the given password is wrong).
143
*/
144
public Key engineGetKey(String alias, char[] password)
145
throws NoSuchAlgorithmException, UnrecoverableKeyException
146
{
147
Object entry = entries.get(convertAlias(alias));
148
149
if (entry == null || !(entry instanceof KeyEntry)) {
150
return null;
151
}
152
if (password == null) {
153
throw new UnrecoverableKeyException("Password must not be null");
154
}
155
156
byte[] passwordBytes = convertToBytes(password);
157
KeyProtector keyProtector = new KeyProtector(passwordBytes);
158
byte[] encrBytes = ((KeyEntry)entry).protectedPrivKey;
159
EncryptedPrivateKeyInfo encrInfo;
160
try {
161
encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
162
return keyProtector.recover(encrInfo);
163
} catch (IOException ioe) {
164
throw new UnrecoverableKeyException("Private key not stored as "
165
+ "PKCS #8 "
166
+ "EncryptedPrivateKeyInfo");
167
} finally {
168
Arrays.fill(passwordBytes, (byte) 0x00);
169
}
170
}
171
172
/**
173
* Returns the certificate chain associated with the given alias.
174
*
175
* @param alias the alias name
176
*
177
* @return the certificate chain (ordered with the user's certificate first
178
* and the root certificate authority last), or null if the given alias
179
* does not exist or does not contain a certificate chain (i.e., the given
180
* alias identifies either a <i>trusted certificate entry</i> or a
181
* <i>key entry</i> without a certificate chain).
182
*/
183
public Certificate[] engineGetCertificateChain(String alias) {
184
Object entry = entries.get(convertAlias(alias));
185
186
if (entry != null && entry instanceof KeyEntry) {
187
if (((KeyEntry)entry).chain == null) {
188
return null;
189
} else {
190
return ((KeyEntry)entry).chain.clone();
191
}
192
} else {
193
return null;
194
}
195
}
196
197
/**
198
* Returns the certificate associated with the given alias.
199
*
200
* <p>If the given alias name identifies a
201
* <i>trusted certificate entry</i>, the certificate associated with that
202
* entry is returned. If the given alias name identifies a
203
* <i>key entry</i>, the first element of the certificate chain of that
204
* entry is returned, or null if that entry does not have a certificate
205
* chain.
206
*
207
* @param alias the alias name
208
*
209
* @return the certificate, or null if the given alias does not exist or
210
* does not contain a certificate.
211
*/
212
public Certificate engineGetCertificate(String alias) {
213
Object entry = entries.get(convertAlias(alias));
214
215
if (entry != null) {
216
if (entry instanceof TrustedCertEntry) {
217
return ((TrustedCertEntry)entry).cert;
218
} else {
219
if (((KeyEntry)entry).chain == null) {
220
return null;
221
} else {
222
return ((KeyEntry)entry).chain[0];
223
}
224
}
225
} else {
226
return null;
227
}
228
}
229
230
/**
231
* Returns the creation date of the entry identified by the given alias.
232
*
233
* @param alias the alias name
234
*
235
* @return the creation date of this entry, or null if the given alias does
236
* not exist
237
*/
238
public Date engineGetCreationDate(String alias) {
239
Object entry = entries.get(convertAlias(alias));
240
241
if (entry != null) {
242
if (entry instanceof TrustedCertEntry) {
243
return new Date(((TrustedCertEntry)entry).date.getTime());
244
} else {
245
return new Date(((KeyEntry)entry).date.getTime());
246
}
247
} else {
248
return null;
249
}
250
}
251
252
/**
253
* Assigns the given private key to the given alias, protecting
254
* it with the given password as defined in PKCS8.
255
*
256
* <p>The given java.security.PrivateKey <code>key</code> must
257
* be accompanied by a certificate chain certifying the
258
* corresponding public key.
259
*
260
* <p>If the given alias already exists, the keystore information
261
* associated with it is overridden by the given key and certificate
262
* chain.
263
*
264
* @param alias the alias name
265
* @param key the private key to be associated with the alias
266
* @param password the password to protect the key
267
* @param chain the certificate chain for the corresponding public
268
* key (only required if the given key is of type
269
* <code>java.security.PrivateKey</code>).
270
*
271
* @exception KeyStoreException if the given key is not a private key,
272
* cannot be protected, or this operation fails for some other reason
273
*/
274
public void engineSetKeyEntry(String alias, Key key, char[] password,
275
Certificate[] chain)
276
throws KeyStoreException
277
{
278
KeyProtector keyProtector;
279
byte[] passwordBytes = null;
280
281
if (!(key instanceof java.security.PrivateKey)) {
282
throw new KeyStoreException("Cannot store non-PrivateKeys");
283
}
284
if (password == null) {
285
throw new KeyStoreException("password can't be null");
286
}
287
try {
288
synchronized(entries) {
289
KeyEntry entry = new KeyEntry();
290
entry.date = new Date();
291
292
// Protect the encoding of the key
293
passwordBytes = convertToBytes(password);
294
keyProtector = new KeyProtector(passwordBytes);
295
entry.protectedPrivKey = keyProtector.protect(key);
296
297
// clone the chain
298
if ((chain != null) &&
299
(chain.length != 0)) {
300
entry.chain = chain.clone();
301
} else {
302
entry.chain = null;
303
}
304
305
entries.put(convertAlias(alias), entry);
306
}
307
} catch (NoSuchAlgorithmException nsae) {
308
throw new KeyStoreException("Key protection algorithm not found");
309
} finally {
310
if (passwordBytes != null)
311
Arrays.fill(passwordBytes, (byte) 0x00);
312
}
313
}
314
315
/**
316
* Assigns the given key (that has already been protected) to the given
317
* alias.
318
*
319
* <p>If the protected key is of type
320
* <code>java.security.PrivateKey</code>, it must be accompanied by a
321
* certificate chain certifying the corresponding public key. If the
322
* underlying keystore implementation is of type <code>jks</code>,
323
* <code>key</code> must be encoded as an
324
* <code>EncryptedPrivateKeyInfo</code> as defined in the PKCS #8 standard.
325
*
326
* <p>If the given alias already exists, the keystore information
327
* associated with it is overridden by the given key (and possibly
328
* certificate chain).
329
*
330
* @param alias the alias name
331
* @param key the key (in protected format) to be associated with the alias
332
* @param chain the certificate chain for the corresponding public
333
* key (only useful if the protected key is of type
334
* <code>java.security.PrivateKey</code>).
335
*
336
* @exception KeyStoreException if this operation fails.
337
*/
338
public void engineSetKeyEntry(String alias, byte[] key,
339
Certificate[] chain)
340
throws KeyStoreException
341
{
342
synchronized(entries) {
343
// key must be encoded as EncryptedPrivateKeyInfo as defined in
344
// PKCS#8
345
try {
346
new EncryptedPrivateKeyInfo(key);
347
} catch (IOException ioe) {
348
throw new KeyStoreException("key is not encoded as "
349
+ "EncryptedPrivateKeyInfo");
350
}
351
352
KeyEntry entry = new KeyEntry();
353
entry.date = new Date();
354
355
entry.protectedPrivKey = key.clone();
356
if ((chain != null) &&
357
(chain.length != 0)) {
358
entry.chain = chain.clone();
359
} else {
360
entry.chain = null;
361
}
362
363
entries.put(convertAlias(alias), entry);
364
}
365
}
366
367
/**
368
* Assigns the given certificate to the given alias.
369
*
370
* <p>If the given alias already exists in this keystore and identifies a
371
* <i>trusted certificate entry</i>, the certificate associated with it is
372
* overridden by the given certificate.
373
*
374
* @param alias the alias name
375
* @param cert the certificate
376
*
377
* @exception KeyStoreException if the given alias already exists and does
378
* not identify a <i>trusted certificate entry</i>, or this operation
379
* fails for some other reason.
380
*/
381
public void engineSetCertificateEntry(String alias, Certificate cert)
382
throws KeyStoreException
383
{
384
synchronized(entries) {
385
386
Object entry = entries.get(convertAlias(alias));
387
if ((entry != null) && (entry instanceof KeyEntry)) {
388
throw new KeyStoreException
389
("Cannot overwrite own certificate");
390
}
391
392
TrustedCertEntry trustedCertEntry = new TrustedCertEntry();
393
trustedCertEntry.cert = cert;
394
trustedCertEntry.date = new Date();
395
entries.put(convertAlias(alias), trustedCertEntry);
396
}
397
}
398
399
/**
400
* Deletes the entry identified by the given alias from this keystore.
401
*
402
* @param alias the alias name
403
*
404
* @exception KeyStoreException if the entry cannot be removed.
405
*/
406
public void engineDeleteEntry(String alias)
407
throws KeyStoreException
408
{
409
synchronized(entries) {
410
entries.remove(convertAlias(alias));
411
}
412
}
413
414
/**
415
* Lists all the alias names of this keystore.
416
*
417
* @return enumeration of the alias names
418
*/
419
public Enumeration<String> engineAliases() {
420
return entries.keys();
421
}
422
423
/**
424
* Checks if the given alias exists in this keystore.
425
*
426
* @param alias the alias name
427
*
428
* @return true if the alias exists, false otherwise
429
*/
430
public boolean engineContainsAlias(String alias) {
431
return entries.containsKey(convertAlias(alias));
432
}
433
434
/**
435
* Retrieves the number of entries in this keystore.
436
*
437
* @return the number of entries in this keystore
438
*/
439
public int engineSize() {
440
return entries.size();
441
}
442
443
/**
444
* Returns true if the entry identified by the given alias is a
445
* <i>key entry</i>, and false otherwise.
446
*
447
* @return true if the entry identified by the given alias is a
448
* <i>key entry</i>, false otherwise.
449
*/
450
public boolean engineIsKeyEntry(String alias) {
451
Object entry = entries.get(convertAlias(alias));
452
if ((entry != null) && (entry instanceof KeyEntry)) {
453
return true;
454
} else {
455
return false;
456
}
457
}
458
459
/**
460
* Returns true if the entry identified by the given alias is a
461
* <i>trusted certificate entry</i>, and false otherwise.
462
*
463
* @return true if the entry identified by the given alias is a
464
* <i>trusted certificate entry</i>, false otherwise.
465
*/
466
public boolean engineIsCertificateEntry(String alias) {
467
Object entry = entries.get(convertAlias(alias));
468
if ((entry != null) && (entry instanceof TrustedCertEntry)) {
469
return true;
470
} else {
471
return false;
472
}
473
}
474
475
/**
476
* Returns the (alias) name of the first keystore entry whose certificate
477
* matches the given certificate.
478
*
479
* <p>This method attempts to match the given certificate with each
480
* keystore entry. If the entry being considered
481
* is a <i>trusted certificate entry</i>, the given certificate is
482
* compared to that entry's certificate. If the entry being considered is
483
* a <i>key entry</i>, the given certificate is compared to the first
484
* element of that entry's certificate chain (if a chain exists).
485
*
486
* @param cert the certificate to match with.
487
*
488
* @return the (alias) name of the first entry with matching certificate,
489
* or null if no such entry exists in this keystore.
490
*/
491
public String engineGetCertificateAlias(Certificate cert) {
492
Certificate certElem;
493
494
for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {
495
String alias = e.nextElement();
496
Object entry = entries.get(alias);
497
if (entry instanceof TrustedCertEntry) {
498
certElem = ((TrustedCertEntry)entry).cert;
499
} else if (((KeyEntry)entry).chain != null) {
500
certElem = ((KeyEntry)entry).chain[0];
501
} else {
502
continue;
503
}
504
if (certElem.equals(cert)) {
505
return alias;
506
}
507
}
508
return null;
509
}
510
511
/**
512
* Stores this keystore to the given output stream, and protects its
513
* integrity with the given password.
514
*
515
* @param stream the output stream to which this keystore is written.
516
* @param password the password to generate the keystore integrity check
517
*
518
* @exception IOException if there was an I/O problem with data
519
* @exception NoSuchAlgorithmException if the appropriate data integrity
520
* algorithm could not be found
521
* @exception CertificateException if any of the certificates included in
522
* the keystore data could not be stored
523
*/
524
public void engineStore(OutputStream stream, char[] password)
525
throws IOException, NoSuchAlgorithmException, CertificateException
526
{
527
synchronized(entries) {
528
/*
529
* KEYSTORE FORMAT:
530
*
531
* Magic number (big-endian integer),
532
* Version of this file format (big-endian integer),
533
*
534
* Count (big-endian integer),
535
* followed by "count" instances of either:
536
*
537
* {
538
* tag=1 (big-endian integer),
539
* alias (UTF string)
540
* timestamp
541
* encrypted private-key info according to PKCS #8
542
* (integer length followed by encoding)
543
* cert chain (integer count, then certs; for each cert,
544
* integer length followed by encoding)
545
* }
546
*
547
* or:
548
*
549
* {
550
* tag=2 (big-endian integer)
551
* alias (UTF string)
552
* timestamp
553
* cert (integer length followed by encoding)
554
* }
555
*
556
* ended by a keyed SHA1 hash (bytes only) of
557
* { password + extra data + preceding body }
558
*/
559
560
// password is mandatory when storing
561
if (password == null) {
562
throw new IllegalArgumentException("password can't be null");
563
}
564
565
byte[] encoded; // the certificate encoding
566
567
MessageDigest md = getPreKeyedHash(password);
568
DataOutputStream dos
569
= new DataOutputStream(new DigestOutputStream(stream, md));
570
571
dos.writeInt(MAGIC);
572
// always write the latest version
573
dos.writeInt(VERSION_2);
574
575
dos.writeInt(entries.size());
576
577
for (Enumeration<String> e = entries.keys(); e.hasMoreElements();) {
578
579
String alias = e.nextElement();
580
Object entry = entries.get(alias);
581
582
if (entry instanceof KeyEntry) {
583
584
// Store this entry as a KeyEntry
585
dos.writeInt(1);
586
587
// Write the alias
588
dos.writeUTF(alias);
589
590
// Write the (entry creation) date
591
dos.writeLong(((KeyEntry)entry).date.getTime());
592
593
// Write the protected private key
594
dos.writeInt(((KeyEntry)entry).protectedPrivKey.length);
595
dos.write(((KeyEntry)entry).protectedPrivKey);
596
597
// Write the certificate chain
598
int chainLen;
599
if (((KeyEntry)entry).chain == null) {
600
chainLen = 0;
601
} else {
602
chainLen = ((KeyEntry)entry).chain.length;
603
}
604
dos.writeInt(chainLen);
605
for (int i = 0; i < chainLen; i++) {
606
encoded = ((KeyEntry)entry).chain[i].getEncoded();
607
dos.writeUTF(((KeyEntry)entry).chain[i].getType());
608
dos.writeInt(encoded.length);
609
dos.write(encoded);
610
}
611
} else {
612
613
// Store this entry as a certificate
614
dos.writeInt(2);
615
616
// Write the alias
617
dos.writeUTF(alias);
618
619
// Write the (entry creation) date
620
dos.writeLong(((TrustedCertEntry)entry).date.getTime());
621
622
// Write the trusted certificate
623
encoded = ((TrustedCertEntry)entry).cert.getEncoded();
624
dos.writeUTF(((TrustedCertEntry)entry).cert.getType());
625
dos.writeInt(encoded.length);
626
dos.write(encoded);
627
}
628
}
629
630
/*
631
* Write the keyed hash which is used to detect tampering with
632
* the keystore (such as deleting or modifying key or
633
* certificate entries).
634
*/
635
byte[] digest = md.digest();
636
637
dos.write(digest);
638
dos.flush();
639
}
640
}
641
642
/**
643
* Loads the keystore from the given input stream.
644
*
645
* <p>If a password is given, it is used to check the integrity of the
646
* keystore data. Otherwise, the integrity of the keystore is not checked.
647
*
648
* @param stream the input stream from which the keystore is loaded
649
* @param password the (optional) password used to check the integrity of
650
* the keystore.
651
*
652
* @exception IOException if there is an I/O or format problem with the
653
* keystore data
654
* @exception NoSuchAlgorithmException if the algorithm used to check
655
* the integrity of the keystore cannot be found
656
* @exception CertificateException if any of the certificates in the
657
* keystore could not be loaded
658
*/
659
public void engineLoad(InputStream stream, char[] password)
660
throws IOException, NoSuchAlgorithmException, CertificateException
661
{
662
synchronized(entries) {
663
DataInputStream dis;
664
MessageDigest md = null;
665
CertificateFactory cf = null;
666
Hashtable<String, CertificateFactory> cfs = null;
667
ByteArrayInputStream bais = null;
668
byte[] encoded = null;
669
int trustedKeyCount = 0, privateKeyCount = 0;
670
671
if (stream == null)
672
return;
673
674
if (password != null) {
675
md = getPreKeyedHash(password);
676
dis = new DataInputStream(new DigestInputStream(stream, md));
677
} else {
678
dis = new DataInputStream(stream);
679
}
680
681
// Body format: see store method
682
683
int xMagic = dis.readInt();
684
int xVersion = dis.readInt();
685
686
if (xMagic!=MAGIC ||
687
(xVersion!=VERSION_1 && xVersion!=VERSION_2)) {
688
throw new IOException("Invalid keystore format");
689
}
690
691
if (xVersion == VERSION_1) {
692
cf = CertificateFactory.getInstance("X509");
693
} else {
694
// version 2
695
cfs = new Hashtable<String, CertificateFactory>(3);
696
}
697
698
entries.clear();
699
int count = dis.readInt();
700
701
for (int i = 0; i < count; i++) {
702
int tag;
703
String alias;
704
705
tag = dis.readInt();
706
707
if (tag == 1) { // private key entry
708
privateKeyCount++;
709
KeyEntry entry = new KeyEntry();
710
711
// Read the alias
712
alias = dis.readUTF();
713
714
// Read the (entry creation) date
715
entry.date = new Date(dis.readLong());
716
717
// Read the private key
718
entry.protectedPrivKey =
719
IOUtils.readExactlyNBytes(dis, dis.readInt());
720
721
// Read the certificate chain
722
int numOfCerts = dis.readInt();
723
if (numOfCerts > 0) {
724
List<Certificate> certs = new ArrayList<>(
725
numOfCerts > 10 ? 10 : numOfCerts);
726
for (int j = 0; j < numOfCerts; j++) {
727
if (xVersion == 2) {
728
// read the certificate type, and instantiate a
729
// certificate factory of that type (reuse
730
// existing factory if possible)
731
String certType = dis.readUTF();
732
if (cfs.containsKey(certType)) {
733
// reuse certificate factory
734
cf = cfs.get(certType);
735
} else {
736
// create new certificate factory
737
cf = CertificateFactory.getInstance(certType);
738
// store the certificate factory so we can
739
// reuse it later
740
cfs.put(certType, cf);
741
}
742
}
743
// instantiate the certificate
744
encoded = IOUtils.readExactlyNBytes(dis, dis.readInt());
745
bais = new ByteArrayInputStream(encoded);
746
certs.add(cf.generateCertificate(bais));
747
bais.close();
748
}
749
// We can be sure now that numOfCerts of certs are read
750
entry.chain = certs.toArray(new Certificate[numOfCerts]);
751
}
752
753
// Add the entry to the list
754
entries.put(alias, entry);
755
756
} else if (tag == 2) { // trusted certificate entry
757
trustedKeyCount++;
758
TrustedCertEntry entry = new TrustedCertEntry();
759
760
// Read the alias
761
alias = dis.readUTF();
762
763
// Read the (entry creation) date
764
entry.date = new Date(dis.readLong());
765
766
// Read the trusted certificate
767
if (xVersion == 2) {
768
// read the certificate type, and instantiate a
769
// certificate factory of that type (reuse
770
// existing factory if possible)
771
String certType = dis.readUTF();
772
if (cfs.containsKey(certType)) {
773
// reuse certificate factory
774
cf = cfs.get(certType);
775
} else {
776
// create new certificate factory
777
cf = CertificateFactory.getInstance(certType);
778
// store the certificate factory so we can
779
// reuse it later
780
cfs.put(certType, cf);
781
}
782
}
783
encoded = IOUtils.readExactlyNBytes(dis, dis.readInt());
784
bais = new ByteArrayInputStream(encoded);
785
entry.cert = cf.generateCertificate(bais);
786
bais.close();
787
788
// Add the entry to the list
789
entries.put(alias, entry);
790
791
} else {
792
throw new IOException("Unrecognized keystore entry: " +
793
tag);
794
}
795
}
796
797
if (debug != null) {
798
debug.println("JavaKeyStore load: private key count: " +
799
privateKeyCount + ". trusted key count: " + trustedKeyCount);
800
}
801
802
/*
803
* If a password has been provided, we check the keyed digest
804
* at the end. If this check fails, the store has been tampered
805
* with
806
*/
807
if (password != null) {
808
byte[] computed = md.digest();
809
byte[] actual = IOUtils.readExactlyNBytes(dis, computed.length);
810
if (!MessageDigest.isEqual(computed, actual)) {
811
Throwable t = new UnrecoverableKeyException
812
("Password verification failed");
813
throw (IOException) new IOException
814
("Keystore was tampered with, or "
815
+ "password was incorrect").initCause(t);
816
}
817
}
818
}
819
}
820
821
/**
822
* To guard against tampering with the keystore, we append a keyed
823
* hash with a bit of extra data.
824
*/
825
private MessageDigest getPreKeyedHash(char[] password)
826
throws NoSuchAlgorithmException
827
{
828
829
MessageDigest md = MessageDigest.getInstance("SHA");
830
byte[] passwdBytes = convertToBytes(password);
831
md.update(passwdBytes);
832
Arrays.fill(passwdBytes, (byte) 0x00);
833
md.update("Mighty Aphrodite".getBytes(UTF_8));
834
return md;
835
}
836
837
/**
838
* Helper method to convert char[] to byte[]
839
*/
840
841
private byte[] convertToBytes(char[] password) {
842
int i, j;
843
byte[] passwdBytes = new byte[password.length * 2];
844
for (i=0, j=0; i<password.length; i++) {
845
passwdBytes[j++] = (byte)(password[i] >> 8);
846
passwdBytes[j++] = (byte)password[i];
847
}
848
return passwdBytes;
849
}
850
}
851
852