PKCS12KeyStore.java 91.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28
 */

package sun.security.pkcs12;

import java.io.*;
29
import java.security.AccessController;
D
duke 已提交
30 31 32 33
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Key;
import java.security.KeyFactory;
V
vinnie 已提交
34
import java.security.KeyStore;
D
duke 已提交
35 36
import java.security.KeyStoreSpi;
import java.security.KeyStoreException;
V
vinnie 已提交
37 38 39
import java.security.PKCS12Attribute;
import java.security.PrivateKey;
import java.security.PrivilegedAction;
40
import java.security.UnrecoverableEntryException;
D
duke 已提交
41 42
import java.security.UnrecoverableKeyException;
import java.security.SecureRandom;
V
vinnie 已提交
43
import java.security.Security;
D
duke 已提交
44 45 46 47
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
48
import java.security.spec.AlgorithmParameterSpec;
49
import java.security.spec.InvalidParameterSpecException;
V
vinnie 已提交
50
import java.security.spec.KeySpec;
D
duke 已提交
51 52 53 54
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;

import java.security.AlgorithmParameters;
55
import java.security.InvalidAlgorithmParameterException;
D
duke 已提交
56 57
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.PBEKeySpec;
V
vinnie 已提交
58
import javax.crypto.spec.SecretKeySpec;
D
duke 已提交
59 60 61 62
import javax.crypto.SecretKeyFactory;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.Mac;
63
import javax.security.auth.DestroyFailedException;
D
duke 已提交
64 65
import javax.security.auth.x500.X500Principal;

66
import sun.security.util.Debug;
D
duke 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
import sun.security.util.ObjectIdentifier;
import sun.security.pkcs.ContentInfo;
import sun.security.x509.AlgorithmId;
import sun.security.pkcs.EncryptedPrivateKeyInfo;


/**
 * This class provides the keystore implementation referred to as "PKCS12".
 * Implements the PKCS#12 PFX protected using the Password privacy mode.
 * The contents are protected using Password integrity mode.
 *
 * Currently we support following PBE algorithms:
 *  - pbeWithSHAAnd3KeyTripleDESCBC to encrypt private keys
 *  - pbeWithSHAAnd40BitRC2CBC to encrypt certificates
 *
 * Supported encryption of various implementations :
 *
 * Software and mode.     Certificate encryption  Private key encryption
 * ---------------------------------------------------------------------
 * MSIE4 (domestic            40 bit RC2.            40 bit RC2
 * and xport versions)
 * PKCS#12 export.
 *
 * MSIE4, 5 (domestic         40 bit RC2,            40 bit RC2,
 * and export versions)       3 key triple DES       3 key triple DES
 * PKCS#12 import.
 *
 * MSIE5                      40 bit RC2             3 key triple DES,
 * PKCS#12 export.                                   with SHA1 (168 bits)
 *
 * Netscape Communicator      40 bit RC2             3 key triple DES,
 * (domestic and export                              with SHA1 (168 bits)
 * versions) PKCS#12 export
 *
 * Netscape Communicator      40 bit ciphers only    All.
 * (export version)
 * PKCS#12 import.
 *
 * Netscape Communicator      All.                   All.
 * (domestic or fortified
 * version) PKCS#12 import.
 *
 * OpenSSL PKCS#12 code.      All.                   All.
 * ---------------------------------------------------------------------
 *
V
vinnie 已提交
115
 * NOTE: PKCS12 KeyStore supports PrivateKeyEntry and TrustedCertficateEntry.
D
duke 已提交
116 117 118
 * PKCS#12 is mainly used to deliver private keys with their associated
 * certificate chain and aliases. In a PKCS12 keystore, entries are
 * identified by the alias, and a localKeyId is required to match the
V
vinnie 已提交
119 120
 * private key with the certificate. Trusted certificate entries are identified
 * by the presence of an trustedKeyUsage attribute.
D
duke 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
 *
 * @author Seema Malkani
 * @author Jeff Nisewanger
 * @author Jan Luehe
 *
 * @see KeyProtector
 * @see java.security.KeyStoreSpi
 * @see KeyTool
 *
 *
 */
public final class PKCS12KeyStore extends KeyStoreSpi {

    public static final int VERSION_3 = 3;

136 137 138 139 140
    private static final String[] KEY_PROTECTION_ALGORITHM = {
        "keystore.pkcs12.keyProtectionAlgorithm",
        "keystore.PKCS12.keyProtectionAlgorithm"
    };

141 142 143 144 145
    private static final int MAX_ITERATION_COUNT = 5000000;
    private static final int PBE_ITERATION_COUNT = 50000; // default
    private static final int MAC_ITERATION_COUNT = 100000; // default
    private static final int SALT_LEN = 20;

146 147 148 149 150 151 152
    // friendlyName, localKeyId, trustedKeyUsage
    private static final String[] CORE_ATTRIBUTES = {
        "1.2.840.113549.1.9.20",
        "1.2.840.113549.1.9.21",
        "2.16.840.1.113894.746875.1.1"
    };

153 154
    private static final Debug debug = Debug.getInstance("pkcs12");

D
duke 已提交
155 156
    private static final int keyBag[]  = {1, 2, 840, 113549, 1, 12, 10, 1, 2};
    private static final int certBag[] = {1, 2, 840, 113549, 1, 12, 10, 1, 3};
V
vinnie 已提交
157
    private static final int secretBag[] = {1, 2, 840, 113549, 1, 12, 10, 1, 5};
D
duke 已提交
158 159 160 161 162 163 164 165 166 167

    private static final int pkcs9Name[]  = {1, 2, 840, 113549, 1, 9, 20};
    private static final int pkcs9KeyId[] = {1, 2, 840, 113549, 1, 9, 21};

    private static final int pkcs9certType[] = {1, 2, 840, 113549, 1, 9, 22, 1};

    private static final int pbeWithSHAAnd40BitRC2CBC[] =
                                        {1, 2, 840, 113549, 1, 12, 1, 6};
    private static final int pbeWithSHAAnd3KeyTripleDESCBC[] =
                                        {1, 2, 840, 113549, 1, 12, 1, 3};
168
    private static final int pbes2[] = {1, 2, 840, 113549, 1, 5, 13};
V
vinnie 已提交
169 170 171 172 173 174 175 176
    // TODO: temporary Oracle OID
    /*
     * { joint-iso-itu-t(2) country(16) us(840) organization(1) oracle(113894)
     *   jdk(746875) crypto(1) id-at-trustedKeyUsage(1) }
     */
    private static final int TrustedKeyUsage[] =
                                        {2, 16, 840, 1, 113894, 746875, 1, 1};
    private static final int AnyExtendedKeyUsage[] = {2, 5, 29, 37, 0};
D
duke 已提交
177 178 179

    private static ObjectIdentifier PKCS8ShroudedKeyBag_OID;
    private static ObjectIdentifier CertBag_OID;
V
vinnie 已提交
180
    private static ObjectIdentifier SecretBag_OID;
D
duke 已提交
181 182 183 184 185
    private static ObjectIdentifier PKCS9FriendlyName_OID;
    private static ObjectIdentifier PKCS9LocalKeyId_OID;
    private static ObjectIdentifier PKCS9CertType_OID;
    private static ObjectIdentifier pbeWithSHAAnd40BitRC2CBC_OID;
    private static ObjectIdentifier pbeWithSHAAnd3KeyTripleDESCBC_OID;
186
    private static ObjectIdentifier pbes2_OID;
V
vinnie 已提交
187 188
    private static ObjectIdentifier TrustedKeyUsage_OID;
    private static ObjectIdentifier[] AnyUsage;
D
duke 已提交
189 190 191 192 193 194 195 196

    private int counter = 0;

    // private key count
    // Note: This is a workaround to allow null localKeyID attribute
    // in pkcs12 with one private key entry and associated cert-chain
    private int privateKeyCount = 0;

V
vinnie 已提交
197 198 199 200 201 202
    // secret key count
    private int secretKeyCount = 0;

    // certificate count
    private int certificateCount = 0;

D
duke 已提交
203 204 205 206 207 208 209
    // the source of randomness
    private SecureRandom random;

    static {
        try {
            PKCS8ShroudedKeyBag_OID = new ObjectIdentifier(keyBag);
            CertBag_OID = new ObjectIdentifier(certBag);
V
vinnie 已提交
210
            SecretBag_OID = new ObjectIdentifier(secretBag);
D
duke 已提交
211 212 213 214 215 216 217
            PKCS9FriendlyName_OID = new ObjectIdentifier(pkcs9Name);
            PKCS9LocalKeyId_OID = new ObjectIdentifier(pkcs9KeyId);
            PKCS9CertType_OID = new ObjectIdentifier(pkcs9certType);
            pbeWithSHAAnd40BitRC2CBC_OID =
                        new ObjectIdentifier(pbeWithSHAAnd40BitRC2CBC);
            pbeWithSHAAnd3KeyTripleDESCBC_OID =
                        new ObjectIdentifier(pbeWithSHAAnd3KeyTripleDESCBC);
218
            pbes2_OID = new ObjectIdentifier(pbes2);
V
vinnie 已提交
219 220 221
            TrustedKeyUsage_OID = new ObjectIdentifier(TrustedKeyUsage);
            AnyUsage = new ObjectIdentifier[]{
                new ObjectIdentifier(AnyExtendedKeyUsage)};
D
duke 已提交
222 223 224 225 226
        } catch (IOException ioe) {
            // should not happen
        }
    }

V
vinnie 已提交
227 228
    // A keystore entry and associated attributes
    private static class Entry {
D
duke 已提交
229
        Date date; // the creation date of this entry
V
vinnie 已提交
230 231 232 233 234 235 236 237 238 239 240
        String alias;
        byte[] keyId;
        Set<KeyStore.Entry.Attribute> attributes;
    }

    // A key entry
    private static class KeyEntry extends Entry {
    }

    // A private key entry and its supporting certificate chain
    private static class PrivateKeyEntry extends KeyEntry {
D
duke 已提交
241 242 243 244
        byte[] protectedPrivKey;
        Certificate chain[];
    };

V
vinnie 已提交
245 246 247 248 249 250 251
    // A secret key
    private static class SecretKeyEntry extends KeyEntry {
        byte[] protectedSecretKey;
    };

    // A certificate entry
    private static class CertEntry extends Entry {
W
weijun 已提交
252
        final X509Certificate cert;
V
vinnie 已提交
253 254
        ObjectIdentifier[] trustedKeyUsage;

W
weijun 已提交
255
        CertEntry(X509Certificate cert, byte[] keyId, String alias) {
V
vinnie 已提交
256 257 258 259 260 261 262
            this(cert, keyId, alias, null, null);
        }

        CertEntry(X509Certificate cert, byte[] keyId, String alias,
                ObjectIdentifier[] trustedKeyUsage,
                Set<? extends KeyStore.Entry.Attribute> attributes) {
            this.date = new Date();
W
weijun 已提交
263
            this.cert = cert;
D
duke 已提交
264
            this.keyId = keyId;
W
weijun 已提交
265
            this.alias = alias;
V
vinnie 已提交
266 267 268 269 270
            this.trustedKeyUsage = trustedKeyUsage;
            this.attributes = new HashSet<>();
            if (attributes != null) {
                this.attributes.addAll(attributes);
            }
D
duke 已提交
271 272 273 274
        }
    }

    /**
V
vinnie 已提交
275 276
     * Private keys and certificates are stored in a map.
     * Map entries are keyed by alias names.
D
duke 已提交
277
     */
V
vinnie 已提交
278 279
    private Map<String, Entry> entries =
        Collections.synchronizedMap(new LinkedHashMap<String, Entry>());
D
duke 已提交
280 281

    private ArrayList<KeyEntry> keyList = new ArrayList<KeyEntry>();
W
weijun 已提交
282 283 284
    private LinkedHashMap<X500Principal, X509Certificate> certsMap =
            new LinkedHashMap<X500Principal, X509Certificate>();
    private ArrayList<CertEntry> certEntries = new ArrayList<CertEntry>();
D
duke 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

    /**
     * Returns the key associated with the given alias, using the given
     * password to recover it.
     *
     * @param alias the alias name
     * @param password the password for recovering the key
     *
     * @return the requested key, or null if the given alias does not exist
     * or does not identify a <i>key entry</i>.
     *
     * @exception NoSuchAlgorithmException if the algorithm for recovering the
     * key cannot be found
     * @exception UnrecoverableKeyException if the key cannot be recovered
     * (e.g., the given password is wrong).
     */
    public Key engineGetKey(String alias, char[] password)
        throws NoSuchAlgorithmException, UnrecoverableKeyException
    {
V
vinnie 已提交
304
        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
D
duke 已提交
305 306
        Key key = null;

V
vinnie 已提交
307
        if (entry == null || (!(entry instanceof KeyEntry))) {
D
duke 已提交
308 309 310
            return null;
        }

V
vinnie 已提交
311 312 313 314 315 316 317 318 319
        // get the encoded private key or secret key
        byte[] encrBytes = null;
        if (entry instanceof PrivateKeyEntry) {
            encrBytes = ((PrivateKeyEntry) entry).protectedPrivKey;
        } else if (entry instanceof SecretKeyEntry) {
            encrBytes = ((SecretKeyEntry) entry).protectedSecretKey;
        } else {
            throw new UnrecoverableKeyException("Error locating key");
        }
D
duke 已提交
320 321 322 323

        byte[] encryptedKey;
        AlgorithmParameters algParams;
        ObjectIdentifier algOid;
324

D
duke 已提交
325 326 327 328 329 330 331 332 333 334
        try {
            // get the encrypted private key
            EncryptedPrivateKeyInfo encrInfo =
                        new EncryptedPrivateKeyInfo(encrBytes);
            encryptedKey = encrInfo.getEncryptedData();

            // parse Algorithm parameters
            DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
            DerInputStream in = val.toDerInputStream();
            algOid = in.getOID();
335
            algParams = parseAlgParameters(algOid, in);
D
duke 已提交
336 337 338 339 340 341 342 343 344

        } catch (IOException ioe) {
            UnrecoverableKeyException uke =
                new UnrecoverableKeyException("Private key not stored as "
                                 + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
            uke.initCause(ioe);
            throw uke;
        }

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
       try {
            PBEParameterSpec pbeSpec;
            int ic = 0;

            if (algParams != null) {
                try {
                    pbeSpec =
                        algParams.getParameterSpec(PBEParameterSpec.class);
                } catch (InvalidParameterSpecException ipse) {
                    throw new IOException("Invalid PBE algorithm parameters");
                }
                ic = pbeSpec.getIterationCount();

                if (ic > MAX_ITERATION_COUNT) {
                    throw new IOException("PBE iteration count too large");
                }
            }

V
vinnie 已提交
363
            byte[] keyInfo;
364 365 366 367
            while (true) {
                try {
                    // Use JCE
                    SecretKey skey = getPBEKey(password);
368 369
                    Cipher cipher = Cipher.getInstance(
                        mapPBEParamsToAlgorithm(algOid, algParams));
370
                    cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
V
vinnie 已提交
371
                    keyInfo = cipher.doFinal(encryptedKey);
372 373 374 375 376 377 378 379 380 381 382
                    break;
                } catch (Exception e) {
                    if (password.length == 0) {
                        // Retry using an empty password
                        // without a NULL terminator.
                        password = new char[1];
                        continue;
                    }
                    throw e;
                }
            }
D
duke 已提交
383 384 385

            /*
             * Parse the key algorithm and then use a JCA key factory
V
vinnie 已提交
386
             * to re-create the key.
D
duke 已提交
387
             */
V
vinnie 已提交
388
            DerValue val = new DerValue(keyInfo);
D
duke 已提交
389 390 391
            DerInputStream in = val.toDerInputStream();
            int i = in.getInteger();
            DerValue[] value = in.getSequence(2);
392 393 394
            if (value.length < 1 || value.length > 2) {
                throw new IOException("Invalid length for AlgorithmIdentifier");
            }
D
duke 已提交
395
            AlgorithmId algId = new AlgorithmId(value[0].getOID());
V
vinnie 已提交
396
            String keyAlgo = algId.getName();
D
duke 已提交
397

V
vinnie 已提交
398 399 400 401 402
            // decode private key
            if (entry instanceof PrivateKeyEntry) {
                KeyFactory kfac = KeyFactory.getInstance(keyAlgo);
                PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(keyInfo);
                key = kfac.generatePrivate(kspec);
403

V
vinnie 已提交
404
                if (debug != null) {
405 406 407 408
                    debug.println("Retrieved a protected private key at alias" +
                        " '" + alias + "' (" +
                        new AlgorithmId(algOid).getName() +
                        " iterations: " + ic + ")");
V
vinnie 已提交
409 410 411 412 413 414 415 416 417 418
                }

            // decode secret key
            } else {
                byte[] keyBytes = in.getOctetString();
                SecretKeySpec secretKeySpec =
                    new SecretKeySpec(keyBytes, keyAlgo);

                // Special handling required for PBE: needs a PBEKeySpec
                if (keyAlgo.startsWith("PBE")) {
419 420
                    SecretKeyFactory sKeyFactory =
                        SecretKeyFactory.getInstance(keyAlgo);
V
vinnie 已提交
421 422 423 424
                    KeySpec pbeKeySpec =
                        sKeyFactory.getKeySpec(secretKeySpec, PBEKeySpec.class);
                    key = sKeyFactory.generateSecret(pbeKeySpec);
                } else {
425
                    key = secretKeySpec;
V
vinnie 已提交
426
                }
427

V
vinnie 已提交
428
                if (debug != null) {
429 430 431 432
                    debug.println("Retrieved a protected secret key at alias " +
                        "'" + alias + "' (" +
                        new AlgorithmId(algOid).getName() +
                        " iterations: " + ic + ")");
V
vinnie 已提交
433 434
                }
            }
D
duke 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        } catch (Exception e) {
            UnrecoverableKeyException uke =
                new UnrecoverableKeyException("Get Key failed: " +
                                        e.getMessage());
            uke.initCause(e);
            throw uke;
        }
        return key;
    }

    /**
     * Returns the certificate chain associated with the given alias.
     *
     * @param alias the alias name
     *
     * @return the certificate chain (ordered with the user's certificate first
     * and the root certificate authority last), or null if the given alias
     * does not exist or does not contain a certificate chain (i.e., the given
     * alias identifies either a <i>trusted certificate entry</i> or a
     * <i>key entry</i> without a certificate chain).
     */
    public Certificate[] engineGetCertificateChain(String alias) {
V
vinnie 已提交
457 458 459
        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (entry != null && entry instanceof PrivateKeyEntry) {
            if (((PrivateKeyEntry) entry).chain == null) {
D
duke 已提交
460 461
                return null;
            } else {
462 463 464

                if (debug != null) {
                    debug.println("Retrieved a " +
V
vinnie 已提交
465
                        ((PrivateKeyEntry) entry).chain.length +
466 467 468
                        "-certificate chain at alias '" + alias + "'");
                }

V
vinnie 已提交
469
                return ((PrivateKeyEntry) entry).chain.clone();
D
duke 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
            }
        } else {
            return null;
        }
    }

    /**
     * Returns the certificate associated with the given alias.
     *
     * <p>If the given alias name identifies a
     * <i>trusted certificate entry</i>, the certificate associated with that
     * entry is returned. If the given alias name identifies a
     * <i>key entry</i>, the first element of the certificate chain of that
     * entry is returned, or null if that entry does not have a certificate
     * chain.
     *
     * @param alias the alias name
     *
     * @return the certificate, or null if the given alias does not exist or
     * does not contain a certificate.
     */
    public Certificate engineGetCertificate(String alias) {
V
vinnie 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (entry == null) {
            return null;
        }
        if (entry instanceof CertEntry &&
            ((CertEntry) entry).trustedKeyUsage != null) {

            if (debug != null) {
                if (Arrays.equals(AnyUsage,
                    ((CertEntry) entry).trustedKeyUsage)) {
                    debug.println("Retrieved a certificate at alias '" + alias +
                        "' (trusted for any purpose)");
                } else {
                    debug.println("Retrieved a certificate at alias '" + alias +
                        "' (trusted for limited purposes)");
                }
            }

            return ((CertEntry) entry).cert;

        } else if (entry instanceof PrivateKeyEntry) {
            if (((PrivateKeyEntry) entry).chain == null) {
D
duke 已提交
514 515
                return null;
            } else {
516 517 518 519 520 521

                if (debug != null) {
                    debug.println("Retrieved a certificate at alias '" + alias +
                        "'");
                }

V
vinnie 已提交
522
                return ((PrivateKeyEntry) entry).chain[0];
D
duke 已提交
523
            }
V
vinnie 已提交
524

D
duke 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538
        } else {
            return null;
        }
    }

    /**
     * Returns the creation date of the entry identified by the given alias.
     *
     * @param alias the alias name
     *
     * @return the creation date of this entry, or null if the given alias does
     * not exist
     */
    public Date engineGetCreationDate(String alias) {
V
vinnie 已提交
539
        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
D
duke 已提交
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
        if (entry != null) {
            return new Date(entry.date.getTime());
        } else {
            return null;
        }
    }

    /**
     * Assigns the given key to the given alias, protecting it with the given
     * password.
     *
     * <p>If the given key is of type <code>java.security.PrivateKey</code>,
     * it must be accompanied by a certificate chain certifying the
     * corresponding public key.
     *
     * <p>If the given alias already exists, the keystore information
     * associated with it is overridden by the given key (and possibly
     * certificate chain).
     *
     * @param alias the alias name
     * @param key the key to be associated with the alias
     * @param password the password to protect the key
     * @param chain the certificate chain for the corresponding public
     * key (only required if the given key is of type
     * <code>java.security.PrivateKey</code>).
     *
     * @exception KeyStoreException if the given key cannot be protected, or
     * this operation fails for some other reason
     */
    public synchronized void engineSetKeyEntry(String alias, Key key,
                        char[] password, Certificate[] chain)
        throws KeyStoreException
572 573 574 575 576
    {
        KeyStore.PasswordProtection passwordProtection =
            new KeyStore.PasswordProtection(password);

        try {
V
vinnie 已提交
577
            setKeyEntry(alias, key, passwordProtection, chain, null);
578 579 580 581 582 583 584 585 586 587 588

        } finally {
            try {
                passwordProtection.destroy();
            } catch (DestroyFailedException dfe) {
                // ignore
            }
        }
    }

    /*
V
vinnie 已提交
589
     * Sets a key entry (with attributes, when present)
590 591
     */
    private void setKeyEntry(String alias, Key key,
V
vinnie 已提交
592 593
        KeyStore.PasswordProtection passwordProtection, Certificate[] chain,
        Set<KeyStore.Entry.Attribute> attributes)
594
            throws KeyStoreException
D
duke 已提交
595 596
    {
        try {
V
vinnie 已提交
597
            Entry entry;
D
duke 已提交
598 599

            if (key instanceof PrivateKey) {
V
vinnie 已提交
600 601 602
                PrivateKeyEntry keyEntry = new PrivateKeyEntry();
                keyEntry.date = new Date();

D
duke 已提交
603 604
                if ((key.getFormat().equals("PKCS#8")) ||
                    (key.getFormat().equals("PKCS8"))) {
605 606

                    if (debug != null) {
607 608 609
                        debug.println(
                            "Setting a protected private key at alias '" +
                            alias + "'");
V
vinnie 已提交
610
                        }
611

V
vinnie 已提交
612 613
                    // Encrypt the private key
                    keyEntry.protectedPrivKey =
614
                        encryptPrivateKey(key.getEncoded(), passwordProtection);
D
duke 已提交
615 616 617 618 619
                } else {
                    throw new KeyStoreException("Private key is not encoded" +
                                "as PKCS#8");
                }

V
vinnie 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
                // clone the chain
                if (chain != null) {
                    // validate cert-chain
                    if ((chain.length > 1) && (!validateChain(chain)))
                       throw new KeyStoreException("Certificate chain is " +
                                                "not valid");
                    keyEntry.chain = chain.clone();
                    certificateCount += chain.length;

                    if (debug != null) {
                        debug.println("Setting a " + chain.length +
                            "-certificate chain at alias '" + alias + "'");
                    }
                }
                privateKeyCount++;
                entry = keyEntry;

            } else if (key instanceof SecretKey) {
                SecretKeyEntry keyEntry = new SecretKeyEntry();
                keyEntry.date = new Date();

                // Encode secret key in a PKCS#8
                DerOutputStream pkcs8 = new DerOutputStream();
                DerOutputStream secretKeyInfo = new DerOutputStream();
                secretKeyInfo.putInteger(0);
                AlgorithmId algId = AlgorithmId.get(key.getAlgorithm());
                algId.encode(secretKeyInfo);
                secretKeyInfo.putOctetString(key.getEncoded());
                pkcs8.write(DerValue.tag_Sequence, secretKeyInfo);

                // Encrypt the secret key (using same PBE as for private keys)
                keyEntry.protectedSecretKey =
                    encryptPrivateKey(pkcs8.toByteArray(), passwordProtection);
653 654

                if (debug != null) {
655 656
                    debug.println("Setting a protected secret key at alias '" +
                        alias + "'");
657
                }
V
vinnie 已提交
658 659 660 661 662
                secretKeyCount++;
                entry = keyEntry;

            } else {
                throw new KeyStoreException("Unsupported Key type");
D
duke 已提交
663 664
            }

V
vinnie 已提交
665 666 667 668
            entry.attributes = new HashSet<>();
            if (attributes != null) {
                entry.attributes.addAll(attributes);
            }
D
duke 已提交
669 670 671
            // set the keyId to current date
            entry.keyId = ("Time " + (entry.date).getTime()).getBytes("UTF8");
            // set the alias
672
            entry.alias = alias.toLowerCase(Locale.ENGLISH);
D
duke 已提交
673
            // add the entry
674
            entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
V
vinnie 已提交
675

D
duke 已提交
676
        } catch (Exception nsae) {
677 678
            throw new KeyStoreException("Key protection " +
                       " algorithm not found: " + nsae, nsae);
D
duke 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
        }
    }

    /**
     * Assigns the given key (that has already been protected) to the given
     * alias.
     *
     * <p>If the protected key is of type
     * <code>java.security.PrivateKey</code>, it must be accompanied by a
     * certificate chain certifying the corresponding public key. If the
     * underlying keystore implementation is of type <code>jks</code>,
     * <code>key</code> must be encoded as an
     * <code>EncryptedPrivateKeyInfo</code> as defined in the PKCS #8 standard.
     *
     * <p>If the given alias already exists, the keystore information
     * associated with it is overridden by the given key (and possibly
     * certificate chain).
     *
     * @param alias the alias name
     * @param key the key (in protected format) to be associated with the alias
     * @param chain the certificate chain for the corresponding public
     * key (only useful if the protected key is of type
     * <code>java.security.PrivateKey</code>).
     *
     * @exception KeyStoreException if this operation fails.
     */
    public synchronized void engineSetKeyEntry(String alias, byte[] key,
                                  Certificate[] chain)
        throws KeyStoreException
    {
V
vinnie 已提交
709
        // Private key must be encoded as EncryptedPrivateKeyInfo
D
duke 已提交
710 711 712 713
        // as defined in PKCS#8
        try {
            new EncryptedPrivateKeyInfo(key);
        } catch (IOException ioe) {
714 715
            throw new KeyStoreException("Private key is not stored"
                    + " as PKCS#8 EncryptedPrivateKeyInfo: " + ioe, ioe);
D
duke 已提交
716 717
        }

V
vinnie 已提交
718
        PrivateKeyEntry entry = new PrivateKeyEntry();
D
duke 已提交
719 720
        entry.date = new Date();

721
        if (debug != null) {
V
vinnie 已提交
722 723
            debug.println("Setting a protected private key at alias '" +
                alias + "'");
724 725
        }

W
weijun 已提交
726 727 728 729 730 731 732
        try {
            // set the keyId to current date
            entry.keyId = ("Time " + (entry.date).getTime()).getBytes("UTF8");
        } catch (UnsupportedEncodingException ex) {
            // Won't happen
        }
        // set the alias
733
        entry.alias = alias.toLowerCase(Locale.ENGLISH);
W
weijun 已提交
734

D
duke 已提交
735 736
        entry.protectedPrivKey = key.clone();
        if (chain != null) {
J
juh 已提交
737 738 739 740 741
            // validate cert-chain
            if ((chain.length > 1) && (!validateChain(chain))) {
                throw new KeyStoreException("Certificate chain is "
                        + "not valid");
            }
V
vinnie 已提交
742 743
            entry.chain = chain.clone();
            certificateCount += chain.length;
744 745 746 747 748

            if (debug != null) {
                debug.println("Setting a " + entry.chain.length +
                    "-certificate chain at alias '" + alias + "'");
            }
D
duke 已提交
749 750 751
        }

        // add the entry
V
vinnie 已提交
752
        privateKeyCount++;
753
        entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
D
duke 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    }


    /*
     * Generate random salt
     */
    private byte[] getSalt()
    {
        // Generate a random salt.
        byte[] salt = new byte[SALT_LEN];
        if (random == null) {
           random = new SecureRandom();
        }
        random.nextBytes(salt);
        return salt;
    }

    /*
     * Generate PBE Algorithm Parameters
     */
774
    private AlgorithmParameters getPBEAlgorithmParameters(String algorithm)
D
duke 已提交
775 776 777 778 779 780
        throws IOException
    {
        AlgorithmParameters algParams = null;

        // create PBE parameters from salt and iteration count
        PBEParameterSpec paramSpec =
781
                new PBEParameterSpec(getSalt(), PBE_ITERATION_COUNT);
D
duke 已提交
782 783 784 785
        try {
           algParams = AlgorithmParameters.getInstance(algorithm);
           algParams.init(paramSpec);
        } catch (Exception e) {
786
           throw new IOException("getPBEAlgorithmParameters failed: " +
787
                                 e.getMessage(), e);
D
duke 已提交
788 789 790 791 792 793 794
        }
        return algParams;
    }

    /*
     * parse Algorithm Parameters
     */
795 796
    private AlgorithmParameters parseAlgParameters(ObjectIdentifier algorithm,
        DerInputStream in) throws IOException
D
duke 已提交
797 798 799 800 801 802 803 804 805 806 807 808 809
    {
        AlgorithmParameters algParams = null;
        try {
            DerValue params;
            if (in.available() == 0) {
                params = null;
            } else {
                params = in.getDerValue();
                if (params.tag == DerValue.tag_Null) {
                   params = null;
                }
            }
            if (params != null) {
810
                if (algorithm.equals((Object)pbes2_OID)) {
811 812 813 814
                    algParams = AlgorithmParameters.getInstance("PBES2");
                } else {
                    algParams = AlgorithmParameters.getInstance("PBE");
                }
D
duke 已提交
815 816 817
                algParams.init(params.toByteArray());
            }
        } catch (Exception e) {
818 819
           throw new IOException("parseAlgParameters failed: " +
                                 e.getMessage(), e);
D
duke 已提交
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
        }
        return algParams;
    }

    /*
     * Generate PBE key
     */
    private SecretKey getPBEKey(char[] password) throws IOException
    {
        SecretKey skey = null;

        try {
            PBEKeySpec keySpec = new PBEKeySpec(password);
            SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
            skey = skFac.generateSecret(keySpec);
V
vinnie 已提交
835
            keySpec.clearPassword();
D
duke 已提交
836
        } catch (Exception e) {
837 838
           throw new IOException("getSecretKey failed: " +
                                 e.getMessage(), e);
D
duke 已提交
839 840 841 842 843 844 845 846
        }
        return skey;
    }

    /*
     * Encrypt private key using Password-based encryption (PBE)
     * as defined in PKCS#5.
     *
847
     * NOTE: By default, pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
D
duke 已提交
848 849 850 851
     *       used to derive the key and IV.
     *
     * @return encrypted private key encoded as EncryptedPrivateKeyInfo
     */
852 853
    private byte[] encryptPrivateKey(byte[] data,
        KeyStore.PasswordProtection passwordProtection)
D
duke 已提交
854 855 856 857 858
        throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException
    {
        byte[] key = null;

        try {
859 860 861 862 863 864 865 866 867 868 869 870 871
            String algorithm;
            AlgorithmParameters algParams;
            AlgorithmId algid;

            // Initialize PBE algorithm and parameters
            algorithm = passwordProtection.getProtectionAlgorithm();
            if (algorithm != null) {
                AlgorithmParameterSpec algParamSpec =
                    passwordProtection.getProtectionParameters();
                if (algParamSpec != null) {
                    algParams = AlgorithmParameters.getInstance(algorithm);
                    algParams.init(algParamSpec);
                } else {
872
                    algParams = getPBEAlgorithmParameters(algorithm);
873 874 875 876 877 878 879
                }
            } else {
                // Check default key protection algorithm for PKCS12 keystores
                algorithm = AccessController.doPrivileged(
                    new PrivilegedAction<String>() {
                        public String run() {
                            String prop =
880
                                Security.getProperty(
881 882 883 884 885 886 887 888
                                    KEY_PROTECTION_ALGORITHM[0]);
                            if (prop == null) {
                                prop = Security.getProperty(
                                    KEY_PROTECTION_ALGORITHM[1]);
                            }
                            return prop;
                        }
                    });
889
                if (algorithm == null || algorithm.isEmpty()) {
890 891
                    algorithm = "PBEWithSHA1AndDESede";
                }
892
                algParams = getPBEAlgorithmParameters(algorithm);
893 894 895 896 897 898
            }

            ObjectIdentifier pbeOID = mapPBEAlgorithmToOID(algorithm);
            if (pbeOID == null) {
                    throw new IOException("PBE algorithm '" + algorithm +
                        " 'is not supported for key entry protection");
899
            }
D
duke 已提交
900 901

            // Use JCE
902 903
            SecretKey skey = getPBEKey(passwordProtection.getPassword());
            Cipher cipher = Cipher.getInstance(algorithm);
D
duke 已提交
904 905
            cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
            byte[] encryptedKey = cipher.doFinal(data);
906
            algid = new AlgorithmId(pbeOID, cipher.getParameters());
D
duke 已提交
907

908 909 910 911 912
            if (debug != null) {
                debug.println("  (Cipher algorithm: " + cipher.getAlgorithm() +
                    ")");
            }

D
duke 已提交
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
            // wrap encrypted private key in EncryptedPrivateKeyInfo
            // as defined in PKCS#8
            EncryptedPrivateKeyInfo encrInfo =
                new EncryptedPrivateKeyInfo(algid, encryptedKey);
            key = encrInfo.getEncoded();
        } catch (Exception e) {
            UnrecoverableKeyException uke =
                new UnrecoverableKeyException("Encrypt Private Key failed: "
                                                + e.getMessage());
            uke.initCause(e);
            throw uke;
        }

        return key;
    }

929 930 931
    /*
     * Map a PBE algorithm name onto its object identifier
     */
932
    private static ObjectIdentifier mapPBEAlgorithmToOID(String algorithm)
933
        throws NoSuchAlgorithmException {
934
        // Check for PBES2 algorithms
935
        if (algorithm.toLowerCase(Locale.ENGLISH).startsWith("pbewithhmacsha")) {
936 937
            return pbes2_OID;
        }
938
        return AlgorithmId.get(algorithm).getOID();
939 940
    }

941 942 943 944 945 946
    /*
     * Map a PBE algorithm parameters onto its algorithm name
     */
    private static String mapPBEParamsToAlgorithm(ObjectIdentifier algorithm,
        AlgorithmParameters algParams) throws NoSuchAlgorithmException {
        // Check for PBES2 algorithms
947
        if (algorithm.equals((Object)pbes2_OID) && algParams != null) {
948 949 950 951 952
            return algParams.toString();
        }
        return algorithm.toString();
    }

D
duke 已提交
953 954 955 956 957 958 959 960 961 962 963
    /**
     * Assigns the given certificate to the given alias.
     *
     * <p>If the given alias already exists in this keystore and identifies a
     * <i>trusted certificate entry</i>, the certificate associated with it is
     * overridden by the given certificate.
     *
     * @param alias the alias name
     * @param cert the certificate
     *
     * @exception KeyStoreException if the given alias already exists and does
V
vinnie 已提交
964 965
     * not identify a <i>trusted certificate entry</i>, or this operation fails
     * for some other reason.
D
duke 已提交
966 967 968 969
     */
    public synchronized void engineSetCertificateEntry(String alias,
        Certificate cert) throws KeyStoreException
    {
V
vinnie 已提交
970 971 972 973 974 975 976 977 978 979 980
        setCertEntry(alias, cert, null);
    }

    /*
     * Sets a trusted cert entry (with attributes, when present)
     */
    private void setCertEntry(String alias, Certificate cert,
        Set<KeyStore.Entry.Attribute> attributes) throws KeyStoreException {

        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (entry != null && entry instanceof KeyEntry) {
D
duke 已提交
981
            throw new KeyStoreException("Cannot overwrite own certificate");
V
vinnie 已提交
982 983 984 985 986 987
        }

        CertEntry certEntry =
            new CertEntry((X509Certificate) cert, null, alias, AnyUsage,
                attributes);
        certificateCount++;
988
        entries.put(alias.toLowerCase(Locale.ENGLISH), certEntry);
V
vinnie 已提交
989 990 991 992 993

        if (debug != null) {
            debug.println("Setting a trusted certificate at alias '" + alias +
                "'");
        }
D
duke 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    }

    /**
     * Deletes the entry identified by the given alias from this keystore.
     *
     * @param alias the alias name
     *
     * @exception KeyStoreException if the entry cannot be removed.
     */
    public synchronized void engineDeleteEntry(String alias)
        throws KeyStoreException
    {
1006 1007 1008 1009
        if (debug != null) {
            debug.println("Removing entry at alias '" + alias + "'");
        }

V
vinnie 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (entry instanceof PrivateKeyEntry) {
            PrivateKeyEntry keyEntry = (PrivateKeyEntry) entry;
            if (keyEntry.chain != null) {
                certificateCount -= keyEntry.chain.length;
            }
            privateKeyCount--;
        } else if (entry instanceof CertEntry) {
            certificateCount--;
        } else if (entry instanceof SecretKeyEntry) {
            secretKeyCount--;
        }
1022
        entries.remove(alias.toLowerCase(Locale.ENGLISH));
D
duke 已提交
1023 1024 1025 1026 1027 1028 1029 1030
    }

    /**
     * Lists all the alias names of this keystore.
     *
     * @return enumeration of the alias names
     */
    public Enumeration<String> engineAliases() {
V
vinnie 已提交
1031
        return Collections.enumeration(entries.keySet());
D
duke 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    }

    /**
     * Checks if the given alias exists in this keystore.
     *
     * @param alias the alias name
     *
     * @return true if the alias exists, false otherwise
     */
    public boolean engineContainsAlias(String alias) {
1042
        return entries.containsKey(alias.toLowerCase(Locale.ENGLISH));
D
duke 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    }

    /**
     * Retrieves the number of entries in this keystore.
     *
     * @return the number of entries in this keystore
     */
    public int engineSize() {
        return entries.size();
    }

    /**
     * Returns true if the entry identified by the given alias is a
     * <i>key entry</i>, and false otherwise.
     *
     * @return true if the entry identified by the given alias is a
     * <i>key entry</i>, false otherwise.
     */
    public boolean engineIsKeyEntry(String alias) {
V
vinnie 已提交
1062 1063
        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (entry != null && entry instanceof KeyEntry) {
D
duke 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
            return true;
        } else {
            return false;
        }
    }

    /**
     * Returns true if the entry identified by the given alias is a
     * <i>trusted certificate entry</i>, and false otherwise.
     *
     * @return true if the entry identified by the given alias is a
     * <i>trusted certificate entry</i>, false otherwise.
     */
    public boolean engineIsCertificateEntry(String alias) {
V
vinnie 已提交
1078 1079 1080 1081 1082 1083 1084
        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (entry != null && entry instanceof CertEntry &&
            ((CertEntry) entry).trustedKeyUsage != null) {
            return true;
        } else {
            return false;
        }
D
duke 已提交
1085 1086
    }

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
    /**
     * Determines if the keystore {@code Entry} for the specified
     * {@code alias} is an instance or subclass of the specified
     * {@code entryClass}.
     *
     * @param alias the alias name
     * @param entryClass the entry class
     *
     * @return true if the keystore {@code Entry} for the specified
     *          {@code alias} is an instance or subclass of the
     *          specified {@code entryClass}, false otherwise
     *
     * @since 1.5
     */
    @Override
    public boolean
        engineEntryInstanceOf(String alias,
                              Class<? extends KeyStore.Entry> entryClass)
    {
        if (entryClass == KeyStore.TrustedCertificateEntry.class) {
            return engineIsCertificateEntry(alias);
        }

        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (entryClass == KeyStore.PrivateKeyEntry.class) {
            return (entry != null && entry instanceof PrivateKeyEntry);
        }
        if (entryClass == KeyStore.SecretKeyEntry.class) {
            return (entry != null && entry instanceof SecretKeyEntry);
        }
        return false;
    }

D
duke 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    /**
     * Returns the (alias) name of the first keystore entry whose certificate
     * matches the given certificate.
     *
     * <p>This method attempts to match the given certificate with each
     * keystore entry. If the entry being considered
     * is a <i>trusted certificate entry</i>, the given certificate is
     * compared to that entry's certificate. If the entry being considered is
     * a <i>key entry</i>, the given certificate is compared to the first
     * element of that entry's certificate chain (if a chain exists).
     *
     * @param cert the certificate to match with.
     *
     * @return the (alias) name of the first entry with matching certificate,
     * or null if no such entry exists in this keystore.
     */
    public String engineGetCertificateAlias(Certificate cert) {
        Certificate certElem = null;

V
vinnie 已提交
1139
        for (Enumeration<String> e = engineAliases(); e.hasMoreElements(); ) {
D
duke 已提交
1140
            String alias = e.nextElement();
V
vinnie 已提交
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
            Entry entry = entries.get(alias);
            if (entry instanceof PrivateKeyEntry) {
                if (((PrivateKeyEntry) entry).chain != null) {
                    certElem = ((PrivateKeyEntry) entry).chain[0];
                }
            } else if (entry instanceof CertEntry &&
                    ((CertEntry) entry).trustedKeyUsage != null) {
                certElem = ((CertEntry) entry).cert;
            } else {
                continue;
D
duke 已提交
1151
            }
1152
            if (certElem != null && certElem.equals(cert)) {
D
duke 已提交
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
                return alias;
            }
        }
        return null;
    }

    /**
     * Stores this keystore to the given output stream, and protects its
     * integrity with the given password.
     *
     * @param stream the output stream to which this keystore is written.
     * @param password the password to generate the keystore integrity check
     *
     * @exception IOException if there was an I/O problem with data
     * @exception NoSuchAlgorithmException if the appropriate data integrity
     * algorithm could not be found
     * @exception CertificateException if any of the certificates included in
     * the keystore data could not be stored
     */
    public synchronized void engineStore(OutputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException
    {
        // password is mandatory when storing
        if (password == null) {
           throw new IllegalArgumentException("password can't be null");
        }

        // -- Create PFX
        DerOutputStream pfx = new DerOutputStream();

        // PFX version (always write the latest version)
        DerOutputStream version = new DerOutputStream();
        version.putInteger(VERSION_3);
        byte[] pfxVersion = version.toByteArray();
        pfx.write(pfxVersion);

        // -- Create AuthSafe
        DerOutputStream authSafe = new DerOutputStream();

        // -- Create ContentInfos
        DerOutputStream authSafeContentInfo = new DerOutputStream();

        // -- create safeContent Data ContentInfo
V
vinnie 已提交
1196
        if (privateKeyCount > 0 || secretKeyCount > 0) {
1197

V
vinnie 已提交
1198
            if (debug != null) {
1199
                debug.println("Storing " + (privateKeyCount + secretKeyCount) +
1200
                    " protected key(s) in a PKCS#7 data");
V
vinnie 已提交
1201
            }
D
duke 已提交
1202

V
vinnie 已提交
1203 1204 1205
            byte[] safeContentData = createSafeContent();
            ContentInfo dataContentInfo = new ContentInfo(safeContentData);
            dataContentInfo.encode(authSafeContentInfo);
1206 1207
        }

V
vinnie 已提交
1208 1209 1210 1211 1212
        // -- create EncryptedContentInfo
        if (certificateCount > 0) {

            if (debug != null) {
                debug.println("Storing " + certificateCount +
1213
                    " certificate(s) in a PKCS#7 encryptedData");
V
vinnie 已提交
1214 1215 1216 1217
            }

            byte[] encrData = createEncryptedData(password);
            ContentInfo encrContentInfo =
D
duke 已提交
1218 1219
                new ContentInfo(ContentInfo.ENCRYPTED_DATA_OID,
                                new DerValue(encrData));
V
vinnie 已提交
1220 1221
            encrContentInfo.encode(authSafeContentInfo);
        }
D
duke 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245

        // wrap as SequenceOf ContentInfos
        DerOutputStream cInfo = new DerOutputStream();
        cInfo.write(DerValue.tag_SequenceOf, authSafeContentInfo);
        byte[] authenticatedSafe = cInfo.toByteArray();

        // Create Encapsulated ContentInfo
        ContentInfo contentInfo = new ContentInfo(authenticatedSafe);
        contentInfo.encode(authSafe);
        byte[] authSafeData = authSafe.toByteArray();
        pfx.write(authSafeData);

        // -- MAC
        byte[] macData = calculateMac(password, authenticatedSafe);
        pfx.write(macData);

        // write PFX to output stream
        DerOutputStream pfxout = new DerOutputStream();
        pfxout.write(DerValue.tag_Sequence, pfx);
        byte[] pfxData = pfxout.toByteArray();
        stream.write(pfxData);
        stream.flush();
    }

V
vinnie 已提交
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    /**
     * Gets a <code>KeyStore.Entry</code> for the specified alias
     * with the specified protection parameter.
     *
     * @param alias get the <code>KeyStore.Entry</code> for this alias
     * @param protParam the <code>ProtectionParameter</code>
     *          used to protect the <code>Entry</code>,
     *          which may be <code>null</code>
     *
     * @return the <code>KeyStore.Entry</code> for the specified alias,
     *          or <code>null</code> if there is no such entry
     *
     * @exception KeyStoreException if the operation failed
     * @exception NoSuchAlgorithmException if the algorithm for recovering the
     *          entry cannot be found
     * @exception UnrecoverableEntryException if the specified
     *          <code>protParam</code> were insufficient or invalid
     * @exception UnrecoverableKeyException if the entry is a
     *          <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
     *          and the specified <code>protParam</code> does not contain
     *          the information needed to recover the key (e.g. wrong password)
     *
     * @since 1.5
     */
    @Override
    public KeyStore.Entry engineGetEntry(String alias,
                        KeyStore.ProtectionParameter protParam)
                throws KeyStoreException, NoSuchAlgorithmException,
                UnrecoverableEntryException {

        if (!engineContainsAlias(alias)) {
            return null;
        }

        Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
        if (protParam == null) {
            if (engineIsCertificateEntry(alias)) {
                if (entry instanceof CertEntry &&
                    ((CertEntry) entry).trustedKeyUsage != null) {

                    if (debug != null) {
                        debug.println("Retrieved a trusted certificate at " +
                            "alias '" + alias + "'");
                    }

                    return new KeyStore.TrustedCertificateEntry(
                        ((CertEntry)entry).cert, getAttributes(entry));
                }
            } else {
                throw new UnrecoverableKeyException
                        ("requested entry requires a password");
            }
        }

        if (protParam instanceof KeyStore.PasswordProtection) {
            if (engineIsCertificateEntry(alias)) {
                throw new UnsupportedOperationException
                    ("trusted certificate entries are not password-protected");
            } else if (engineIsKeyEntry(alias)) {
                KeyStore.PasswordProtection pp =
                        (KeyStore.PasswordProtection)protParam;
                char[] password = pp.getPassword();

                Key key = engineGetKey(alias, password);
                if (key instanceof PrivateKey) {
                    Certificate[] chain = engineGetCertificateChain(alias);

                    return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain,
                        getAttributes(entry));

                } else if (key instanceof SecretKey) {

                    return new KeyStore.SecretKeyEntry((SecretKey)key,
                        getAttributes(entry));
                }
            } else if (!engineIsKeyEntry(alias)) {
                throw new UnsupportedOperationException
                    ("untrusted certificate entries are not " +
                        "password-protected");
            }
        }

        throw new UnsupportedOperationException();
    }

    /**
     * Saves a <code>KeyStore.Entry</code> under the specified alias.
     * The specified protection parameter is used to protect the
     * <code>Entry</code>.
     *
     * <p> If an entry already exists for the specified alias,
     * it is overridden.
     *
     * @param alias save the <code>KeyStore.Entry</code> under this alias
     * @param entry the <code>Entry</code> to save
     * @param protParam the <code>ProtectionParameter</code>
     *          used to protect the <code>Entry</code>,
     *          which may be <code>null</code>
     *
     * @exception KeyStoreException if this operation fails
     *
     * @since 1.5
     */
    @Override
    public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
        KeyStore.ProtectionParameter protParam) throws KeyStoreException {

        // get password
        if (protParam != null &&
            !(protParam instanceof KeyStore.PasswordProtection)) {
            throw new KeyStoreException("unsupported protection parameter");
        }
        KeyStore.PasswordProtection pProtect = null;
        if (protParam != null) {
            pProtect = (KeyStore.PasswordProtection)protParam;
        }

        // set entry
        if (entry instanceof KeyStore.TrustedCertificateEntry) {
            if (protParam != null && pProtect.getPassword() != null) {
                // pre-1.5 style setCertificateEntry did not allow password
                throw new KeyStoreException
                    ("trusted certificate entries are not password-protected");
            } else {
                KeyStore.TrustedCertificateEntry tce =
                        (KeyStore.TrustedCertificateEntry)entry;
                setCertEntry(alias, tce.getTrustedCertificate(),
                    tce.getAttributes());

                return;
            }
        } else if (entry instanceof KeyStore.PrivateKeyEntry) {
            if (pProtect == null || pProtect.getPassword() == null) {
                // pre-1.5 style setKeyEntry required password
                throw new KeyStoreException
                    ("non-null password required to create PrivateKeyEntry");
            } else {
                KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
                setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                    pke.getCertificateChain(), pke.getAttributes());

                return;
            }
        } else if (entry instanceof KeyStore.SecretKeyEntry) {
            if (pProtect == null || pProtect.getPassword() == null) {
                // pre-1.5 style setKeyEntry required password
                throw new KeyStoreException
                    ("non-null password required to create SecretKeyEntry");
            } else {
                KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
                setKeyEntry(alias, ske.getSecretKey(), pProtect,
                    (Certificate[])null, ske.getAttributes());

                return;
            }
        }

        throw new KeyStoreException
                ("unsupported entry type: " + entry.getClass().getName());
    }

    /*
     * Assemble the entry attributes
     */
    private Set<KeyStore.Entry.Attribute> getAttributes(Entry entry) {

        if (entry.attributes == null) {
            entry.attributes = new HashSet<>();
        }

        // friendlyName
        entry.attributes.add(new PKCS12Attribute(
            PKCS9FriendlyName_OID.toString(), entry.alias));

        // localKeyID
        byte[] keyIdValue = entry.keyId;
        if (keyIdValue != null) {
            entry.attributes.add(new PKCS12Attribute(
                PKCS9LocalKeyId_OID.toString(), Debug.toString(keyIdValue)));
        }

        // trustedKeyUsage
        if (entry instanceof CertEntry) {
            ObjectIdentifier[] trustedKeyUsageValue =
                ((CertEntry) entry).trustedKeyUsage;
            if (trustedKeyUsageValue != null) {
                if (trustedKeyUsageValue.length == 1) { // omit brackets
                    entry.attributes.add(new PKCS12Attribute(
                        TrustedKeyUsage_OID.toString(),
                        trustedKeyUsageValue[0].toString()));
                } else { // multi-valued
                    entry.attributes.add(new PKCS12Attribute(
                        TrustedKeyUsage_OID.toString(),
                        Arrays.toString(trustedKeyUsageValue)));
                }
            }
        }

        return entry.attributes;
    }

D
duke 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
    /*
     * Generate Hash.
     */
    private byte[] generateHash(byte[] data) throws IOException
    {
        byte[] digest = null;

        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(data);
            digest = md.digest();
        } catch (Exception e) {
1459
            throw new IOException("generateHash failed: " + e, e);
D
duke 已提交
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
        }
        return digest;
    }


    /*
     * Calculate MAC using HMAC algorithm (required for password integrity)
     *
     * Hash-based MAC algorithm combines secret key with message digest to
     * create a message authentication code (MAC)
     */
    private byte[] calculateMac(char[] passwd, byte[] data)
        throws IOException
    {
        byte[] mData = null;
        String algName = "SHA1";

        try {
            // Generate a random salt.
            byte[] salt = getSalt();

            // generate MAC (MAC key is generated within JCE)
            Mac m = Mac.getInstance("HmacPBESHA1");
            PBEParameterSpec params =
1484
                        new PBEParameterSpec(salt, MAC_ITERATION_COUNT);
D
duke 已提交
1485 1486 1487 1488 1489 1490 1491
            SecretKey key = getPBEKey(passwd);
            m.init(key, params);
            m.update(data);
            byte[] macResult = m.doFinal();

            // encode as MacData
            MacData macData = new MacData(algName, macResult, salt,
1492
                                                MAC_ITERATION_COUNT);
D
duke 已提交
1493 1494 1495 1496
            DerOutputStream bytes = new DerOutputStream();
            bytes.write(macData.getEncoded());
            mData = bytes.toByteArray();
        } catch (Exception e) {
1497
            throw new IOException("calculateMac failed: " + e, e);
D
duke 已提交
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        }
        return mData;
    }


    /*
     * Validate Certificate Chain
     */
    private boolean validateChain(Certificate[] certChain)
    {
        for (int i = 0; i < certChain.length-1; i++) {
            X500Principal issuerDN =
                ((X509Certificate)certChain[i]).getIssuerX500Principal();
            X500Principal subjectDN =
                ((X509Certificate)certChain[i+1]).getSubjectX500Principal();
            if (!(issuerDN.equals(subjectDN)))
                return false;
        }
J
juh 已提交
1516 1517 1518 1519 1520 1521

        // Check for loops in the chain. If there are repeated certs,
        // the Set of certs in the chain will contain fewer certs than
        // the chain
        Set<Certificate> set = new HashSet<>(Arrays.asList(certChain));
        return set.size() == certChain.length;
D
duke 已提交
1522 1523 1524 1525
    }


    /*
V
vinnie 已提交
1526
     * Create PKCS#12 Attributes, friendlyName, localKeyId and trustedKeyUsage.
D
duke 已提交
1527 1528 1529 1530
     *
     * Although attributes are optional, they could be required.
     * For e.g. localKeyId attribute is required to match the
     * private key with the associated end-entity certificate.
V
vinnie 已提交
1531
     * The trustedKeyUsage attribute is used to denote a trusted certificate.
D
duke 已提交
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
     *
     * PKCS8ShroudedKeyBags include unique localKeyID and friendlyName.
     * CertBags may or may not include attributes depending on the type
     * of Certificate. In end-entity certificates, localKeyID should be
     * unique, and the corresponding private key should have the same
     * localKeyID. For trusted CA certs in the cert-chain, localKeyID
     * attribute is not required, hence most vendors don't include it.
     * NSS/Netscape require it to be unique or null, where as IE/OpenSSL
     * ignore it.
     *
     * Here is a list of pkcs12 attribute values in CertBags.
     *
     * PKCS12 Attribute       NSS/Netscape    IE     OpenSSL    J2SE
     * --------------------------------------------------------------
     * LocalKeyId
     * (In EE cert only,
     *  NULL in CA certs)      true          true     true      true
     *
     * friendlyName            unique        same/    same/     unique
     *                                       unique   unique/
     *                                                null
V
vinnie 已提交
1553
     * trustedKeyUsage         -             -        -         true
D
duke 已提交
1554 1555 1556 1557 1558 1559
     *
     * Note: OpenSSL adds friendlyName for end-entity cert only, and
     * removes the localKeyID and friendlyName for CA certs.
     * If the CertBag did not have a friendlyName, most vendors will
     * add it, and assign it to the DN of the cert.
     */
V
vinnie 已提交
1560 1561 1562 1563 1564 1565 1566 1567
    private byte[] getBagAttributes(String alias, byte[] keyId,
        Set<KeyStore.Entry.Attribute> attributes) throws IOException {
        return getBagAttributes(alias, keyId, null, attributes);
    }

    private byte[] getBagAttributes(String alias, byte[] keyId,
        ObjectIdentifier[] trustedUsage,
        Set<KeyStore.Entry.Attribute> attributes) throws IOException {
D
duke 已提交
1568 1569 1570

        byte[] localKeyID = null;
        byte[] friendlyName = null;
V
vinnie 已提交
1571
        byte[] trustedKeyUsage = null;
D
duke 已提交
1572

V
vinnie 已提交
1573 1574
        // return null if all three attributes are null
        if ((alias == null) && (keyId == null) && (trustedKeyUsage == null)) {
D
duke 已提交
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
            return null;
        }

        // SafeBag Attributes
        DerOutputStream bagAttrs = new DerOutputStream();

        // Encode the friendlyname oid.
        if (alias != null) {
            DerOutputStream bagAttr1 = new DerOutputStream();
            bagAttr1.putOID(PKCS9FriendlyName_OID);
            DerOutputStream bagAttrContent1 = new DerOutputStream();
            DerOutputStream bagAttrValue1 = new DerOutputStream();
            bagAttrContent1.putBMPString(alias);
            bagAttr1.write(DerValue.tag_Set, bagAttrContent1);
            bagAttrValue1.write(DerValue.tag_Sequence, bagAttr1);
            friendlyName = bagAttrValue1.toByteArray();
        }

        // Encode the localkeyId oid.
        if (keyId != null) {
            DerOutputStream bagAttr2 = new DerOutputStream();
            bagAttr2.putOID(PKCS9LocalKeyId_OID);
            DerOutputStream bagAttrContent2 = new DerOutputStream();
            DerOutputStream bagAttrValue2 = new DerOutputStream();
            bagAttrContent2.putOctetString(keyId);
            bagAttr2.write(DerValue.tag_Set, bagAttrContent2);
            bagAttrValue2.write(DerValue.tag_Sequence, bagAttr2);
            localKeyID = bagAttrValue2.toByteArray();
        }

V
vinnie 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
        // Encode the trustedKeyUsage oid.
        if (trustedUsage != null) {
            DerOutputStream bagAttr3 = new DerOutputStream();
            bagAttr3.putOID(TrustedKeyUsage_OID);
            DerOutputStream bagAttrContent3 = new DerOutputStream();
            DerOutputStream bagAttrValue3 = new DerOutputStream();
            for (ObjectIdentifier usage : trustedUsage) {
                bagAttrContent3.putOID(usage);
            }
            bagAttr3.write(DerValue.tag_Set, bagAttrContent3);
            bagAttrValue3.write(DerValue.tag_Sequence, bagAttr3);
            trustedKeyUsage = bagAttrValue3.toByteArray();
        }

D
duke 已提交
1619 1620 1621 1622 1623 1624 1625
        DerOutputStream attrs = new DerOutputStream();
        if (friendlyName != null) {
            attrs.write(friendlyName);
        }
        if (localKeyID != null) {
            attrs.write(localKeyID);
        }
V
vinnie 已提交
1626 1627 1628 1629 1630 1631
        if (trustedKeyUsage != null) {
            attrs.write(trustedKeyUsage);
        }

        if (attributes != null) {
            for (KeyStore.Entry.Attribute attribute : attributes) {
1632 1633 1634 1635 1636 1637 1638
                String attributeName = attribute.getName();
                // skip friendlyName, localKeyId and trustedKeyUsage
                if (CORE_ATTRIBUTES[0].equals(attributeName) ||
                    CORE_ATTRIBUTES[1].equals(attributeName) ||
                    CORE_ATTRIBUTES[2].equals(attributeName)) {
                    continue;
                }
V
vinnie 已提交
1639 1640 1641 1642
                attrs.write(((PKCS12Attribute) attribute).getEncoded());
            }
        }

D
duke 已提交
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
        bagAttrs.write(DerValue.tag_Set, attrs);
        return bagAttrs.toByteArray();
    }

    /*
     * Create EncryptedData content type, that contains EncryptedContentInfo.
     * Includes certificates in individual SafeBags of type CertBag.
     * Each CertBag may include pkcs12 attributes
     * (see comments in getBagAttributes)
     */
    private byte[] createEncryptedData(char[] password)
        throws CertificateException, IOException
    {
        DerOutputStream out = new DerOutputStream();
V
vinnie 已提交
1657
        for (Enumeration<String> e = engineAliases(); e.hasMoreElements(); ) {
D
duke 已提交
1658 1659

            String alias = e.nextElement();
V
vinnie 已提交
1660
            Entry entry = entries.get(alias);
D
duke 已提交
1661 1662

            // certificate chain
1663
            Certificate[] certs;
V
vinnie 已提交
1664 1665 1666

            if (entry instanceof PrivateKeyEntry) {
                PrivateKeyEntry keyEntry = (PrivateKeyEntry) entry;
1667 1668 1669 1670 1671
                if (keyEntry.chain != null) {
                    certs = keyEntry.chain;
                } else {
                    certs = new Certificate[0];
                }
V
vinnie 已提交
1672
            } else if (entry instanceof CertEntry) {
1673 1674 1675
                certs = new Certificate[]{((CertEntry) entry).cert};
            } else {
                certs = new Certificate[0];
D
duke 已提交
1676 1677
            }

1678
            for (int i = 0; i < certs.length; i++) {
D
duke 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
                // create SafeBag of Type CertBag
                DerOutputStream safeBag = new DerOutputStream();
                safeBag.putOID(CertBag_OID);

                // create a CertBag
                DerOutputStream certBag = new DerOutputStream();
                certBag.putOID(PKCS9CertType_OID);

                // write encoded certs in a context-specific tag
                DerOutputStream certValue = new DerOutputStream();
V
vinnie 已提交
1689
                X509Certificate cert = (X509Certificate) certs[i];
D
duke 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
                certValue.putOctetString(cert.getEncoded());
                certBag.write(DerValue.createTag(DerValue.TAG_CONTEXT,
                                        true, (byte) 0), certValue);

                // wrap CertBag in a Sequence
                DerOutputStream certout = new DerOutputStream();
                certout.write(DerValue.tag_Sequence, certBag);
                byte[] certBagValue = certout.toByteArray();

                // Wrap the CertBag encoding in a context-specific tag.
                DerOutputStream bagValue = new DerOutputStream();
                bagValue.write(certBagValue);
                // write SafeBag Value
                safeBag.write(DerValue.createTag(DerValue.TAG_CONTEXT,
                                true, (byte) 0), bagValue);

                // write SafeBag Attributes
                // All Certs should have a unique friendlyName.
                // This change is made to meet NSS requirements.
                byte[] bagAttrs = null;
                if (i == 0) {
                    // Only End-Entity Cert should have a localKeyId.
V
vinnie 已提交
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
                    if (entry instanceof KeyEntry) {
                        KeyEntry keyEntry = (KeyEntry) entry;
                        bagAttrs =
                            getBagAttributes(keyEntry.alias, keyEntry.keyId,
                                keyEntry.attributes);
                    } else {
                        CertEntry certEntry = (CertEntry) entry;
                        bagAttrs =
                            getBagAttributes(certEntry.alias, certEntry.keyId,
                                certEntry.trustedKeyUsage,
                                certEntry.attributes);
                    }
D
duke 已提交
1724 1725 1726 1727 1728 1729 1730
                } else {
                    // Trusted root CA certs and Intermediate CA certs do not
                    // need to have a localKeyId, and hence localKeyId is null
                    // This change is made to meet NSS/Netscape requirements.
                    // NSS pkcs12 library requires trusted CA certs in the
                    // certificate chain to have unique or null localKeyID.
                    // However, IE/OpenSSL do not impose this restriction.
W
weijun 已提交
1731
                    bagAttrs = getBagAttributes(
V
vinnie 已提交
1732 1733
                            cert.getSubjectX500Principal().getName(), null,
                            entry.attributes);
D
duke 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
                }
                if (bagAttrs != null) {
                    safeBag.write(bagAttrs);
                }

                // wrap as Sequence
                out.write(DerValue.tag_Sequence, safeBag);
            } // for cert-chain
        }

        // wrap as SequenceOf SafeBag
        DerOutputStream safeBagValue = new DerOutputStream();
        safeBagValue.write(DerValue.tag_SequenceOf, out);
        byte[] safeBagData = safeBagValue.toByteArray();

        // encrypt the content (EncryptedContentInfo)
        byte[] encrContentInfo = encryptContent(safeBagData, password);

        // -- SEQUENCE of EncryptedData
        DerOutputStream encrData = new DerOutputStream();
        DerOutputStream encrDataContent = new DerOutputStream();
        encrData.putInteger(0);
        encrData.write(encrContentInfo);
        encrDataContent.write(DerValue.tag_Sequence, encrData);
        return encrDataContent.toByteArray();
    }

    /*
     * Create SafeContent Data content type.
V
vinnie 已提交
1763
     * Includes encrypted secret key in a SafeBag of type SecretBag.
D
duke 已提交
1764 1765 1766 1767 1768 1769 1770 1771
     * Includes encrypted private key in a SafeBag of type PKCS8ShroudedKeyBag.
     * Each PKCS8ShroudedKeyBag includes pkcs12 attributes
     * (see comments in getBagAttributes)
     */
    private byte[] createSafeContent()
        throws CertificateException, IOException {

        DerOutputStream out = new DerOutputStream();
V
vinnie 已提交
1772
        for (Enumeration<String> e = engineAliases(); e.hasMoreElements(); ) {
D
duke 已提交
1773 1774

            String alias = e.nextElement();
V
vinnie 已提交
1775 1776 1777 1778
            Entry entry = entries.get(alias);
            if (entry == null || (!(entry instanceof KeyEntry))) {
                continue;
            }
D
duke 已提交
1779
            DerOutputStream safeBag = new DerOutputStream();
V
vinnie 已提交
1780
            KeyEntry keyEntry = (KeyEntry) entry;
D
duke 已提交
1781

V
vinnie 已提交
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
            // DER encode the private key
            if (keyEntry instanceof PrivateKeyEntry) {
                // Create SafeBag of type pkcs8ShroudedKeyBag
                safeBag.putOID(PKCS8ShroudedKeyBag_OID);

                // get the encrypted private key
                byte[] encrBytes = ((PrivateKeyEntry)keyEntry).protectedPrivKey;
                EncryptedPrivateKeyInfo encrInfo = null;
                try {
                    encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
D
duke 已提交
1792

V
vinnie 已提交
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
                } catch (IOException ioe) {
                    throw new IOException("Private key not stored as "
                            + "PKCS#8 EncryptedPrivateKeyInfo"
                            + ioe.getMessage());
                }

                // Wrap the EncryptedPrivateKeyInfo in a context-specific tag.
                DerOutputStream bagValue = new DerOutputStream();
                bagValue.write(encrInfo.getEncoded());
                safeBag.write(DerValue.createTag(DerValue.TAG_CONTEXT,
D
duke 已提交
1803 1804
                                true, (byte) 0), bagValue);

V
vinnie 已提交
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
            // DER encode the secret key
            } else if (keyEntry instanceof SecretKeyEntry) {
                // Create SafeBag of type SecretBag
                safeBag.putOID(SecretBag_OID);

                // Create a SecretBag
                DerOutputStream secretBag = new DerOutputStream();
                secretBag.putOID(PKCS8ShroudedKeyBag_OID);

                // Write secret key in a context-specific tag
                DerOutputStream secretKeyValue = new DerOutputStream();
                secretKeyValue.putOctetString(
                    ((SecretKeyEntry) keyEntry).protectedSecretKey);
                secretBag.write(DerValue.createTag(DerValue.TAG_CONTEXT,
                                        true, (byte) 0), secretKeyValue);

                // Wrap SecretBag in a Sequence
                DerOutputStream secretBagSeq = new DerOutputStream();
                secretBagSeq.write(DerValue.tag_Sequence, secretBag);
                byte[] secretBagValue = secretBagSeq.toByteArray();

                // Wrap the secret bag in a context-specific tag.
                DerOutputStream bagValue = new DerOutputStream();
                bagValue.write(secretBagValue);

                // Write SafeBag value
                safeBag.write(DerValue.createTag(DerValue.TAG_CONTEXT,
                                    true, (byte) 0), bagValue);
            } else {
                continue; // skip this entry
            }

D
duke 已提交
1837
            // write SafeBag Attributes
V
vinnie 已提交
1838 1839
            byte[] bagAttrs =
                getBagAttributes(alias, entry.keyId, entry.attributes);
D
duke 已提交
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
            safeBag.write(bagAttrs);

            // wrap as Sequence
            out.write(DerValue.tag_Sequence, safeBag);
        }

        // wrap as Sequence
        DerOutputStream safeBagValue = new DerOutputStream();
        safeBagValue.write(DerValue.tag_Sequence, out);
        return safeBagValue.toByteArray();
    }


    /*
     * Encrypt the contents using Password-based (PBE) encryption
     * as defined in PKCS #5.
     *
     * NOTE: Currently pbeWithSHAAnd40BiteRC2-CBC algorithmID is used
     *       to derive the key and IV.
     *
     * @return encrypted contents encoded as EncryptedContentInfo
     */
    private byte[] encryptContent(byte[] data, char[] password)
        throws IOException {

        byte[] encryptedData = null;

        // create AlgorithmParameters
        AlgorithmParameters algParams =
1869
                getPBEAlgorithmParameters("PBEWithSHA1AndRC2_40");
D
duke 已提交
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
        DerOutputStream bytes = new DerOutputStream();
        AlgorithmId algId =
                new AlgorithmId(pbeWithSHAAnd40BitRC2CBC_OID, algParams);
        algId.encode(bytes);
        byte[] encodedAlgId = bytes.toByteArray();

        try {
            // Use JCE
            SecretKey skey = getPBEKey(password);
            Cipher cipher = Cipher.getInstance("PBEWithSHA1AndRC2_40");
            cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
            encryptedData = cipher.doFinal(data);

1883 1884 1885 1886 1887
            if (debug != null) {
                debug.println("  (Cipher algorithm: " + cipher.getAlgorithm() +
                    ")");
            }

D
duke 已提交
1888
        } catch (Exception e) {
1889 1890
            throw new IOException("Failed to encrypt" +
                    " safe contents entry: " + e, e);
D
duke 已提交
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
        }

        // create EncryptedContentInfo
        DerOutputStream bytes2 = new DerOutputStream();
        bytes2.putOID(ContentInfo.DATA_OID);
        bytes2.write(encodedAlgId);

        // Wrap encrypted data in a context-specific tag.
        DerOutputStream tmpout2 = new DerOutputStream();
        tmpout2.putOctetString(encryptedData);
        bytes2.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
                                        false, (byte)0), tmpout2);

        // wrap EncryptedContentInfo in a Sequence
        DerOutputStream out = new DerOutputStream();
        out.write(DerValue.tag_Sequence, bytes2);
        return out.toByteArray();
    }

    /**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
    public synchronized void engineLoad(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException
    {
        DataInputStream dis;
        CertificateFactory cf = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;

        if (stream == null)
           return;

        // reset the counter
        counter = 0;

        DerValue val = new DerValue(stream);
        DerInputStream s = val.toDerInputStream();
        int version = s.getInteger();

        if (version != VERSION_3) {
           throw new IOException("PKCS12 keystore not in version 3 format");
        }

        entries.clear();

        /*
         * Read the authSafe.
         */
        byte[] authSafeData;
        ContentInfo authSafe = new ContentInfo(s);
        ObjectIdentifier contentType = authSafe.getContentType();

1958
        if (contentType.equals((Object)ContentInfo.DATA_OID)) {
D
duke 已提交
1959 1960 1961 1962 1963 1964 1965 1966 1967
           authSafeData = authSafe.getData();
        } else /* signed data */ {
           throw new IOException("public key protected PKCS12 not supported");
        }

        DerInputStream as = new DerInputStream(authSafeData);
        DerValue[] safeContentsArray = as.getSequence(2);
        int count = safeContentsArray.length;

V
vinnie 已提交
1968
        // reset the counters at the start
D
duke 已提交
1969
        privateKeyCount = 0;
V
vinnie 已提交
1970 1971
        secretKeyCount = 0;
        certificateCount = 0;
D
duke 已提交
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985

        /*
         * Spin over the ContentInfos.
         */
        for (int i = 0; i < count; i++) {
            byte[] safeContentsData;
            ContentInfo safeContents;
            DerInputStream sci;
            byte[] eAlgId = null;

            sci = new DerInputStream(safeContentsArray[i].toByteArray());
            safeContents = new ContentInfo(sci);
            contentType = safeContents.getContentType();
            safeContentsData = null;
1986
            if (contentType.equals((Object)ContentInfo.DATA_OID)) {
1987 1988

                if (debug != null) {
1989
                    debug.println("Loading PKCS#7 data");
1990 1991
                }

D
duke 已提交
1992
                safeContentsData = safeContents.getData();
1993
            } else if (contentType.equals((Object)ContentInfo.ENCRYPTED_DATA_OID)) {
D
duke 已提交
1994
                if (password == null) {
1995 1996 1997

                    if (debug != null) {
                        debug.println("Warning: skipping PKCS#7 encryptedData" +
1998
                            " - no password was supplied");
1999 2000
                    }
                    continue;
D
duke 已提交
2001
                }
2002

D
duke 已提交
2003 2004 2005
                DerInputStream edi =
                                safeContents.getContent().toDerInputStream();
                int edVersion = edi.getInteger();
2006 2007 2008 2009 2010 2011
                DerValue[] seq = edi.getSequence(3);
                if (seq.length != 3) {
                    // We require the encryptedContent field, even though
                    // it is optional
                    throw new IOException("Invalid length for EncryptedContentInfo");
                }
D
duke 已提交
2012 2013 2014
                ObjectIdentifier edContentType = seq[0].getOID();
                eAlgId = seq[1].toByteArray();
                if (!seq[2].isContextSpecific((byte)0)) {
2015 2016
                    throw new IOException("unsupported encrypted content type "
                                          + seq[2].tag);
D
duke 已提交
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
                }
                byte newTag = DerValue.tag_OctetString;
                if (seq[2].isConstructed())
                   newTag |= 0x20;
                seq[2].resetTag(newTag);
                safeContentsData = seq[2].getOctetString();

                // parse Algorithm parameters
                DerInputStream in = seq[1].toDerInputStream();
                ObjectIdentifier algOid = in.getOID();
2027
                AlgorithmParameters algParams = parseAlgParameters(algOid, in);
D
duke 已提交
2028

2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
                PBEParameterSpec pbeSpec;
                int ic = 0;

                if (algParams != null) {
                    try {
                        pbeSpec =
                            algParams.getParameterSpec(PBEParameterSpec.class);
                    } catch (InvalidParameterSpecException ipse) {
                        throw new IOException(
                            "Invalid PBE algorithm parameters");
                    }
                    ic = pbeSpec.getIterationCount();

                    if (ic > MAX_ITERATION_COUNT) {
                        throw new IOException("PBE iteration count too large");
                    }
                }

                if (debug != null) {
                    debug.println("Loading PKCS#7 encryptedData " +
                        "(" + new AlgorithmId(algOid).getName() +
                        " iterations: " + ic + ")");
                }

2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
                while (true) {
                    try {
                        // Use JCE
                        SecretKey skey = getPBEKey(password);
                        Cipher cipher = Cipher.getInstance(algOid.toString());
                        cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
                        safeContentsData = cipher.doFinal(safeContentsData);
                        break;
                    } catch (Exception e) {
                        if (password.length == 0) {
                            // Retry using an empty password
                            // without a NULL terminator.
                            password = new char[1];
                            continue;
                        }
2068 2069 2070
                        throw new IOException("keystore password was incorrect",
                            new UnrecoverableKeyException(
                                "failed to decrypt safe contents entry: " + e));
2071
                    }
D
duke 已提交
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
                }
            } else {
                throw new IOException("public key protected PKCS12" +
                                        " not supported");
            }
            DerInputStream sc = new DerInputStream(safeContentsData);
            loadSafeContents(sc, password);
        }

        // The MacData is optional.
        if (password != null && s.available() > 0) {
2083 2084 2085 2086 2087 2088 2089 2090 2091
            MacData macData = new MacData(s);
            int ic = macData.getIterations();

            try {
                if (ic > MAX_ITERATION_COUNT) {
                    throw new InvalidAlgorithmParameterException(
                        "MAC iteration count too large: " + ic);
                }

2092 2093
                String algName =
                        macData.getDigestAlgName().toUpperCase(Locale.ENGLISH);
2094 2095 2096

                // Change SHA-1 to SHA1
                algName = algName.replace("-", "");
D
duke 已提交
2097 2098 2099 2100

                // generate MAC (MAC key is created within JCE)
                Mac m = Mac.getInstance("HmacPBE" + algName);
                PBEParameterSpec params =
2101
                        new PBEParameterSpec(macData.getSalt(), ic);
D
duke 已提交
2102 2103 2104 2105 2106
                SecretKey key = getPBEKey(password);
                m.init(key, params);
                m.update(authSafeData);
                byte[] macResult = m.doFinal();

2107 2108
                if (debug != null) {
                    debug.println("Checking keystore integrity " +
2109
                        "(" + m.getAlgorithm() + " iterations: " + ic + ")");
2110 2111
                }

2112
                if (!MessageDigest.isEqual(macData.getDigest(), macResult)) {
2113
                   throw new UnrecoverableKeyException("Failed PKCS12" +
D
duke 已提交
2114 2115
                                        " integrity checking");
                }
2116
            } catch (Exception e) {
2117
                throw new IOException("Integrity check failed: " + e, e);
2118
            }
D
duke 已提交
2119 2120 2121 2122 2123
        }

        /*
         * Match up private keys with certificate chains.
         */
V
vinnie 已提交
2124 2125
        PrivateKeyEntry[] list =
            keyList.toArray(new PrivateKeyEntry[keyList.size()]);
D
duke 已提交
2126
        for (int m = 0; m < list.length; m++) {
V
vinnie 已提交
2127
            PrivateKeyEntry entry = list[m];
D
duke 已提交
2128 2129 2130
            if (entry.keyId != null) {
                ArrayList<X509Certificate> chain =
                                new ArrayList<X509Certificate>();
W
weijun 已提交
2131
                X509Certificate cert = findMatchedCertificate(entry);
J
juh 已提交
2132 2133

                mainloop:
D
duke 已提交
2134
                while (cert != null) {
J
juh 已提交
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
                    // Check for loops in the certificate chain
                    if (!chain.isEmpty()) {
                        for (X509Certificate chainCert : chain) {
                            if (cert.equals(chainCert)) {
                                if (debug != null) {
                                    debug.println("Loop detected in " +
                                        "certificate chain. Skip adding " +
                                        "repeated cert to chain. Subject: " +
                                        cert.getSubjectX500Principal()
                                            .toString());
                                }
                                break mainloop;
                            }
                        }
                    }
D
duke 已提交
2150 2151 2152 2153 2154
                    chain.add(cert);
                    X500Principal issuerDN = cert.getIssuerX500Principal();
                    if (issuerDN.equals(cert.getSubjectX500Principal())) {
                        break;
                    }
W
weijun 已提交
2155
                    cert = certsMap.get(issuerDN);
D
duke 已提交
2156 2157 2158 2159 2160 2161
                }
                /* Update existing KeyEntry in entries table */
                if (chain.size() > 0)
                    entry.chain = chain.toArray(new Certificate[chain.size()]);
            }
        }
V
vinnie 已提交
2162 2163

        if (debug != null) {
2164 2165 2166
            debug.println("PKCS12KeyStore load: private key count: " +
                    privateKeyCount + ". secret key count: " + secretKeyCount +
                    ". certificate count: " + certificateCount);
V
vinnie 已提交
2167 2168
        }

W
weijun 已提交
2169 2170
        certEntries.clear();
        certsMap.clear();
D
duke 已提交
2171 2172 2173
        keyList.clear();
    }

W
weijun 已提交
2174 2175 2176 2177 2178
    /**
     * Locates a matched CertEntry from certEntries, and returns its cert.
     * @param entry the KeyEntry to match
     * @return a certificate, null if not found
     */
V
vinnie 已提交
2179
    private X509Certificate findMatchedCertificate(PrivateKeyEntry entry) {
W
weijun 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
        CertEntry keyIdMatch = null;
        CertEntry aliasMatch = null;
        for (CertEntry ce: certEntries) {
            if (Arrays.equals(entry.keyId, ce.keyId)) {
                keyIdMatch = ce;
                if (entry.alias.equalsIgnoreCase(ce.alias)) {
                    // Full match!
                    return ce.cert;
                }
            } else if (entry.alias.equalsIgnoreCase(ce.alias)) {
                aliasMatch = ce;
            }
        }
        // keyId match first, for compatibility
        if (keyIdMatch != null) return keyIdMatch.cert;
        else if (aliasMatch != null) return aliasMatch.cert;
        else return null;
    }
D
duke 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221

    private void loadSafeContents(DerInputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException
    {
        DerValue[] safeBags = stream.getSequence(2);
        int count = safeBags.length;

        /*
         * Spin over the SafeBags.
         */
        for (int i = 0; i < count; i++) {
            ObjectIdentifier bagId;
            DerInputStream sbi;
            DerValue bagValue;
            Object bagItem = null;

            sbi = safeBags[i].toDerInputStream();
            bagId = sbi.getOID();
            bagValue = sbi.getDerValue();
            if (!bagValue.isContextSpecific((byte)0)) {
                throw new IOException("unsupported PKCS12 bag value type "
                                        + bagValue.tag);
            }
            bagValue = bagValue.data.getDerValue();
2222
            if (bagId.equals((Object)PKCS8ShroudedKeyBag_OID)) {
V
vinnie 已提交
2223
                PrivateKeyEntry kEntry = new PrivateKeyEntry();
D
duke 已提交
2224 2225 2226
                kEntry.protectedPrivKey = bagValue.toByteArray();
                bagItem = kEntry;
                privateKeyCount++;
2227
            } else if (bagId.equals((Object)CertBag_OID)) {
D
duke 已提交
2228 2229
                DerInputStream cs = new DerInputStream(bagValue.toByteArray());
                DerValue[] certValues = cs.getSequence(2);
2230 2231 2232
                if (certValues.length != 2) {
                    throw new IOException("Invalid length for CertBag");
                }
D
duke 已提交
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
                ObjectIdentifier certId = certValues[0].getOID();
                if (!certValues[1].isContextSpecific((byte)0)) {
                    throw new IOException("unsupported PKCS12 cert value type "
                                        + certValues[1].tag);
                }
                DerValue certValue = certValues[1].data.getDerValue();
                CertificateFactory cf = CertificateFactory.getInstance("X509");
                X509Certificate cert;
                cert = (X509Certificate)cf.generateCertificate
                        (new ByteArrayInputStream(certValue.getOctetString()));
                bagItem = cert;
V
vinnie 已提交
2244 2245 2246 2247
                certificateCount++;
            } else if (bagId.equals((Object)SecretBag_OID)) {
                DerInputStream ss = new DerInputStream(bagValue.toByteArray());
                DerValue[] secretValues = ss.getSequence(2);
2248 2249 2250
                if (secretValues.length != 2) {
                    throw new IOException("Invalid length for SecretBag");
                }
V
vinnie 已提交
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
                ObjectIdentifier secretId = secretValues[0].getOID();
                if (!secretValues[1].isContextSpecific((byte)0)) {
                    throw new IOException(
                        "unsupported PKCS12 secret value type "
                                        + secretValues[1].tag);
                }
                DerValue secretValue = secretValues[1].data.getDerValue();
                SecretKeyEntry kEntry = new SecretKeyEntry();
                kEntry.protectedSecretKey = secretValue.getOctetString();
                bagItem = kEntry;
2261
                secretKeyCount++;
D
duke 已提交
2262
            } else {
2263 2264 2265 2266

                if (debug != null) {
                    debug.println("Unsupported PKCS12 bag type: " + bagId);
                }
D
duke 已提交
2267 2268 2269 2270
            }

            DerValue[] attrSet;
            try {
V
vinnie 已提交
2271
                attrSet = sbi.getSet(3);
D
duke 已提交
2272 2273 2274 2275 2276 2277 2278 2279 2280
            } catch (IOException e) {
                // entry does not have attributes
                // Note: CA certs can have no attributes
                // OpenSSL generates pkcs12 with no attr for CA certs.
                attrSet = null;
            }

            String alias = null;
            byte[] keyId = null;
V
vinnie 已提交
2281 2282
            ObjectIdentifier[] trustedKeyUsage = null;
            Set<PKCS12Attribute> attributes = new HashSet<>();
D
duke 已提交
2283 2284 2285

            if (attrSet != null) {
                for (int j = 0; j < attrSet.length; j++) {
V
vinnie 已提交
2286 2287
                    byte[] encoded = attrSet[j].toByteArray();
                    DerInputStream as = new DerInputStream(encoded);
D
duke 已提交
2288
                    DerValue[] attrSeq = as.getSequence(2);
2289 2290 2291
                    if (attrSeq.length != 2) {
                        throw new IOException("Invalid length for Attribute");
                    }
D
duke 已提交
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
                    ObjectIdentifier attrId = attrSeq[0].getOID();
                    DerInputStream vs =
                        new DerInputStream(attrSeq[1].toByteArray());
                    DerValue[] valSet;
                    try {
                        valSet = vs.getSet(1);
                    } catch (IOException e) {
                        throw new IOException("Attribute " + attrId +
                                " should have a value " + e.getMessage());
                    }
2302
                    if (attrId.equals((Object)PKCS9FriendlyName_OID)) {
D
duke 已提交
2303
                        alias = valSet[0].getBMPString();
2304
                    } else if (attrId.equals((Object)PKCS9LocalKeyId_OID)) {
D
duke 已提交
2305
                        keyId = valSet[0].getOctetString();
V
vinnie 已提交
2306 2307 2308 2309 2310
                    } else if
                        (attrId.equals((Object)TrustedKeyUsage_OID)) {
                        trustedKeyUsage = new ObjectIdentifier[valSet.length];
                        for (int k = 0; k < valSet.length; k++) {
                            trustedKeyUsage[k] = valSet[k].getOID();
2311
                        }
V
vinnie 已提交
2312 2313
                    } else {
                        attributes.add(new PKCS12Attribute(encoded));
D
duke 已提交
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
                    }
                }
            }

            /*
             * As per PKCS12 v1.0 friendlyname (alias) and localKeyId (keyId)
             * are optional PKCS12 bagAttributes. But entries in the keyStore
             * are identified by their alias. Hence we need to have an
             * Unfriendlyname in the alias, if alias is null. The keyId
             * attribute is required to match the private key with the
             * certificate. If we get a bagItem of type KeyEntry with a
             * null keyId, we should skip it entirely.
             */
            if (bagItem instanceof KeyEntry) {
                KeyEntry entry = (KeyEntry)bagItem;
V
vinnie 已提交
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341

                if (bagItem instanceof PrivateKeyEntry) {
                    if (keyId == null) {
                       // Insert a localKeyID for the privateKey
                       // Note: This is a workaround to allow null localKeyID
                       // attribute in pkcs12 with one private key entry and
                       // associated cert-chain
                       if (privateKeyCount == 1) {
                            keyId = "01".getBytes("UTF8");
                       } else {
                            continue;
                       }
                    }
D
duke 已提交
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
                }
                entry.keyId = keyId;
                // restore date if it exists
                String keyIdStr = new String(keyId, "UTF8");
                Date date = null;
                if (keyIdStr.startsWith("Time ")) {
                    try {
                        date = new Date(
                                Long.parseLong(keyIdStr.substring(5)));
                    } catch (Exception e) {
                        date = null;
                    }
                }
                if (date == null) {
                    date = new Date();
                }
                entry.date = date;
V
vinnie 已提交
2359 2360 2361 2362

                if (bagItem instanceof PrivateKeyEntry) {
                    keyList.add((PrivateKeyEntry) entry);
                }
2363 2364 2365 2366
                if (entry.attributes == null) {
                    entry.attributes = new HashSet<>();
                }
                entry.attributes.addAll(attributes);
V
vinnie 已提交
2367
                if (alias == null) {
D
duke 已提交
2368
                   alias = getUnfriendlyName();
V
vinnie 已提交
2369
                }
D
duke 已提交
2370
                entry.alias = alias;
2371
                entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
V
vinnie 已提交
2372

D
duke 已提交
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
            } else if (bagItem instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate)bagItem;
                // Insert a localKeyID for the corresponding cert
                // Note: This is a workaround to allow null localKeyID
                // attribute in pkcs12 with one private key entry and
                // associated cert-chain
                if ((keyId == null) && (privateKeyCount == 1)) {
                    // insert localKeyID only for EE cert or self-signed cert
                    if (i == 0) {
                        keyId = "01".getBytes("UTF8");
                    }
                }
V
vinnie 已提交
2385 2386
                // Trusted certificate
                if (trustedKeyUsage != null) {
2387 2388 2389
                    if (alias == null) {
                        alias = getUnfriendlyName();
                    }
V
vinnie 已提交
2390 2391 2392 2393 2394 2395 2396
                    CertEntry certEntry =
                        new CertEntry(cert, keyId, alias, trustedKeyUsage,
                            attributes);
                    entries.put(alias.toLowerCase(Locale.ENGLISH), certEntry);
                } else {
                    certEntries.add(new CertEntry(cert, keyId, alias));
                }
D
duke 已提交
2397 2398
                X500Principal subjectDN = cert.getSubjectX500Principal();
                if (subjectDN != null) {
W
weijun 已提交
2399 2400 2401
                    if (!certsMap.containsKey(subjectDN)) {
                        certsMap.put(subjectDN, cert);
                    }
D
duke 已提交
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
                }
            }
        }
    }

    private String getUnfriendlyName() {
        counter++;
        return (String.valueOf(counter));
    }
}