Path: blob/master/src/java.base/macosx/classes/apple/security/KeychainStore.java
41133 views
/*1* Copyright (c) 2011, 2021, 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.55static class 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 certificates65static class 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<String, Object> deletedEntries = new Hashtable<>();7778/**79* Entries that have been added. When something calls engineStore we'll80* add them to the keychain.81*/82private Hashtable<String, Object> 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<String, Object> entries = new Hashtable<>();8990/**91* Algorithm identifiers and corresponding OIDs for the contents of the92* PKCS12 bag we get from the Keychain.93*/94private static ObjectIdentifier PKCS8ShroudedKeyBag_OID =95ObjectIdentifier.of(KnownOIDs.PKCS8ShroudedKeyBag);96private static ObjectIdentifier pbeWithSHAAnd3KeyTripleDESCBC_OID =97ObjectIdentifier.of(KnownOIDs.PBEWithSHA1AndDESede);9899/**100* Constnats used in PBE decryption.101*/102private static final int iterationCount = 1024;103private static final int SALT_LEN = 20;104105private static final Debug debug = Debug.getInstance("keystore");106107static {108jdk.internal.loader.BootLoader.loadLibrary("osxsecurity");109}110111private static void permissionCheck() {112@SuppressWarnings("removal")113SecurityManager sec = System.getSecurityManager();114115if (sec != null) {116sec.checkPermission(new RuntimePermission("useKeychainStore"));117}118}119120121/**122* Verify the Apple provider in the constructor.123*124* @exception SecurityException if fails to verify125* its own integrity126*/127public KeychainStore() { }128129/**130* Returns the key associated with the given alias, using the given131* password to recover it.132*133* @param alias the alias name134* @param password the password for recovering the key. This password is135* used internally as the key is exported in a PKCS12 format.136*137* @return the requested key, or null if the given alias does not exist138* or does not identify a <i>key entry</i>.139*140* @exception NoSuchAlgorithmException if the algorithm for recovering the141* key cannot be found142* @exception UnrecoverableKeyException if the key cannot be recovered143* (e.g., the given password is wrong).144*/145public Key engineGetKey(String alias, char[] password)146throws NoSuchAlgorithmException, UnrecoverableKeyException147{148permissionCheck();149150// An empty password is rejected by MacOS API, no private key data151// is exported. If no password is passed (as is the case when152// this implementation is used as browser keystore in various153// deployment scenarios like Webstart, JFX and applets), create154// a dummy password so MacOS API is happy.155if (password == null || password.length == 0) {156// Must not be a char array with only a 0, as this is an empty157// string.158if (random == null) {159random = new SecureRandom();160}161password = Long.toString(random.nextLong()).toCharArray();162}163164Object entry = entries.get(alias.toLowerCase());165166if (entry == null || !(entry instanceof KeyEntry)) {167return null;168}169170// This call gives us a PKCS12 bag, with the key inside it.171byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry)entry).keyRef, password);172if (exportedKeyInfo == null) {173return null;174}175176PrivateKey returnValue = null;177178try {179byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);180byte[] encryptedKey;181AlgorithmParameters algParams;182ObjectIdentifier algOid;183try {184// get the encrypted private key185EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);186encryptedKey = encrInfo.getEncryptedData();187188// parse Algorithm parameters189DerValue val = new DerValue(encrInfo.getAlgorithm().encode());190DerInputStream in = val.toDerInputStream();191algOid = in.getOID();192algParams = parseAlgParameters(in);193194} catch (IOException ioe) {195UnrecoverableKeyException uke =196new UnrecoverableKeyException("Private key not stored as "197+ "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);198uke.initCause(ioe);199throw uke;200}201202// Use JCE to decrypt the data using the supplied password.203SecretKey skey = getPBEKey(password);204Cipher cipher = Cipher.getInstance(algOid.toString());205cipher.init(Cipher.DECRYPT_MODE, skey, algParams);206byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);207PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);208209// Parse the key algorithm and then use a JCA key factory to create the private key.210DerValue val = new DerValue(decryptedPrivateKey);211DerInputStream in = val.toDerInputStream();212213// Ignore this -- version should be 0.214int i = in.getInteger();215216// Get the Algorithm ID next217DerValue[] value = in.getSequence(2);218if (value.length < 1 || value.length > 2) {219throw new IOException("Invalid length for AlgorithmIdentifier");220}221AlgorithmId algId = new AlgorithmId(value[0].getOID());222String algName = algId.getName();223224// Get a key factory for this algorithm. It's likely to be 'RSA'.225KeyFactory kfac = KeyFactory.getInstance(algName);226returnValue = kfac.generatePrivate(kspec);227} catch (Exception e) {228UnrecoverableKeyException uke =229new UnrecoverableKeyException("Get Key failed: " +230e.getMessage());231uke.initCause(e);232throw uke;233}234235return returnValue;236}237238private native byte[] _getEncodedKeyData(long secKeyRef, char[] password);239240/**241* Returns the certificate chain associated with the given alias.242*243* @param alias the alias name244*245* @return the certificate chain (ordered with the user's certificate first246* and the root certificate authority last), or null if the given alias247* does not exist or does not contain a certificate chain (i.e., the given248* alias identifies either a <i>trusted certificate entry</i> or a249* <i>key entry</i> without a certificate chain).250*/251public Certificate[] engineGetCertificateChain(String alias) {252permissionCheck();253254Object entry = entries.get(alias.toLowerCase());255256if (entry != null && entry instanceof KeyEntry) {257if (((KeyEntry)entry).chain == null) {258return null;259} else {260return ((KeyEntry)entry).chain.clone();261}262} else {263return null;264}265}266267/**268* Returns the certificate associated with the given alias.269*270* <p>If the given alias name identifies a271* <i>trusted certificate entry</i>, the certificate associated with that272* entry is returned. If the given alias name identifies a273* <i>key entry</i>, the first element of the certificate chain of that274* entry is returned, or null if that entry does not have a certificate275* chain.276*277* @param alias the alias name278*279* @return the certificate, or null if the given alias does not exist or280* does not contain a certificate.281*/282public Certificate engineGetCertificate(String alias) {283permissionCheck();284285Object entry = entries.get(alias.toLowerCase());286287if (entry != null) {288if (entry instanceof TrustedCertEntry) {289return ((TrustedCertEntry)entry).cert;290} else {291KeyEntry ke = (KeyEntry)entry;292if (ke.chain == null || ke.chain.length == 0) {293return null;294}295return ke.chain[0];296}297} else {298return null;299}300}301302/**303* Returns the creation date of the entry identified by the given alias.304*305* @param alias the alias name306*307* @return the creation date of this entry, or null if the given alias does308* not exist309*/310public Date engineGetCreationDate(String alias) {311permissionCheck();312313Object entry = entries.get(alias.toLowerCase());314315if (entry != null) {316if (entry instanceof TrustedCertEntry) {317return new Date(((TrustedCertEntry)entry).date.getTime());318} else {319return new Date(((KeyEntry)entry).date.getTime());320}321} else {322return null;323}324}325326/**327* Assigns the given key to the given alias, protecting it with the given328* password.329*330* <p>If the given key is of type <code>java.security.PrivateKey</code>,331* it must be accompanied by a certificate chain certifying the332* corresponding public key.333*334* <p>If the given alias already exists, the keystore information335* associated with it is overridden by the given key (and possibly336* certificate chain).337*338* @param alias the alias name339* @param key the key to be associated with the alias340* @param password the password to protect the key341* @param chain the certificate chain for the corresponding public342* key (only required if the given key is of type343* <code>java.security.PrivateKey</code>).344*345* @exception KeyStoreException if the given key cannot be protected, or346* this operation fails for some other reason347*/348public void engineSetKeyEntry(String alias, Key key, char[] password,349Certificate[] chain)350throws KeyStoreException351{352permissionCheck();353354synchronized(entries) {355try {356KeyEntry entry = new KeyEntry();357entry.date = new Date();358359if (key instanceof PrivateKey) {360if ((key.getFormat().equals("PKCS#8")) ||361(key.getFormat().equals("PKCS8"))) {362entry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), password);363entry.password = password.clone();364} else {365throw new KeyStoreException("Private key is not encoded as PKCS#8");366}367} else {368throw new KeyStoreException("Key is not a PrivateKey");369}370371// clone the chain372if (chain != null) {373if ((chain.length > 1) && !validateChain(chain)) {374throw new KeyStoreException("Certificate chain does not validate");375}376377entry.chain = chain.clone();378entry.chainRefs = new long[entry.chain.length];379}380381String lowerAlias = alias.toLowerCase();382if (entries.get(lowerAlias) != null) {383deletedEntries.put(lowerAlias, entries.get(lowerAlias));384}385386entries.put(lowerAlias, entry);387addedEntries.put(lowerAlias, entry);388} catch (Exception nsae) {389KeyStoreException ke = new KeyStoreException("Key protection algorithm not found: " + nsae);390ke.initCause(nsae);391throw ke;392}393}394}395396/**397* Assigns the given key (that has already been protected) to the given398* alias.399*400* <p>If the protected key is of type401* <code>java.security.PrivateKey</code>, it must be accompanied by a402* certificate chain certifying the corresponding public key. If the403* underlying keystore implementation is of type <code>jks</code>,404* <code>key</code> must be encoded as an405* <code>EncryptedPrivateKeyInfo</code> as defined in the PKCS #8 standard.406*407* <p>If the given alias already exists, the keystore information408* associated with it is overridden by the given key (and possibly409* certificate chain).410*411* @param alias the alias name412* @param key the key (in protected format) to be associated with the alias413* @param chain the certificate chain for the corresponding public414* key (only useful if the protected key is of type415* <code>java.security.PrivateKey</code>).416*417* @exception KeyStoreException if this operation fails.418*/419public void engineSetKeyEntry(String alias, byte[] key,420Certificate[] chain)421throws KeyStoreException422{423permissionCheck();424425synchronized(entries) {426// key must be encoded as EncryptedPrivateKeyInfo as defined in427// PKCS#8428KeyEntry entry = new KeyEntry();429try {430EncryptedPrivateKeyInfo privateKey = new EncryptedPrivateKeyInfo(key);431entry.protectedPrivKey = privateKey.getEncoded();432} catch (IOException ioe) {433throw new KeyStoreException("key is not encoded as "434+ "EncryptedPrivateKeyInfo");435}436437entry.date = new Date();438439if ((chain != null) &&440(chain.length != 0)) {441entry.chain = chain.clone();442entry.chainRefs = new long[entry.chain.length];443}444445String lowerAlias = alias.toLowerCase();446if (entries.get(lowerAlias) != null) {447deletedEntries.put(lowerAlias, entries.get(alias));448}449entries.put(lowerAlias, entry);450addedEntries.put(lowerAlias, entry);451}452}453454/**455* Assigns the given certificate to the given alias.456*457* <p>If the given alias already exists in this keystore and identifies a458* <i>trusted certificate entry</i>, the certificate associated with it is459* overridden by the given certificate.460*461* @param alias the alias name462* @param cert the certificate463*464* @exception KeyStoreException if the given alias already exists and does465* not identify a <i>trusted certificate entry</i>, or this operation466* fails for some other reason.467*/468public void engineSetCertificateEntry(String alias, Certificate cert)469throws KeyStoreException470{471permissionCheck();472473synchronized(entries) {474475Object entry = entries.get(alias.toLowerCase());476if ((entry != null) && (entry instanceof KeyEntry)) {477throw new KeyStoreException478("Cannot overwrite key entry with certificate");479}480481// This will be slow, but necessary. Enumerate the values and then see if the cert matches the one in the trusted cert entry.482// Security framework doesn't support the same certificate twice in a keychain.483Collection<Object> allValues = entries.values();484485for (Object value : allValues) {486if (value instanceof TrustedCertEntry) {487TrustedCertEntry tce = (TrustedCertEntry)value;488if (tce.cert.equals(cert)) {489throw new KeyStoreException("Keychain does not support mulitple copies of same certificate.");490}491}492}493494TrustedCertEntry trustedCertEntry = new TrustedCertEntry();495trustedCertEntry.cert = cert;496trustedCertEntry.date = new Date();497String lowerAlias = alias.toLowerCase();498if (entries.get(lowerAlias) != null) {499deletedEntries.put(lowerAlias, entries.get(lowerAlias));500}501entries.put(lowerAlias, trustedCertEntry);502addedEntries.put(lowerAlias, trustedCertEntry);503}504}505506/**507* Deletes the entry identified by the given alias from this keystore.508*509* @param alias the alias name510*511* @exception KeyStoreException if the entry cannot be removed.512*/513public void engineDeleteEntry(String alias)514throws KeyStoreException515{516permissionCheck();517518synchronized(entries) {519Object entry = entries.remove(alias.toLowerCase());520deletedEntries.put(alias.toLowerCase(), entry);521}522}523524/**525* Lists all the alias names of this keystore.526*527* @return enumeration of the alias names528*/529public Enumeration<String> engineAliases() {530permissionCheck();531return entries.keys();532}533534/**535* Checks if the given alias exists in this keystore.536*537* @param alias the alias name538*539* @return true if the alias exists, false otherwise540*/541public boolean engineContainsAlias(String alias) {542permissionCheck();543return entries.containsKey(alias.toLowerCase());544}545546/**547* Retrieves the number of entries in this keystore.548*549* @return the number of entries in this keystore550*/551public int engineSize() {552permissionCheck();553return entries.size();554}555556/**557* Returns true if the entry identified by the given alias is a558* <i>key entry</i>, and false otherwise.559*560* @return true if the entry identified by the given alias is a561* <i>key entry</i>, false otherwise.562*/563public boolean engineIsKeyEntry(String alias) {564permissionCheck();565Object entry = entries.get(alias.toLowerCase());566if ((entry != null) && (entry instanceof KeyEntry)) {567return true;568} else {569return false;570}571}572573/**574* Returns true if the entry identified by the given alias is a575* <i>trusted certificate entry</i>, and false otherwise.576*577* @return true if the entry identified by the given alias is a578* <i>trusted certificate entry</i>, false otherwise.579*/580public boolean engineIsCertificateEntry(String alias) {581permissionCheck();582Object entry = entries.get(alias.toLowerCase());583if ((entry != null) && (entry instanceof TrustedCertEntry)) {584return true;585} else {586return false;587}588}589590/**591* Returns the (alias) name of the first keystore entry whose certificate592* matches the given certificate.593*594* <p>This method attempts to match the given certificate with each595* keystore entry. If the entry being considered596* is a <i>trusted certificate entry</i>, the given certificate is597* compared to that entry's certificate. If the entry being considered is598* a <i>key entry</i>, the given certificate is compared to the first599* element of that entry's certificate chain (if a chain exists).600*601* @param cert the certificate to match with.602*603* @return the (alias) name of the first entry with matching certificate,604* or null if no such entry exists in this keystore.605*/606public String engineGetCertificateAlias(Certificate cert) {607permissionCheck();608Certificate certElem;609610for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {611String alias = e.nextElement();612Object entry = entries.get(alias);613if (entry instanceof TrustedCertEntry) {614certElem = ((TrustedCertEntry)entry).cert;615} else {616KeyEntry ke = (KeyEntry)entry;617if (ke.chain == null || ke.chain.length == 0) {618continue;619}620certElem = ke.chain[0];621}622if (certElem.equals(cert)) {623return alias;624}625}626return null;627}628629/**630* Stores this keystore to the given output stream, and protects its631* integrity with the given password.632*633* @param stream Ignored. the output stream to which this keystore is written.634* @param password the password to generate the keystore integrity check635*636* @exception IOException if there was an I/O problem with data637* @exception NoSuchAlgorithmException if the appropriate data integrity638* algorithm could not be found639* @exception CertificateException if any of the certificates included in640* the keystore data could not be stored641*/642public void engineStore(OutputStream stream, char[] password)643throws IOException, NoSuchAlgorithmException, CertificateException644{645permissionCheck();646647// Delete items that do have a keychain item ref.648for (Enumeration<String> e = deletedEntries.keys(); e.hasMoreElements(); ) {649String alias = e.nextElement();650Object entry = deletedEntries.get(alias);651if (entry instanceof TrustedCertEntry) {652if (((TrustedCertEntry)entry).certRef != 0) {653_removeItemFromKeychain(((TrustedCertEntry)entry).certRef);654_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);655}656} else {657Certificate certElem;658KeyEntry keyEntry = (KeyEntry)entry;659660if (keyEntry.chain != null) {661for (int i = 0; i < keyEntry.chain.length; i++) {662if (keyEntry.chainRefs[i] != 0) {663_removeItemFromKeychain(keyEntry.chainRefs[i]);664_releaseKeychainItemRef(keyEntry.chainRefs[i]);665}666}667668if (keyEntry.keyRef != 0) {669_removeItemFromKeychain(keyEntry.keyRef);670_releaseKeychainItemRef(keyEntry.keyRef);671}672}673}674}675676// Add all of the certs or keys in the added entries.677// No need to check for 0 refs, as they are in the added list.678for (Enumeration<String> e = addedEntries.keys(); e.hasMoreElements(); ) {679String alias = e.nextElement();680Object entry = addedEntries.get(alias);681if (entry instanceof TrustedCertEntry) {682TrustedCertEntry tce = (TrustedCertEntry)entry;683Certificate certElem;684certElem = tce.cert;685tce.certRef = addCertificateToKeychain(alias, certElem);686} else {687KeyEntry keyEntry = (KeyEntry)entry;688689if (keyEntry.chain != null) {690for (int i = 0; i < keyEntry.chain.length; i++) {691keyEntry.chainRefs[i] = addCertificateToKeychain(alias, keyEntry.chain[i]);692}693694keyEntry.keyRef = _addItemToKeychain(alias, false, keyEntry.protectedPrivKey, keyEntry.password);695}696}697}698699// Clear the added and deletedEntries hashtables here, now that we're done with the updates.700// For the deleted entries, we freed up the native references above.701deletedEntries.clear();702addedEntries.clear();703}704705private long addCertificateToKeychain(String alias, Certificate cert) {706byte[] certblob = null;707long returnValue = 0;708709try {710certblob = cert.getEncoded();711returnValue = _addItemToKeychain(alias, true, certblob, null);712} catch (Exception e) {713e.printStackTrace();714}715716return returnValue;717}718719private native long _addItemToKeychain(String alias, boolean isCertificate, byte[] datablob, char[] password);720private native int _removeItemFromKeychain(long certRef);721private native void _releaseKeychainItemRef(long keychainItemRef);722723/**724* Loads the keystore from the Keychain.725*726* @param stream Ignored - here for API compatibility.727* @param password Ignored - if user needs to unlock keychain Security728* framework will post any dialogs.729*730* @exception IOException if there is an I/O or format problem with the731* keystore data732* @exception NoSuchAlgorithmException if the algorithm used to check733* the integrity of the keystore cannot be found734* @exception CertificateException if any of the certificates in the735* keystore could not be loaded736*/737public void engineLoad(InputStream stream, char[] password)738throws IOException, NoSuchAlgorithmException, CertificateException739{740permissionCheck();741742// Release any stray keychain references before clearing out the entries.743synchronized(entries) {744for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {745String alias = e.nextElement();746Object entry = entries.get(alias);747if (entry instanceof TrustedCertEntry) {748if (((TrustedCertEntry)entry).certRef != 0) {749_releaseKeychainItemRef(((TrustedCertEntry)entry).certRef);750}751} else {752KeyEntry keyEntry = (KeyEntry)entry;753754if (keyEntry.chain != null) {755for (int i = 0; i < keyEntry.chain.length; i++) {756if (keyEntry.chainRefs[i] != 0) {757_releaseKeychainItemRef(keyEntry.chainRefs[i]);758}759}760761if (keyEntry.keyRef != 0) {762_releaseKeychainItemRef(keyEntry.keyRef);763}764}765}766}767768entries.clear();769_scanKeychain();770if (debug != null) {771debug.println("KeychainStore load entry count: " +772entries.size());773}774}775}776777private native void _scanKeychain();778779/**780* Callback method from _scanKeychain. If a trusted certificate is found, this method will be called.781*/782private void createTrustedCertEntry(String alias, long keychainItemRef, long creationDate, byte[] derStream) {783TrustedCertEntry tce = new TrustedCertEntry();784785try {786CertificateFactory cf = CertificateFactory.getInstance("X.509");787InputStream input = new ByteArrayInputStream(derStream);788X509Certificate cert = (X509Certificate) cf.generateCertificate(input);789input.close();790tce.cert = cert;791tce.certRef = keychainItemRef;792793// Make a creation date.794if (creationDate != 0)795tce.date = new Date(creationDate);796else797tce.date = new Date();798799int uniqueVal = 1;800String originalAlias = alias;801802while (entries.containsKey(alias.toLowerCase())) {803alias = originalAlias + " " + uniqueVal;804uniqueVal++;805}806807entries.put(alias.toLowerCase(), tce);808} catch (Exception e) {809// The certificate will be skipped.810System.err.println("KeychainStore Ignored Exception: " + e);811}812}813814/**815* Callback method from _scanKeychain. If an identity is found, this method will be called to create Java certificate816* and private key objects from the keychain data.817*/818private void createKeyEntry(String alias, long creationDate, long secKeyRef,819long[] secCertificateRefs, byte[][] rawCertData) {820KeyEntry ke = new KeyEntry();821822// First, store off the private key information. This is the easy part.823ke.protectedPrivKey = null;824ke.keyRef = secKeyRef;825826// Make a creation date.827if (creationDate != 0)828ke.date = new Date(creationDate);829else830ke.date = new Date();831832// Next, create X.509 Certificate objects from the raw data. This is complicated833// because a certificate's public key may be too long for Java's default encryption strength.834List<CertKeychainItemPair> createdCerts = new ArrayList<>();835836try {837CertificateFactory cf = CertificateFactory.getInstance("X.509");838839for (int i = 0; i < rawCertData.length; i++) {840try {841InputStream input = new ByteArrayInputStream(rawCertData[i]);842X509Certificate cert = (X509Certificate) cf.generateCertificate(input);843input.close();844845// We successfully created the certificate, so track it and its corresponding SecCertificateRef.846createdCerts.add(new CertKeychainItemPair(secCertificateRefs[i], cert));847} catch (CertificateException e) {848// The certificate will be skipped.849System.err.println("KeychainStore Ignored Exception: " + e);850}851}852} catch (CertificateException e) {853e.printStackTrace();854} catch (IOException ioe) {855ioe.printStackTrace(); // How would this happen?856}857858// We have our certificates in the List, so now extract them into an array of859// Certificates and SecCertificateRefs.860CertKeychainItemPair[] objArray = createdCerts.toArray(new CertKeychainItemPair[0]);861Certificate[] certArray = new Certificate[objArray.length];862long[] certRefArray = new long[objArray.length];863864for (int i = 0; i < objArray.length; i++) {865CertKeychainItemPair addedItem = objArray[i];866certArray[i] = addedItem.mCert;867certRefArray[i] = addedItem.mCertificateRef;868}869870ke.chain = certArray;871ke.chainRefs = certRefArray;872873// If we don't have already have an item with this item's alias874// create a new one for it.875int uniqueVal = 1;876String originalAlias = alias;877878while (entries.containsKey(alias.toLowerCase())) {879alias = originalAlias + " " + uniqueVal;880uniqueVal++;881}882883entries.put(alias.toLowerCase(), ke);884}885886private static class CertKeychainItemPair {887long mCertificateRef;888Certificate mCert;889890CertKeychainItemPair(long inCertRef, Certificate cert) {891mCertificateRef = inCertRef;892mCert = cert;893}894}895896/*897* Validate Certificate Chain898*/899private boolean validateChain(Certificate[] certChain)900{901for (int i = 0; i < certChain.length-1; i++) {902X500Principal issuerDN =903((X509Certificate)certChain[i]).getIssuerX500Principal();904X500Principal subjectDN =905((X509Certificate)certChain[i+1]).getSubjectX500Principal();906if (!(issuerDN.equals(subjectDN)))907return false;908}909return true;910}911912private byte[] fetchPrivateKeyFromBag(byte[] privateKeyInfo) throws IOException, NoSuchAlgorithmException, CertificateException913{914byte[] returnValue = null;915DerValue val = new DerValue(new ByteArrayInputStream(privateKeyInfo));916DerInputStream s = val.toDerInputStream();917int version = s.getInteger();918919if (version != 3) {920throw new IOException("PKCS12 keystore not in version 3 format");921}922923/*924* Read the authSafe.925*/926byte[] authSafeData;927ContentInfo authSafe = new ContentInfo(s);928ObjectIdentifier contentType = authSafe.getContentType();929930if (contentType.equals(ContentInfo.DATA_OID)) {931authSafeData = authSafe.getData();932} else /* signed data */ {933throw new IOException("public key protected PKCS12 not supported");934}935936DerInputStream as = new DerInputStream(authSafeData);937DerValue[] safeContentsArray = as.getSequence(2);938int count = safeContentsArray.length;939940/*941* Spin over the ContentInfos.942*/943for (int i = 0; i < count; i++) {944byte[] safeContentsData;945ContentInfo safeContents;946DerInputStream sci;947byte[] eAlgId = null;948949sci = new DerInputStream(safeContentsArray[i].toByteArray());950safeContents = new ContentInfo(sci);951contentType = safeContents.getContentType();952safeContentsData = null;953954if (contentType.equals(ContentInfo.DATA_OID)) {955safeContentsData = safeContents.getData();956} else if (contentType.equals(ContentInfo.ENCRYPTED_DATA_OID)) {957// The password was used to export the private key from the keychain.958// The Keychain won't export the key with encrypted data, so we don't need959// to worry about it.960continue;961} else {962throw new IOException("public key protected PKCS12" +963" not supported");964}965DerInputStream sc = new DerInputStream(safeContentsData);966returnValue = extractKeyData(sc);967}968969return returnValue;970}971972private byte[] extractKeyData(DerInputStream stream)973throws IOException, NoSuchAlgorithmException, CertificateException974{975byte[] returnValue = null;976DerValue[] safeBags = stream.getSequence(2);977int count = safeBags.length;978979/*980* Spin over the SafeBags.981*/982for (int i = 0; i < count; i++) {983ObjectIdentifier bagId;984DerInputStream sbi;985DerValue bagValue;986Object bagItem = null;987988sbi = safeBags[i].toDerInputStream();989bagId = sbi.getOID();990bagValue = sbi.getDerValue();991if (!bagValue.isContextSpecific((byte)0)) {992throw new IOException("unsupported PKCS12 bag value type "993+ bagValue.tag);994}995bagValue = bagValue.data.getDerValue();996if (bagId.equals(PKCS8ShroudedKeyBag_OID)) {997// got what we were looking for. Return it.998returnValue = bagValue.toByteArray();999} else {1000// log error message for "unsupported PKCS12 bag type"1001System.out.println("Unsupported bag type '" + bagId + "'");1002}1003}10041005return returnValue;1006}10071008/*1009* Generate PBE Algorithm Parameters1010*/1011private AlgorithmParameters getAlgorithmParameters(String algorithm)1012throws IOException1013{1014AlgorithmParameters algParams = null;10151016// create PBE parameters from salt and iteration count1017PBEParameterSpec paramSpec =1018new PBEParameterSpec(getSalt(), iterationCount);1019try {1020algParams = AlgorithmParameters.getInstance(algorithm);1021algParams.init(paramSpec);1022} catch (Exception e) {1023IOException ioe =1024new IOException("getAlgorithmParameters failed: " +1025e.getMessage());1026ioe.initCause(e);1027throw ioe;1028}1029return algParams;1030}10311032// the source of randomness1033private SecureRandom random;10341035/*1036* Generate random salt1037*/1038private byte[] getSalt()1039{1040// Generate a random salt.1041byte[] salt = new byte[SALT_LEN];1042if (random == null) {1043random = new SecureRandom();1044}1045random.nextBytes(salt);1046return salt;1047}10481049/*1050* parse Algorithm Parameters1051*/1052private AlgorithmParameters parseAlgParameters(DerInputStream in)1053throws IOException1054{1055AlgorithmParameters algParams = null;1056try {1057DerValue params;1058if (in.available() == 0) {1059params = null;1060} else {1061params = in.getDerValue();1062if (params.tag == DerValue.tag_Null) {1063params = null;1064}1065}1066if (params != null) {1067algParams = AlgorithmParameters.getInstance("PBE");1068algParams.init(params.toByteArray());1069}1070} catch (Exception e) {1071IOException ioe =1072new IOException("parseAlgParameters failed: " +1073e.getMessage());1074ioe.initCause(e);1075throw ioe;1076}1077return algParams;1078}10791080/*1081* Generate PBE key1082*/1083private SecretKey getPBEKey(char[] password) throws IOException1084{1085SecretKey skey = null;10861087try {1088PBEKeySpec keySpec = new PBEKeySpec(password);1089SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");1090skey = skFac.generateSecret(keySpec);1091} catch (Exception e) {1092IOException ioe = new IOException("getSecretKey failed: " +1093e.getMessage());1094ioe.initCause(e);1095throw ioe;1096}1097return skey;1098}10991100/*1101* Encrypt private key using Password-based encryption (PBE)1102* as defined in PKCS#5.1103*1104* NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is1105* used to derive the key and IV.1106*1107* @return encrypted private key encoded as EncryptedPrivateKeyInfo1108*/1109private byte[] encryptPrivateKey(byte[] data, char[] password)1110throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException1111{1112byte[] key = null;11131114try {1115// create AlgorithmParameters1116AlgorithmParameters algParams =1117getAlgorithmParameters("PBEWithSHA1AndDESede");11181119// Use JCE1120SecretKey skey = getPBEKey(password);1121Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");1122cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);1123byte[] encryptedKey = cipher.doFinal(data);11241125// wrap encrypted private key in EncryptedPrivateKeyInfo1126// as defined in PKCS#81127AlgorithmId algid =1128new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams);1129EncryptedPrivateKeyInfo encrInfo =1130new EncryptedPrivateKeyInfo(algid, encryptedKey);1131key = encrInfo.getEncoded();1132} catch (Exception e) {1133UnrecoverableKeyException uke =1134new UnrecoverableKeyException("Encrypt Private Key failed: "1135+ e.getMessage());1136uke.initCause(e);1137throw uke;1138}11391140return key;1141}114211431144}1145114611471148