Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/macosx/classes/apple/security/KeychainStore.java
38829 views
/*1* Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package apple.security;2627import java.io.*;28import java.security.*;29import java.security.cert.*;30import java.security.cert.Certificate;31import java.security.spec.*;32import java.util.*;3334import javax.crypto.*;35import javax.crypto.spec.*;36import javax.security.auth.x500.*;3738import sun.security.pkcs.*;39import sun.security.pkcs.EncryptedPrivateKeyInfo;40import sun.security.util.*;41import sun.security.x509.*;4243/**44* This class provides the keystore implementation referred to as "KeychainStore".45* It uses the current user's keychain as its backing storage, and does NOT support46* a file-based implementation.47*/4849public final class KeychainStore extends KeyStoreSpi {5051// Private keys and their supporting certificate chains52// If a key came from the keychain it has a SecKeyRef and one or more53// SecCertificateRef. When we delete the key we have to delete all of the corresponding54// native objects.55class KeyEntry {56Date date; // the creation date of this entry57byte[] protectedPrivKey;58char[] password;59long keyRef; // SecKeyRef for this key60Certificate chain[];61long chainRefs[]; // SecCertificateRefs for this key's chain.62};6364// Trusted certificates65class TrustedCertEntry {66Date date; // the creation date of this entry6768Certificate cert;69long certRef; // SecCertificateRef for this key70};7172/**73* Entries that have been deleted. When something calls engineStore we'll74* remove them from the keychain.75*/76private Hashtable deletedEntries = new Hashtable();7778/**79* Entries that have been added. When something calls engineStore we'll80* add them to the keychain.81*/82private Hashtable addedEntries = new Hashtable();8384/**85* Private keys and certificates are stored in a hashtable.86* Hash entries are keyed by alias names.87*/88private Hashtable entries = new Hashtable();8990/**91* Algorithm identifiers and corresponding OIDs for the contents of the PKCS12 bag we get from the Keychain.92*/93private static final int keyBag[] = {1, 2, 840, 113549, 1, 12, 10, 1, 2};94private static final int pbeWithSHAAnd3KeyTripleDESCBC[] = {1, 2, 840, 113549, 1, 12, 1, 3};95private static ObjectIdentifier PKCS8ShroudedKeyBag_OID;96private static ObjectIdentifier pbeWithSHAAnd3KeyTripleDESCBC_OID;9798/**99* Constnats used in PBE decryption.100*/101private static final int iterationCount = 1024;102private static final int SALT_LEN = 20;103104private static final Debug debug = Debug.getInstance("keystore");105106static {107AccessController.doPrivileged(108new PrivilegedAction<Void>() {109public Void run() {110System.loadLibrary("osx");111return null;112}113});114try {115PKCS8ShroudedKeyBag_OID = new ObjectIdentifier(keyBag);116pbeWithSHAAnd3KeyTripleDESCBC_OID = new ObjectIdentifier(pbeWithSHAAnd3KeyTripleDESCBC);117} catch (IOException ioe) {118// should not happen119}120}121122private static void permissionCheck() {123SecurityManager sec = System.getSecurityManager();124125if (sec != null) {126sec.checkPermission(new RuntimePermission("useKeychainStore"));127}128}129130131/**132* Verify the Apple provider in the constructor.133*134* @exception SecurityException if fails to verify135* its own integrity136*/137public KeychainStore() { }138139/**140* Returns the key associated with the given alias, using the given141* password to recover it.142*143* @param alias the alias name144* @param password the password for recovering the key. This password is145* used internally as the key is exported in a PKCS12 format.146*147* @return the requested key, or null if the given alias does not exist148* or does not identify a <i>key entry</i>.149*150* @exception NoSuchAlgorithmException if the algorithm for recovering the151* key cannot be found152* @exception UnrecoverableKeyException if the key cannot be recovered153* (e.g., the given password is wrong).154*/155public Key engineGetKey(String alias, char[] password)156throws NoSuchAlgorithmException, UnrecoverableKeyException157{158permissionCheck();159160// An empty password is rejected by MacOS API, no private key data161// is exported. If no password is passed (as is the case when162// this implementation is used as browser keystore in various163// deployment scenarios like Webstart, JFX and applets), create164// a dummy password so MacOS API is happy.165if (password == null || password.length == 0) {166// Must not be a char array with only a 0, as this is an empty167// string.168if (random == null) {169random = new SecureRandom();170}171password = Long.toString(random.nextLong()).toCharArray();172}173174Object entry = entries.get(alias.toLowerCase());175176if (entry == null || !(entry instanceof KeyEntry)) {177return null;178}179180// This call gives us a PKCS12 bag, with the key inside it.181byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry)entry).keyRef, password);182if (exportedKeyInfo == null) {183return null;184}185186PrivateKey returnValue = null;187188try {189byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);190byte[] encryptedKey;191AlgorithmParameters algParams;192ObjectIdentifier algOid;193try {194// get the encrypted private key195EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);196encryptedKey = encrInfo.getEncryptedData();197198// parse Algorithm parameters199DerValue val = new DerValue(encrInfo.getAlgorithm().encode());200DerInputStream in = val.toDerInputStream();201algOid = in.getOID();202algParams = parseAlgParameters(in);203204} catch (IOException ioe) {205UnrecoverableKeyException uke =206new UnrecoverableKeyException("Private key not stored as "207+ "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);208uke.initCause(ioe);209throw uke;210}211212// Use JCE to decrypt the data using the supplied password.213SecretKey skey = getPBEKey(password);214Cipher cipher = Cipher.getInstance(algOid.toString());215cipher.init(Cipher.DECRYPT_MODE, skey, algParams);216byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);217PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);218219// Parse the key algorithm and then use a JCA key factory to create the private key.220DerValue val = new DerValue(decryptedPrivateKey);221DerInputStream in = val.toDerInputStream();222223// Ignore this -- version should be 0.224int i = in.getInteger();225226// Get the Algorithm ID next227DerValue[] value = in.getSequence(2);228if (value.length < 1 || value.length > 2) {229throw new IOException("Invalid length for AlgorithmIdentifier");230}231AlgorithmId algId = new AlgorithmId(value[0].getOID());232String algName = algId.getName();233234// Get a key factory for this algorithm. It's likely to be 'RSA'.235KeyFactory kfac = KeyFactory.getInstance(algName);236returnValue = kfac.generatePrivate(kspec);237} catch (Exception e) {238UnrecoverableKeyException uke =239new UnrecoverableKeyException("Get Key failed: " +240e.getMessage());241uke.initCause(e);242throw uke;243}244245return returnValue;246}247248private native byte[] _getEncodedKeyData(long secKeyRef, char[] password);249250/**251* Returns the certificate chain associated with the given alias.252*253* @param alias the alias name254*255* @return the certificate chain (ordered with the user's certificate first256* and the root certificate authority last), or null if the given alias257* does not exist or does not contain a certificate chain (i.e., the given258* alias identifies either a <i>trusted certificate entry</i> or a259* <i>key entry</i> without a certificate chain).260*/261public Certificate[] engineGetCertificateChain(String alias) {262permissionCheck();263264Object entry = entries.get(alias.toLowerCase());265266if (entry != null && entry instanceof KeyEntry) {267if (((KeyEntry)entry).chain == null) {268return null;269} else {270return (Certificate[])((KeyEntry)entry).chain.clone();271}272} else {273return null;274}275}276277/**278* Returns the certificate associated with the given alias.279*280* <p>If the given alias name identifies a281* <i>trusted certificate entry</i>, the certificate associated with that282* entry is returned. If the given alias name identifies a283* <i>key entry</i>, the first element of the certificate chain of that284* entry is returned, or null if that entry does not have a certificate285* chain.286*287* @param alias the alias name288*289* @return the certificate, or null if the given alias does not exist or290* does not contain a certificate.291*/292public Certificate engineGetCertificate(String alias) {293permissionCheck();294295Object entry = entries.get(alias.toLowerCase());296297if (entry != null) {298if (entry instanceof TrustedCertEntry) {299return ((TrustedCertEntry)entry).cert;300} else {301if (((KeyEntry)entry).chain == null) {302return null;303} else {304return ((KeyEntry)entry).chain[0];305}306}307} else {308return null;309}310}311312/**313* Returns the creation date of the entry identified by the given alias.314*315* @param alias the alias name316*317* @return the creation date of this entry, or null if the given alias does318* not exist319*/320public Date engineGetCreationDate(String alias) {321permissionCheck();322323Object entry = entries.get(alias.toLowerCase());324325if (entry != null) {326if (entry instanceof TrustedCertEntry) {327return new Date(((TrustedCertEntry)entry).date.getTime());328} else {329return new Date(((KeyEntry)entry).date.getTime());330}331} else {332return null;333}334}335336/**337* Assigns the given key to the given alias, protecting it with the given338* password.339*340* <p>If the given key is of type <code>java.security.PrivateKey</code>,341* it must be accompanied by a certificate chain certifying the342* corresponding public key.343*344* <p>If the given alias already exists, the keystore information345* associated with it is overridden by the given key (and possibly346* certificate chain).347*348* @param alias the alias name349* @param key the key to be associated with the alias350* @param password the password to protect the key351* @param chain the certificate chain for the corresponding public352* key (only required if the given key is of type353* <code>java.security.PrivateKey</code>).354*355* @exception KeyStoreException if the given key cannot be protected, or356* this operation fails for some other reason357*/358public void engineSetKeyEntry(String alias, Key key, char[] password,359Certificate[] chain)360throws KeyStoreException361{362permissionCheck();363364synchronized(entries) {365try {366KeyEntry entry = new KeyEntry();367entry.date = new Date();368369if (key instanceof PrivateKey) {370if ((key.getFormat().equals("PKCS#8")) ||371(key.getFormat().equals("PKCS8"))) {372entry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), password);373entry.password = password.clone();374} else {375throw new KeyStoreException("Private key is not encoded as PKCS#8");376}377} else {378throw new KeyStoreException("Key is not a PrivateKey");379}380381// clone the chain382if (chain != null) {383if ((chain.length > 1) && !validateChain(chain)) {384throw new KeyStoreException("Certificate chain does not validate");385}386387entry.chain = (Certificate[])chain.clone();388entry.chainRefs = new long[entry.chain.length];389}390391String lowerAlias = alias.toLowerCase();392if (entries.get(lowerAlias) != null) {393deletedEntries.put(lowerAlias, entries.get(lowerAlias));394}395396entries.put(lowerAlias, entry);397addedEntries.put(lowerAlias, entry);398} catch (Exception nsae) {399KeyStoreException ke = new KeyStoreException("Key protection algorithm not found: " + nsae);400ke.initCause(nsae);401throw ke;402}403}404}405406/**407* Assigns the given key (that has already been protected) to the given408* alias.409*410* <p>If the protected key is of type411* <code>java.security.PrivateKey</code>, it must be accompanied by a412* certificate chain certifying the corresponding public key. If the413* underlying keystore implementation is of type <code>jks</code>,414* <code>key</code> must be encoded as an415* <code>EncryptedPrivateKeyInfo</code> as defined in the PKCS #8 standard.416*417* <p>If the given alias already exists, the keystore information418* associated with it is overridden by the given key (and possibly419* certificate chain).420*421* @param alias the alias name422* @param key the key (in protected format) to be associated with the alias423* @param chain the certificate chain for the corresponding public424* key (only useful if the protected key is of type425* <code>java.security.PrivateKey</code>).426*427* @exception KeyStoreException if this operation fails.428*/429public void engineSetKeyEntry(String alias, byte[] key,430Certificate[] chain)431throws KeyStoreException432{433permissionCheck();434435synchronized(entries) {436// key must be encoded as EncryptedPrivateKeyInfo as defined in437// PKCS#8438KeyEntry entry = new KeyEntry();439try {440EncryptedPrivateKeyInfo privateKey = new EncryptedPrivateKeyInfo(key);441entry.protectedPrivKey = privateKey.getEncoded();442} catch (IOException ioe) {443throw new KeyStoreException("key is not encoded as "444+ "EncryptedPrivateKeyInfo");445}446447entry.date = new Date();448449if ((chain != null) &&450(chain.length != 0)) {451entry.chain = (Certificate[])chain.clone();452entry.chainRefs = new long[entry.chain.length];453}454455String lowerAlias = alias.toLowerCase();456if (entries.get(lowerAlias) != null) {457deletedEntries.put(lowerAlias, entries.get(alias));458}459entries.put(lowerAlias, entry);460addedEntries.put(lowerAlias, entry);461}462}463464/**465* Assigns the given certificate to the given alias.466*467* <p>If the given alias already exists in this keystore and identifies a468* <i>trusted certificate entry</i>, the certificate associated with it is469* overridden by the given certificate.470*471* @param alias the alias name472* @param cert the certificate473*474* @exception KeyStoreException if the given alias already exists and does475* not identify a <i>trusted certificate entry</i>, or this operation476* fails for some other reason.477*/478public void engineSetCertificateEntry(String alias, Certificate cert)479throws KeyStoreException480{481permissionCheck();482483synchronized(entries) {484485Object entry = entries.get(alias.toLowerCase());486if ((entry != null) && (entry instanceof KeyEntry)) {487throw new KeyStoreException488("Cannot overwrite key entry with certificate");489}490491// This will be slow, but necessary. Enumerate the values and then see if the cert matches the one in the trusted cert entry.492// Security framework doesn't support the same certificate twice in a keychain.493Collection allValues = entries.values();494495for (Object value : allValues) {496if (value instanceof TrustedCertEntry) {497TrustedCertEntry tce = (TrustedCertEntry)value;498if (tce.cert.equals(cert)) {499throw new KeyStoreException("Keychain does not support mulitple copies of same certificate.");500}501}502}503504TrustedCertEntry trustedCertEntry = new TrustedCertEntry();505trustedCertEntry.cert = cert;506trustedCertEntry.date = new Date();507String lowerAlias = alias.toLowerCase();508if (entries.get(lowerAlias) != null) {509deletedEntries.put(lowerAlias, entries.get(lowerAlias));510}511entries.put(lowerAlias, trustedCertEntry);512addedEntries.put(lowerAlias, trustedCertEntry);513}514}515516/**517* Deletes the entry identified by the given alias from this keystore.518*519* @param alias the alias name520*521* @exception KeyStoreException if the entry cannot be removed.522*/523public void engineDeleteEntry(String alias)524throws KeyStoreException525{526permissionCheck();527528synchronized(entries) {529Object entry = entries.remove(alias.toLowerCase());530deletedEntries.put(alias.toLowerCase(), entry);531}532}533534/**535* Lists all the alias names of this keystore.536*537* @return enumeration of the alias names538*/539public Enumeration engineAliases() {540permissionCheck();541return entries.keys();542}543544/**545* Checks if the given alias exists in this keystore.546*547* @param alias the alias name548*549* @return true if the alias exists, false otherwise550*/551public boolean engineContainsAlias(String alias) {552permissionCheck();553return entries.containsKey(alias.toLowerCase());554}555556/**557* Retrieves the number of entries in this keystore.558*559* @return the number of entries in this keystore560*/561public int engineSize() {562permissionCheck();563return entries.size();564}565566/**567* Returns true if the entry identified by the given alias is a568* <i>key entry</i>, and false otherwise.569*570* @return true if the entry identified by the given alias is a571* <i>key entry</i>, false otherwise.572*/573public boolean engineIsKeyEntry(String alias) {574permissionCheck();575Object entry = entries.get(alias.toLowerCase());576if ((entry != null) && (entry instanceof KeyEntry)) {577return true;578} else {579return false;580}581}582583/**584* Returns true if the entry identified by the given alias is a585* <i>trusted certificate entry</i>, and false otherwise.586*587* @return true if the entry identified by the given alias is a588* <i>trusted certificate entry</i>, false otherwise.589*/590public boolean engineIsCertificateEntry(String alias) {591permissionCheck();592Object entry = entries.get(alias.toLowerCase());593if ((entry != null) && (entry instanceof TrustedCertEntry)) {594return true;595} else {596return false;597}598}599600/**601* Returns the (alias) name of the first keystore entry whose certificate602* matches the given certificate.603*604* <p>This method attempts to match the given certificate with each605* keystore entry. If the entry being considered606* is a <i>trusted certificate entry</i>, the given certificate is607* compared to that entry's certificate. If the entry being considered is608* a <i>key entry</i>, the given certificate is compared to the first609* element of that entry's certificate chain (if a chain exists).610*611* @param cert the certificate to match with.612*613* @return the (alias) name of the first entry with matching certificate,614* or null if no such entry exists in this keystore.615*/616public String engineGetCertificateAlias(Certificate cert) {617permissionCheck();618Certificate certElem;619620for (Enumeration e = entries.keys(); e.hasMoreElements(); ) {621String alias = (String)e.nextElement();622Object entry = entries.get(alias);623if (entry instanceof TrustedCertEntry) {624certElem = ((TrustedCertEntry)entry).cert;625} else if (((KeyEntry)entry).chain != null) {626certElem = ((KeyEntry)entry).chain[0];627} else {628continue;629}630if (certElem.equals(cert)) {631return alias;632}633}634return null;635}636637/**638* Stores this keystore to the given output stream, and protects its639* integrity with the given password.640*641* @param stream Ignored. the output stream to which this keystore is written.642* @param password the password to generate the keystore integrity check643*644* @exception IOException if there was an I/O problem with data645* @exception NoSuchAlgorithmException if the appropriate data integrity646* algorithm could not be found647* @exception CertificateException if any of the certificates included in648* the keystore data could not be stored649*/650public void engineStore(OutputStream stream, char[] password)651throws IOException, NoSuchAlgorithmException, CertificateException652{653permissionCheck();654655// Delete items that do have a keychain item ref.656for (Enumeration e = deletedEntries.keys(); e.hasMoreElements(); ) {657String alias = (String)e.nextElement();658Object entry = deletedEntries.get(alias);659if (entry instanceof TrustedCertEntry) {660if (((TrustedCertEntry)entry).certRef != 0) {661_removeItemFromKeychain(((TrustedCertEntry)entry).certRef);662_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);663}664} else {665Certificate certElem;666KeyEntry keyEntry = (KeyEntry)entry;667668if (keyEntry.chain != null) {669for (int i = 0; i < keyEntry.chain.length; i++) {670if (keyEntry.chainRefs[i] != 0) {671_removeItemFromKeychain(keyEntry.chainRefs[i]);672_releaseKeychainItemRef(keyEntry.chainRefs[i]);673}674}675676if (keyEntry.keyRef != 0) {677_removeItemFromKeychain(keyEntry.keyRef);678_releaseKeychainItemRef(keyEntry.keyRef);679}680}681}682}683684// Add all of the certs or keys in the added entries.685// No need to check for 0 refs, as they are in the added list.686for (Enumeration e = addedEntries.keys(); e.hasMoreElements(); ) {687String alias = (String)e.nextElement();688Object entry = addedEntries.get(alias);689if (entry instanceof TrustedCertEntry) {690TrustedCertEntry tce = (TrustedCertEntry)entry;691Certificate certElem;692certElem = tce.cert;693tce.certRef = addCertificateToKeychain(alias, certElem);694} else {695KeyEntry keyEntry = (KeyEntry)entry;696697if (keyEntry.chain != null) {698for (int i = 0; i < keyEntry.chain.length; i++) {699keyEntry.chainRefs[i] = addCertificateToKeychain(alias, keyEntry.chain[i]);700}701702keyEntry.keyRef = _addItemToKeychain(alias, false, keyEntry.protectedPrivKey, keyEntry.password);703}704}705}706707// Clear the added and deletedEntries hashtables here, now that we're done with the updates.708// For the deleted entries, we freed up the native references above.709deletedEntries.clear();710addedEntries.clear();711}712713private long addCertificateToKeychain(String alias, Certificate cert) {714byte[] certblob = null;715long returnValue = 0;716717try {718certblob = cert.getEncoded();719returnValue = _addItemToKeychain(alias, true, certblob, null);720} catch (Exception e) {721e.printStackTrace();722}723724return returnValue;725}726727private native long _addItemToKeychain(String alias, boolean isCertificate, byte[] datablob, char[] password);728private native int _removeItemFromKeychain(long certRef);729private native void _releaseKeychainItemRef(long keychainItemRef);730731/**732* Loads the keystore from the Keychain.733*734* @param stream Ignored - here for API compatibility.735* @param password Ignored - if user needs to unlock keychain Security736* framework will post any dialogs.737*738* @exception IOException if there is an I/O or format problem with the739* keystore data740* @exception NoSuchAlgorithmException if the algorithm used to check741* the integrity of the keystore cannot be found742* @exception CertificateException if any of the certificates in the743* keystore could not be loaded744*/745public void engineLoad(InputStream stream, char[] password)746throws IOException, NoSuchAlgorithmException, CertificateException747{748permissionCheck();749750// Release any stray keychain references before clearing out the entries.751synchronized(entries) {752for (Enumeration e = entries.keys(); e.hasMoreElements(); ) {753String alias = (String)e.nextElement();754Object entry = entries.get(alias);755if (entry instanceof TrustedCertEntry) {756if (((TrustedCertEntry)entry).certRef != 0) {757_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);758}759} else {760KeyEntry keyEntry = (KeyEntry)entry;761762if (keyEntry.chain != null) {763for (int i = 0; i < keyEntry.chain.length; i++) {764if (keyEntry.chainRefs[i] != 0) {765_releaseKeychainItemRef(keyEntry.chainRefs[i]);766}767}768769if (keyEntry.keyRef != 0) {770_releaseKeychainItemRef(keyEntry.keyRef);771}772}773}774}775776entries.clear();777_scanKeychain();778if (debug != null) {779debug.println("KeychainStore load entry count: " +780entries.size());781}782}783}784785private native void _scanKeychain();786787/**788* Callback method from _scanKeychain. If a trusted certificate is found, this method will be called.789*/790private void createTrustedCertEntry(String alias, long keychainItemRef, long creationDate, byte[] derStream) {791TrustedCertEntry tce = new TrustedCertEntry();792793try {794CertificateFactory cf = CertificateFactory.getInstance("X.509");795InputStream input = new ByteArrayInputStream(derStream);796X509Certificate cert = (X509Certificate) cf.generateCertificate(input);797input.close();798tce.cert = cert;799tce.certRef = keychainItemRef;800801// Make a creation date.802if (creationDate != 0)803tce.date = new Date(creationDate);804else805tce.date = new Date();806807int uniqueVal = 1;808String originalAlias = alias;809810while (entries.containsKey(alias.toLowerCase())) {811alias = originalAlias + " " + uniqueVal;812uniqueVal++;813}814815entries.put(alias.toLowerCase(), tce);816} catch (Exception e) {817// The certificate will be skipped.818System.err.println("KeychainStore Ignored Exception: " + e);819}820}821822/**823* Callback method from _scanKeychain. If an identity is found, this method will be called to create Java certificate824* and private key objects from the keychain data.825*/826private void createKeyEntry(String alias, long creationDate, long secKeyRef, long[] secCertificateRefs, byte[][] rawCertData)827throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {828KeyEntry ke = new KeyEntry();829830// First, store off the private key information. This is the easy part.831ke.protectedPrivKey = null;832ke.keyRef = secKeyRef;833834// Make a creation date.835if (creationDate != 0)836ke.date = new Date(creationDate);837else838ke.date = new Date();839840// Next, create X.509 Certificate objects from the raw data. This is complicated841// because a certificate's public key may be too long for Java's default encryption strength.842List createdCerts = new ArrayList();843844try {845CertificateFactory cf = CertificateFactory.getInstance("X.509");846847for (int i = 0; i < rawCertData.length; i++) {848try {849InputStream input = new ByteArrayInputStream(rawCertData[i]);850X509Certificate cert = (X509Certificate) cf.generateCertificate(input);851input.close();852853// We successfully created the certificate, so track it and its corresponding SecCertificateRef.854createdCerts.add(new CertKeychainItemPair(secCertificateRefs[i], cert));855} catch (CertificateException e) {856// The certificate will be skipped.857System.err.println("KeychainStore Ignored Exception: " + e);858}859}860} catch (CertificateException e) {861e.printStackTrace();862} catch (IOException ioe) {863ioe.printStackTrace(); // How would this happen?864}865866// We have our certificates in the List, so now extract them into an array of867// Certificates and SecCertificateRefs.868Object[] objArray = createdCerts.toArray();869Certificate[] certArray = new Certificate[objArray.length];870long[] certRefArray = new long[objArray.length];871872for (int i = 0; i < objArray.length; i++) {873CertKeychainItemPair addedItem = (CertKeychainItemPair)objArray[i];874certArray[i] = addedItem.mCert;875certRefArray[i] = addedItem.mCertificateRef;876}877878ke.chain = certArray;879ke.chainRefs = certRefArray;880881// If we don't have already have an item with this item's alias882// create a new one for it.883int uniqueVal = 1;884String originalAlias = alias;885886while (entries.containsKey(alias.toLowerCase())) {887alias = originalAlias + " " + uniqueVal;888uniqueVal++;889}890891entries.put(alias.toLowerCase(), ke);892}893894private class CertKeychainItemPair {895long mCertificateRef;896Certificate mCert;897898CertKeychainItemPair(long inCertRef, Certificate cert) {899mCertificateRef = inCertRef;900mCert = cert;901}902}903904/*905* Validate Certificate Chain906*/907private boolean validateChain(Certificate[] certChain)908{909for (int i = 0; i < certChain.length-1; i++) {910X500Principal issuerDN =911((X509Certificate)certChain[i]).getIssuerX500Principal();912X500Principal subjectDN =913((X509Certificate)certChain[i+1]).getSubjectX500Principal();914if (!(issuerDN.equals(subjectDN)))915return false;916}917return true;918}919920private byte[] fetchPrivateKeyFromBag(byte[] privateKeyInfo) throws IOException, NoSuchAlgorithmException, CertificateException921{922byte[] returnValue = null;923DerValue val = new DerValue(new ByteArrayInputStream(privateKeyInfo));924DerInputStream s = val.toDerInputStream();925int version = s.getInteger();926927if (version != 3) {928throw new IOException("PKCS12 keystore not in version 3 format");929}930931/*932* Read the authSafe.933*/934byte[] authSafeData;935ContentInfo authSafe = new ContentInfo(s);936ObjectIdentifier contentType = authSafe.getContentType();937938if (contentType.equals(ContentInfo.DATA_OID)) {939authSafeData = authSafe.getData();940} else /* signed data */ {941throw new IOException("public key protected PKCS12 not supported");942}943944DerInputStream as = new DerInputStream(authSafeData);945DerValue[] safeContentsArray = as.getSequence(2);946int count = safeContentsArray.length;947948/*949* Spin over the ContentInfos.950*/951for (int i = 0; i < count; i++) {952byte[] safeContentsData;953ContentInfo safeContents;954DerInputStream sci;955byte[] eAlgId = null;956957sci = new DerInputStream(safeContentsArray[i].toByteArray());958safeContents = new ContentInfo(sci);959contentType = safeContents.getContentType();960safeContentsData = null;961962if (contentType.equals(ContentInfo.DATA_OID)) {963safeContentsData = safeContents.getData();964} else if (contentType.equals(ContentInfo.ENCRYPTED_DATA_OID)) {965// The password was used to export the private key from the keychain.966// The Keychain won't export the key with encrypted data, so we don't need967// to worry about it.968continue;969} else {970throw new IOException("public key protected PKCS12" +971" not supported");972}973DerInputStream sc = new DerInputStream(safeContentsData);974returnValue = extractKeyData(sc);975}976977return returnValue;978}979980private byte[] extractKeyData(DerInputStream stream)981throws IOException, NoSuchAlgorithmException, CertificateException982{983byte[] returnValue = null;984DerValue[] safeBags = stream.getSequence(2);985int count = safeBags.length;986987/*988* Spin over the SafeBags.989*/990for (int i = 0; i < count; i++) {991ObjectIdentifier bagId;992DerInputStream sbi;993DerValue bagValue;994Object bagItem = null;995996sbi = safeBags[i].toDerInputStream();997bagId = sbi.getOID();998bagValue = sbi.getDerValue();999if (!bagValue.isContextSpecific((byte)0)) {1000throw new IOException("unsupported PKCS12 bag value type "1001+ bagValue.tag);1002}1003bagValue = bagValue.data.getDerValue();1004if (bagId.equals(PKCS8ShroudedKeyBag_OID)) {1005// got what we were looking for. Return it.1006returnValue = bagValue.toByteArray();1007} else {1008// log error message for "unsupported PKCS12 bag type"1009System.out.println("Unsupported bag type '" + bagId + "'");1010}1011}10121013return returnValue;1014}10151016/*1017* Generate PBE Algorithm Parameters1018*/1019private AlgorithmParameters getAlgorithmParameters(String algorithm)1020throws IOException1021{1022AlgorithmParameters algParams = null;10231024// create PBE parameters from salt and iteration count1025PBEParameterSpec paramSpec =1026new PBEParameterSpec(getSalt(), iterationCount);1027try {1028algParams = AlgorithmParameters.getInstance(algorithm);1029algParams.init(paramSpec);1030} catch (Exception e) {1031IOException ioe =1032new IOException("getAlgorithmParameters failed: " +1033e.getMessage());1034ioe.initCause(e);1035throw ioe;1036}1037return algParams;1038}10391040// the source of randomness1041private SecureRandom random;10421043/*1044* Generate random salt1045*/1046private byte[] getSalt()1047{1048// Generate a random salt.1049byte[] salt = new byte[SALT_LEN];1050if (random == null) {1051random = new SecureRandom();1052}1053salt = random.generateSeed(SALT_LEN);1054return salt;1055}10561057/*1058* parse Algorithm Parameters1059*/1060private AlgorithmParameters parseAlgParameters(DerInputStream in)1061throws IOException1062{1063AlgorithmParameters algParams = null;1064try {1065DerValue params;1066if (in.available() == 0) {1067params = null;1068} else {1069params = in.getDerValue();1070if (params.tag == DerValue.tag_Null) {1071params = null;1072}1073}1074if (params != null) {1075algParams = AlgorithmParameters.getInstance("PBE");1076algParams.init(params.toByteArray());1077}1078} catch (Exception e) {1079IOException ioe =1080new IOException("parseAlgParameters failed: " +1081e.getMessage());1082ioe.initCause(e);1083throw ioe;1084}1085return algParams;1086}10871088/*1089* Generate PBE key1090*/1091private SecretKey getPBEKey(char[] password) throws IOException1092{1093SecretKey skey = null;10941095try {1096PBEKeySpec keySpec = new PBEKeySpec(password);1097SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");1098skey = skFac.generateSecret(keySpec);1099} catch (Exception e) {1100IOException ioe = new IOException("getSecretKey failed: " +1101e.getMessage());1102ioe.initCause(e);1103throw ioe;1104}1105return skey;1106}11071108/*1109* Encrypt private key using Password-based encryption (PBE)1110* as defined in PKCS#5.1111*1112* NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is1113* used to derive the key and IV.1114*1115* @return encrypted private key encoded as EncryptedPrivateKeyInfo1116*/1117private byte[] encryptPrivateKey(byte[] data, char[] password)1118throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException1119{1120byte[] key = null;11211122try {1123// create AlgorithmParameters1124AlgorithmParameters algParams =1125getAlgorithmParameters("PBEWithSHA1AndDESede");11261127// Use JCE1128SecretKey skey = getPBEKey(password);1129Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");1130cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);1131byte[] encryptedKey = cipher.doFinal(data);11321133// wrap encrypted private key in EncryptedPrivateKeyInfo1134// as defined in PKCS#81135AlgorithmId algid =1136new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams);1137EncryptedPrivateKeyInfo encrInfo =1138new EncryptedPrivateKeyInfo(algid, encryptedKey);1139key = encrInfo.getEncoded();1140} catch (Exception e) {1141UnrecoverableKeyException uke =1142new UnrecoverableKeyException("Encrypt Private Key failed: "1143+ e.getMessage());1144uke.initCause(e);1145throw uke;1146}11471148return ((byte[])key);1149}115011511152}1153115411551156