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