KeyStore.java 30.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2005, 2019, 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 29 30 31 32
 */

package sun.security.mscapi;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.AccessController;
33
import java.security.InvalidKeyException;
D
duke 已提交
34 35 36 37 38 39 40 41 42 43
import java.security.KeyStoreSpi;
import java.security.KeyStoreException;
import java.security.UnrecoverableKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecurityPermission;
import java.security.cert.X509Certificate;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateCrtKey;
44
import java.util.*;
D
duke 已提交
45 46 47

import sun.security.action.GetPropertyAction;

48 49
import sun.security.util.Debug;

D
duke 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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 115 116 117 118 119 120 121
/**
 * Implementation of key store for Windows using the Microsoft Crypto API.
 *
 * @since 1.6
 */
abstract class KeyStore extends KeyStoreSpi {

    public static final class MY extends KeyStore {
        public MY() {
            super("MY");
        }
    }

    public static final class ROOT extends KeyStore {
        public ROOT() {
            super("ROOT");
        }
    }

    class KeyEntry
    {
        private Key privateKey;
        private X509Certificate certChain[];
        private String alias;

        KeyEntry(Key key, X509Certificate[] chain) {
            this(null, key, chain);
        }

        KeyEntry(String alias, Key key, X509Certificate[] chain) {
            this.privateKey = key;
            this.certChain = chain;
            /*
             * The default alias for both entry types is derived from a
             * hash value intrinsic to the first certificate in the chain.
             */
             if (alias == null) {
                 this.alias = Integer.toString(chain[0].hashCode());
             } else {
                 this.alias = alias;
             }
        }

        /**
         * Gets the alias for the keystore entry.
         */
        String getAlias()
        {
            return alias;
        }

        /**
         * Sets the alias for the keystore entry.
         */
        void setAlias(String alias)
        {
            // TODO - set friendly name prop in cert store
            this.alias = alias;
        }

        /**
         * Gets the private key for the keystore entry.
         */
        Key getPrivateKey()
        {
            return privateKey;
        }

        /**
         * Sets the private key for the keystore entry.
         */
        void setPrivateKey(RSAPrivateCrtKey key)
122
            throws InvalidKeyException, KeyStoreException
D
duke 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        {
            byte[] modulusBytes = key.getModulus().toByteArray();

            // Adjust key length due to sign bit
            int keyBitLength = (modulusBytes[0] == 0)
                ? (modulusBytes.length - 1) * 8
                : modulusBytes.length * 8;

            byte[] keyBlob = generatePrivateKeyBlob(
                keyBitLength,
                modulusBytes,
                key.getPublicExponent().toByteArray(),
                key.getPrivateExponent().toByteArray(),
                key.getPrimeP().toByteArray(),
                key.getPrimeQ().toByteArray(),
                key.getPrimeExponentP().toByteArray(),
                key.getPrimeExponentQ().toByteArray(),
                key.getCrtCoefficient().toByteArray());

142
            privateKey = storePrivateKey(Objects.requireNonNull(keyBlob),
D
duke 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
                "{" + UUID.randomUUID().toString() + "}", keyBitLength);
        }

        /**
         * Gets the certificate chain for the keystore entry.
         */
        X509Certificate[] getCertificateChain()
        {
            return certChain;
        }

        /**
         * Sets the certificate chain for the keystore entry.
         */
        void setCertificateChain(X509Certificate[] chain)
158
            throws CertificateException, KeyStoreException
D
duke 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        {
            for (int i = 0; i < chain.length; i++) {
                byte[] encoding = chain[i].getEncoded();
                if (i == 0 && privateKey != null) {
                    storeCertificate(getName(), alias, encoding,
                        encoding.length, privateKey.getHCryptProvider(),
                        privateKey.getHCryptKey());

                } else {
                    storeCertificate(getName(), alias, encoding,
                        encoding.length, 0L, 0L); // no private key to attach
                }
            }
            certChain = chain;
        }
174
    }
D
duke 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

    /*
     * An X.509 certificate factory.
     * Used to create an X.509 certificate from its DER-encoding.
     */
    private CertificateFactory certificateFactory = null;

    /*
     * Compatibility mode: for applications that assume keystores are
     * stream-based this mode tolerates (but ignores) a non-null stream
     * or password parameter when passed to the load or store methods.
     * The mode is enabled by default.
     */
    private static final String KEYSTORE_COMPATIBILITY_MODE_PROP =
        "sun.security.mscapi.keyStoreCompatibilityMode";
    private final boolean keyStoreCompatibilityMode;
191
    private static final Debug debug = Debug.getInstance("keystore");
D
duke 已提交
192 193 194

    /*
     * The keystore entries.
195 196
     * Keys in the map are unique aliases (thus can differ from
     * KeyEntry.getAlias())
D
duke 已提交
197
     */
198
    private Map<String,KeyEntry> entries = new HashMap<>();
D
duke 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

    /*
     * The keystore name.
     * Case is not significant.
     */
    private final String storeName;

    KeyStore(String storeName) {
        // Get the compatibility mode
        String prop =
            AccessController.doPrivileged(
                new GetPropertyAction(KEYSTORE_COMPATIBILITY_MODE_PROP));

        if ("false".equalsIgnoreCase(prop)) {
            keyStoreCompatibilityMode = false;
        } else {
            keyStoreCompatibilityMode = true;
        }

        this.storeName = storeName;
    }

    /**
     * Returns the key associated with the given alias.
     * <p>
     * A compatibility mode is supported for applications that assume
     * a password must be supplied. It permits (but ignores) a non-null
     * <code>password</code>.  The mode is enabled by default.
     * Set the
     * <code>sun.security.mscapi.keyStoreCompatibilityMode</code>
     * system property to <code>false</code> to disable compatibility mode
     * and reject a non-null <code>password</code>.
     *
     * @param alias the alias name
     * @param password the password, which should be <code>null</code>
     *
     * @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,
     * or if compatibility mode is disabled and <code>password</code> is
     * non-null.
     * @exception UnrecoverableKeyException if the key cannot be recovered.
     */
    public java.security.Key engineGetKey(String alias, char[] password)
        throws NoSuchAlgorithmException, UnrecoverableKeyException
    {
        if (alias == null) {
            return null;
        }

        if (password != null && !keyStoreCompatibilityMode) {
            throw new UnrecoverableKeyException("Password must be null");
        }

        if (engineIsKeyEntry(alias) == false)
            return null;

258 259 260 261
        KeyEntry entry = entries.get(alias);
        return (entry == null)
                ? null
                : entry.getPrivateKey();
D
duke 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    }

    /**
     * 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)
    {
        if (alias == null) {
            return null;
        }

281 282 283 284 285 286 287
        KeyEntry entry = entries.get(alias);
        X509Certificate[] certChain = (entry == null)
                ? null
                : entry.getCertificateChain();
        return (certChain == null)
                ? null
                : certChain.clone();
D
duke 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    }

    /**
     * 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)
    {
        if (alias == null) {
            return null;
        }

311 312 313 314 315 316 317
        KeyEntry entry = entries.get(alias);
        X509Certificate[] certChain = (entry == null)
                ? null
                : entry.getCertificateChain();
        return (certChain == null || certChain.length == 0)
                ? null
                : certChain[0];
D
duke 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    }

    /**
     * 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) {
        if (alias == null) {
            return null;
        }
        return new Date();
    }

    /**
     * Stores the given private key and associated certificate chain in the
     * keystore.
     *
     * <p>The given java.security.PrivateKey <code>key</code> 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 certificate
     * chain. Otherwise, a new entry is created.
     *
     * <p>
     * A compatibility mode is supported for applications that assume
     * a password must be supplied. It permits (but ignores) a non-null
     * <code>password</code>.  The mode is enabled by default.
     * Set the
     * <code>sun.security.mscapi.keyStoreCompatibilityMode</code>
     * system property to <code>false</code> to disable compatibility mode
     * and reject a non-null <code>password</code>.
     *
     * @param alias the alias name
     * @param key the private key to be associated with the alias
     * @param password the password, which should be <code>null</code>
     * @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 is not a private key,
     * cannot be protected, or if compatibility mode is disabled and
     * <code>password</code> is non-null, or if this operation fails for
     * some other reason.
     */
    public void engineSetKeyEntry(String alias, java.security.Key key,
        char[] password, Certificate[] chain) throws KeyStoreException
    {
        if (alias == null) {
            throw new KeyStoreException("alias must not be null");
        }

        if (password != null && !keyStoreCompatibilityMode) {
            throw new KeyStoreException("Password must be null");
        }

        if (key instanceof RSAPrivateCrtKey) {

381
            KeyEntry entry = entries.get(alias);
D
duke 已提交
382

383 384 385 386 387 388 389
            X509Certificate[] xchain;
            if (chain != null) {
                if (chain instanceof X509Certificate[]) {
                    xchain = (X509Certificate[]) chain;
                } else {
                    xchain = new X509Certificate[chain.length];
                    System.arraycopy(chain, 0, xchain, 0, chain.length);
D
duke 已提交
390
                }
391 392
            } else {
                xchain = null;
D
duke 已提交
393 394
            }

395
            if (entry == null) {
D
duke 已提交
396 397
                entry =
                    //TODO new KeyEntry(alias, key, (X509Certificate[]) chain);
398 399
                    new KeyEntry(alias, null, xchain);
                storeWithUniqueAlias(alias, entry);
D
duke 已提交
400 401 402 403 404
            }

            entry.setAlias(alias);

            try {
405
                entry.setPrivateKey((RSAPrivateCrtKey) key);
406
                entry.setCertificateChain(xchain);
D
duke 已提交
407 408 409

            } catch (CertificateException ce) {
                throw new KeyStoreException(ce);
410 411 412

            } catch (InvalidKeyException ike) {
                throw new KeyStoreException(ike);
D
duke 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
            }

        } else {
            throw new UnsupportedOperationException(
                "Cannot assign the key to the given alias.");
        }
    }

    /**
     * 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 void engineSetKeyEntry(String alias, byte[] key,
                                  Certificate[] chain)
        throws KeyStoreException
    {
        throw new UnsupportedOperationException(
            "Cannot assign the encoded key to the given alias.");
    }

    /**
     * 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
     * not identify a <i>trusted certificate entry</i>, or this operation
     * fails for some other reason.
     */
    public void engineSetCertificateEntry(String alias, Certificate cert)
        throws KeyStoreException
    {
        if (alias == null) {
            throw new KeyStoreException("alias must not be null");
        }

        if (cert instanceof X509Certificate) {

            // TODO - build CryptoAPI chain?
            X509Certificate[] chain =
                new X509Certificate[]{ (X509Certificate) cert };
478
            KeyEntry entry = entries.get(alias);
D
duke 已提交
479

480
            if (entry == null) {
D
duke 已提交
481 482
                entry =
                    new KeyEntry(alias, null, chain);
483
                storeWithUniqueAlias(alias, entry);
D
duke 已提交
484
            }
485

D
duke 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
            if (entry.getPrivateKey() == null) { // trusted-cert entry
                entry.setAlias(alias);

                try {
                    entry.setCertificateChain(chain);

                } catch (CertificateException ce) {
                    throw new KeyStoreException(ce);
                }
            }

        } else {
            throw new UnsupportedOperationException(
                "Cannot assign the certificate to the given alias.");
        }
    }

    /**
     * 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 void engineDeleteEntry(String alias)
        throws KeyStoreException
    {
        if (alias == null) {
            throw new KeyStoreException("alias must not be null");
        }

517 518 519 520 521
        KeyEntry entry = entries.remove(alias);
        if (entry != null) {
            // Get end-entity certificate and remove from system cert store
            X509Certificate[] certChain = entry.getCertificateChain();
            if (certChain != null) {
D
duke 已提交
522

523
                try {
D
duke 已提交
524

525 526
                    byte[] encoding = certChain[0].getEncoded();
                    removeCertificate(getName(), entry.getAlias(), encoding,
D
duke 已提交
527 528
                            encoding.length);

529 530
                } catch (CertificateException e) {
                    throw new KeyStoreException("Cannot remove entry: ", e);
D
duke 已提交
531
                }
532 533 534 535 536
            }
            Key privateKey = entry.getPrivateKey();
            if (privateKey != null) {
                destroyKeyContainer(
                    Key.getContainerName(privateKey.getHCryptProvider()));
D
duke 已提交
537 538 539 540 541 542 543 544 545
            }
        }
    }

    /**
     * Lists all the alias names of this keystore.
     *
     * @return enumeration of the alias names
     */
546
    public Enumeration<String> engineAliases() {
547
        final Iterator<String> iter = entries.keySet().iterator();
D
duke 已提交
548

549
        return new Enumeration<String>()
D
duke 已提交
550 551 552 553 554 555
        {
            public boolean hasMoreElements()
            {
                return iter.hasNext();
            }

556
            public String nextElement()
D
duke 已提交
557
            {
558
                return iter.next();
D
duke 已提交
559 560 561 562 563 564 565 566 567 568 569 570
            }
        };
    }

    /**
     * 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) {
571
        return entries.containsKey(alias);
D
duke 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
    }

    /**
     * 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) {

        if (alias == null) {
            return false;
        }

596 597
        KeyEntry entry = entries.get(alias);
        return entry != null && entry.getPrivateKey() != null;
D
duke 已提交
598 599 600 601 602 603 604 605 606
    }

    /**
     * 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.
     */
607 608 609 610
    public boolean engineIsCertificateEntry(String alias) {

        if (alias == null) {
            return false;
D
duke 已提交
611 612
        }

613 614
        KeyEntry entry = entries.get(alias);
        return entry != null && entry.getPrivateKey() == null;
D
duke 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    }

    /**
     * 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.
     */
633 634 635 636
    public String engineGetCertificateAlias(Certificate cert) {

        for (Map.Entry<String,KeyEntry> mapEntry : entries.entrySet()) {
            KeyEntry entry = mapEntry.getValue();
D
duke 已提交
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 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 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
            if (entry.certChain != null && entry.certChain[0].equals(cert)) {
                return entry.getAlias();
            }
        }

        return null;
    }

    /**
     * engineStore is currently a no-op.
     * Entries are stored during engineSetEntry.
     *
     * A compatibility mode is supported for applications that assume
     * keystores are stream-based. It permits (but ignores) a non-null
     * <code>stream</code> or <code>password</code>.
     * The mode is enabled by default.
     * Set the
     * <code>sun.security.mscapi.keyStoreCompatibilityMode</code>
     * system property to <code>false</code> to disable compatibility mode
     * and reject a non-null <code>stream</code> or <code>password</code>.
     *
     * @param stream the output stream, which should be <code>null</code>
     * @param password the password, which should be <code>null</code>
     *
     * @exception IOException if compatibility mode is disabled and either
     * parameter is non-null.
     */
    public void engineStore(OutputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException
    {
        if (stream != null && !keyStoreCompatibilityMode) {
            throw new IOException("Keystore output stream must be null");
        }

        if (password != null && !keyStoreCompatibilityMode) {
            throw new IOException("Keystore password must be null");
        }
    }

    /**
     * Loads the keystore.
     *
     * A compatibility mode is supported for applications that assume
     * keystores are stream-based. It permits (but ignores) a non-null
     * <code>stream</code> or <code>password</code>.
     * The mode is enabled by default.
     * Set the
     * <code>sun.security.mscapi.keyStoreCompatibilityMode</code>
     * system property to <code>false</code> to disable compatibility mode
     * and reject a non-null <code>stream</code> or <code>password</code>.
     *
     * @param stream the input stream, which should be <code>null</code>.
     * @param password the password, which should be <code>null</code>.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data. Or if compatibility mode is disabled and either
     * parameter is non-null.
     * @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
     * @exception SecurityException if the security check for
     *  <code>SecurityPermission("authProvider.<i>name</i>")</code> does not
     *  pass, where <i>name</i> is the value returned by
     *  this provider's <code>getName</code> method.
     */
    public void engineLoad(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException
    {
        if (stream != null && !keyStoreCompatibilityMode) {
            throw new IOException("Keystore input stream must be null");
        }

        if (password != null && !keyStoreCompatibilityMode) {
            throw new IOException("Keystore password must be null");
        }

        /*
         * Use the same security check as AuthProvider.login
         */
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new SecurityPermission(
                "authProvider.SunMSCAPI"));
        }

        // Clear all key entries
        entries.clear();

726 727 728
        try {

            // Load keys and/or certificate chains
729
            loadKeysOrCertificateChains(getName());
730 731 732 733

        } catch (KeyStoreException e) {
            throw new IOException(e);
        }
734 735 736 737 738

        if (debug != null) {
            debug.println("MSCAPI keystore load: entry count: " +
                    entries.size());
        }
D
duke 已提交
739 740
    }

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
    /**
     * Stores the given entry into the map, making sure
     * the alias, used as the key is unique.
     * If the same alias already exists, it tries to append
     * a suffix  (1), (2), etc to it until it finds a unique
     * value.
     */
    private void storeWithUniqueAlias(String alias, KeyEntry entry) {
        String uniqAlias = alias;
        int uniqNum = 1;

        while (true) {
            if (entries.putIfAbsent(uniqAlias, entry) == null) {
                break;
            }
            uniqAlias = alias + " (" + (uniqNum++) + ")";
        }
    }


D
duke 已提交
761 762 763
    /**
     * Generates a certificate chain from the collection of
     * certificates and stores the result into a key entry.
764
     * This method is called by native code in libsunmscapi.
D
duke 已提交
765 766
     */
    private void generateCertificateChain(String alias,
767
        Collection<? extends Certificate> certCollection)
D
duke 已提交
768 769 770 771 772 773 774
    {
        try
        {
            X509Certificate[] certChain =
                new X509Certificate[certCollection.size()];

            int i = 0;
775 776
            for (Iterator<? extends Certificate> iter =
                    certCollection.iterator(); iter.hasNext(); i++)
D
duke 已提交
777 778 779 780
            {
                certChain[i] = (X509Certificate) iter.next();
            }

781 782
            storeWithUniqueAlias(alias,
                    new KeyEntry(alias, null, certChain));
D
duke 已提交
783 784 785 786
        }
        catch (Throwable e)
        {
            // Ignore the exception and skip this entry
787 788
            // If e is thrown, remember to deal with it in
            // native code.
D
duke 已提交
789 790 791 792 793 794
        }
    }

    /**
     * Generates RSA key and certificate chain from the private key handle,
     * collection of certificates and stores the result into key entries.
795
     * This method is called by native code in libsunmscapi.
D
duke 已提交
796 797 798
     */
    private void generateRSAKeyAndCertificateChain(String alias,
        long hCryptProv, long hCryptKey, int keyLength,
799
        Collection<? extends Certificate> certCollection)
D
duke 已提交
800 801 802 803 804 805 806
    {
        try
        {
            X509Certificate[] certChain =
                new X509Certificate[certCollection.size()];

            int i = 0;
807 808
            for (Iterator<? extends Certificate> iter =
                    certCollection.iterator(); iter.hasNext(); i++)
D
duke 已提交
809 810 811 812
            {
                certChain[i] = (X509Certificate) iter.next();
            }

813
            storeWithUniqueAlias(alias, new KeyEntry(alias,
814 815
                    new RSAPrivateKey(new Key.NativeHandles(hCryptProv,
                            hCryptKey), keyLength),
816
                    certChain));
D
duke 已提交
817 818 819 820
        }
        catch (Throwable e)
        {
            // Ignore the exception and skip this entry
821 822
            // If e is thrown, remember to deal with it in
            // native code.
D
duke 已提交
823 824 825 826 827
        }
    }

    /**
     * Generates certificates from byte data and stores into cert collection.
828
     * This method is called by native code in libsunmscapi.
D
duke 已提交
829 830 831 832
     *
     * @param data Byte data.
     * @param certCollection Collection of certificates.
     */
833 834
    private void generateCertificate(byte[] data,
        Collection<Certificate> certCollection) {
D
duke 已提交
835 836 837 838 839 840
        try
        {
            ByteArrayInputStream bis = new ByteArrayInputStream(data);

            // Obtain certificate factory
            if (certificateFactory == null) {
841
                certificateFactory = CertificateFactory.getInstance("X.509", "SUN");
D
duke 已提交
842 843 844
            }

            // Generate certificate
845 846
            Collection<? extends Certificate> c =
                    certificateFactory.generateCertificates(bis);
D
duke 已提交
847 848 849 850 851
            certCollection.addAll(c);
        }
        catch (CertificateException e)
        {
            // Ignore the exception and skip this certificate
852 853
            // If e is thrown, remember to deal with it in
            // native code.
D
duke 已提交
854 855 856 857
        }
        catch (Throwable te)
        {
            // Ignore the exception and skip this certificate
858 859
            // If e is thrown, remember to deal with it in
            // native code.
D
duke 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
        }
    }

    /**
     * Returns the name of the keystore.
     */
    private String getName()
    {
        return storeName;
    }

    /**
     * Load keys and/or certificates from keystore into Collection.
     *
     * @param name Name of keystore.
     */
876 877
    private native void loadKeysOrCertificateChains(String name)
            throws KeyStoreException;
D
duke 已提交
878 879 880 881 882 883 884 885 886 887

    /**
     * Stores a DER-encoded certificate into the certificate store
     *
     * @param name Name of the keystore.
     * @param alias Name of the certificate.
     * @param encoding DER-encoded certificate.
     */
    private native void storeCertificate(String name, String alias,
        byte[] encoding, int encodingLength, long hCryptProvider,
888
        long hCryptKey) throws CertificateException, KeyStoreException;
D
duke 已提交
889 890 891 892 893 894 895 896 897

    /**
     * Removes the certificate from the certificate store
     *
     * @param name Name of the keystore.
     * @param alias Name of the certificate.
     * @param encoding DER-encoded certificate.
     */
    private native void removeCertificate(String name, String alias,
898 899
        byte[] encoding, int encodingLength)
            throws CertificateException, KeyStoreException;
D
duke 已提交
900 901 902 903 904 905

    /**
     * Destroys the key container.
     *
     * @param keyContainerName The name of the key container.
     */
906 907
    private native void destroyKeyContainer(String keyContainerName)
        throws KeyStoreException;
D
duke 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920

    /**
     * Generates a private-key BLOB from a key's components.
     */
    private native byte[] generatePrivateKeyBlob(
        int keyBitLength,
        byte[] modulus,
        byte[] publicExponent,
        byte[] privateExponent,
        byte[] primeP,
        byte[] primeQ,
        byte[] exponentP,
        byte[] exponentQ,
921
        byte[] crtCoefficient) throws InvalidKeyException;
D
duke 已提交
922 923

    private native RSAPrivateKey storePrivateKey(byte[] keyBlob,
924
        String keyContainerName, int keySize) throws KeyStoreException;
D
duke 已提交
925
}