/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*
* 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.
*/
/**
* This class provides the keystore implementation referred to as "KeychainStore".
* It uses the current user's keychain as its backing storage, and does NOT support
* a file-based implementation.
*/
// Private keys and their supporting certificate chains
// If a key came from the keychain it has a SecKeyRef and one or more
// SecCertificateRef. When we delete the key we have to delete all of the corresponding
// native objects.
class KeyEntry {
byte[] protectedPrivKey;
char[] password;
};
// Trusted certificates
class TrustedCertEntry {
};
/**
* Entries that have been deleted. When something calls engineStore we'll
* remove them from the keychain.
*/
/**
* Entries that have been added. When something calls engineStore we'll
* add them to the keychain.
*/
/**
* Private keys and certificates are stored in a hashtable.
* Hash entries are keyed by alias names.
*/
/**
* Algorithm identifiers and corresponding OIDs for the contents of the PKCS12 bag we get from the Keychain.
*/
/**
* Constnats used in PBE decryption.
*/
static {
java.security.AccessController.doPrivileged((PrivilegedAction<?>)new sun.security.action.LoadLibraryAction("osx"));
try {
} catch (IOException ioe) {
// should not happen
}
}
private static void permissionCheck() {
}
}
/**
* Verify the Apple provider in the constructor.
*
* @exception SecurityException if fails to verify
* its own integrity
*/
public KeychainStore() { }
/**
* Returns the key associated with the given alias, using the given
* password to recover it.
*
* @param alias the alias name
* @param password the password for recovering the key
*
* @return the requested key, or null if the given alias does not exist
* or does not identify a <i>key entry</i>.
*
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* key cannot be found
* @exception UnrecoverableKeyException if the key cannot be recovered
* (e.g., the given password is wrong).
*/
{
return null;
}
// This call gives us a PKCS12 bag, with the key inside it.
if (exportedKeyInfo == null) {
return null;
}
try {
byte[] encryptedKey;
try {
// get the encrypted private key
// parse Algorithm parameters
} catch (IOException ioe) {
new UnrecoverableKeyException("Private key not stored as "
+ "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
throw uke;
}
// Use JCE to decrypt the data using the supplied password.
// Parse the key algorithm and then use a JCA key factory to create the private key.
// Ignore this -- version should be 0.
int i = in.getInteger();
// Get the Algorithm ID next
// Get a key factory for this algorithm. It's likely to be 'RSA'.
} catch (Exception e) {
new UnrecoverableKeyException("Get Key failed: " +
e.getMessage());
throw uke;
}
return returnValue;
}
/**
* 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).
*/
return null;
} else {
}
} else {
return null;
}
}
/**
* Returns the certificate associated with the given alias.
*
* <p>If the given alias name identifies a
* <i>trusted certificate entry</i>, the certificate associated with that
* entry is returned. If the given alias name identifies a
* <i>key entry</i>, the first element of the certificate chain of that
* entry is returned, or null if that entry does not have a certificate
* chain.
*
* @param alias the alias name
*
* @return the certificate, or null if the given alias does not exist or
* does not contain a certificate.
*/
if (entry instanceof TrustedCertEntry) {
} else {
return null;
} else {
}
}
} else {
return null;
}
}
/**
* Returns the creation date of the entry identified by the given alias.
*
* @param alias the alias name
*
* @return the creation date of this entry, or null if the given alias does
* not exist
*/
if (entry instanceof TrustedCertEntry) {
} else {
}
} else {
return null;
}
}
/**
* Assigns the given key to the given alias, protecting it with the given
* password.
*
* <p>If the given key is of type <code>java.security.PrivateKey</code>,
* it must be accompanied by a certificate chain certifying the
* corresponding public key.
*
* <p>If the given alias already exists, the keystore information
* associated with it is overridden by the given key (and possibly
* certificate chain).
*
* @param alias the alias name
* @param key the key to be associated with the alias
* @param password the password to protect the key
* @param chain the certificate chain for the corresponding public
* key (only required if the given key is of type
* <code>java.security.PrivateKey</code>).
*
* @exception KeyStoreException if the given key cannot be protected, or
* this operation fails for some other reason
*/
Certificate[] chain)
throws KeyStoreException
{
synchronized(entries) {
try {
if (key instanceof PrivateKey) {
} else {
throw new KeyStoreException("Private key is not encoded as PKCS#8");
}
} else {
throw new KeyStoreException("Key is not a PrivateKey");
}
// clone the chain
throw new KeyStoreException("Certificate chain does not validate");
}
}
}
throw ke;
}
}
}
/**
* 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.
*/
Certificate[] chain)
throws KeyStoreException
{
synchronized(entries) {
// key must be encoded as EncryptedPrivateKeyInfo as defined in
// PKCS#8
try {
} catch (IOException ioe) {
throw new KeyStoreException("key is not encoded as "
+ "EncryptedPrivateKeyInfo");
}
}
}
}
}
/**
* 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.
*/
throws KeyStoreException
{
synchronized(entries) {
throw new KeyStoreException
("Cannot overwrite key entry with certificate");
}
// This will be slow, but necessary. Enumerate the values and then see if the cert matches the one in the trusted cert entry.
// Security framework doesn't support the same certificate twice in a keychain.
if (value instanceof TrustedCertEntry) {
throw new KeyStoreException("Keychain does not support mulitple copies of same certificate.");
}
}
}
}
}
}
/**
* Deletes the entry identified by the given alias from this keystore.
*
* @param alias the alias name
*
* @exception KeyStoreException if the entry cannot be removed.
*/
throws KeyStoreException
{
synchronized(entries) {
}
}
/**
* Lists all the alias names of this keystore.
*
* @return enumeration of the alias names
*/
}
/**
* Checks if the given alias exists in this keystore.
*
* @param alias the alias name
*
* @return true if the alias exists, false otherwise
*/
}
/**
* Retrieves the number of entries in this keystore.
*
* @return the number of entries in this keystore
*/
public int engineSize() {
}
/**
* 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.
*/
return true;
} else {
return false;
}
}
/**
* Returns true if the entry identified by the given alias is a
* <i>trusted certificate entry</i>, and false otherwise.
*
* @return true if the entry identified by the given alias is a
* <i>trusted certificate entry</i>, false otherwise.
*/
return true;
} else {
return false;
}
}
/**
* 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.
*/
if (entry instanceof TrustedCertEntry) {
} else {
continue;
}
return alias;
}
}
return null;
}
/**
* Stores this keystore to the given output stream, and protects its
* integrity with the given password.
*
* @param stream Ignored. the output stream to which this keystore is written.
* @param password the password to generate the keystore integrity check
*
* @exception IOException if there was an I/O problem with data
* @exception NoSuchAlgorithmException if the appropriate data integrity
* algorithm could not be found
* @exception CertificateException if any of the certificates included in
* the keystore data could not be stored
*/
{
// Delete items that do have a keychain item ref.
if (entry instanceof TrustedCertEntry) {
}
} else {
}
}
}
}
}
}
// Add all of the certs or keys in the added entries.
// No need to check for 0 refs, as they are in the added list.
if (entry instanceof TrustedCertEntry) {
} else {
}
}
}
}
// Clear the added and deletedEntries hashtables here, now that we're done with the updates.
// For the deleted entries, we freed up the native references above.
}
long returnValue = 0;
try {
} catch (Exception e) {
e.printStackTrace();
}
return returnValue;
}
private native long _addItemToKeychain(String alias, boolean isCertificate, byte[] datablob, char[] password);
/**
* Loads the keystore from the Keychain.
*
* @param stream Ignored - here for API compatibility.
* @param password Ignored - if user needs to unlock keychain Security
* framework will post any dialogs.
*
* @exception IOException if there is an I/O or format problem with the
* keystore data
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*/
{
// Release any stray keychain references before clearing out the entries.
synchronized(entries) {
if (entry instanceof TrustedCertEntry) {
}
} else {
}
}
}
}
}
}
}
}
private native void _scanKeychain();
/**
* Callback method from _scanKeychain. If a trusted certificate is found, this method will be called.
*/
private void createTrustedCertEntry(String alias, long keychainItemRef, long creationDate, byte[] derStream) {
try {
// Make a creation date.
if (creationDate != 0)
else
int uniqueVal = 1;
uniqueVal++;
}
} catch (Exception e) {
// The certificate will be skipped.
}
}
/**
* Callback method from _scanKeychain. If an identity is found, this method will be called to create Java certificate
* and private key objects from the keychain data.
*/
private void createKeyEntry(String alias, long creationDate, long secKeyRef, long[] secCertificateRefs, byte[][] rawCertData)
// First, store off the private key information. This is the easy part.
// Make a creation date.
if (creationDate != 0)
else
// Next, create X.509 Certificate objects from the raw data. This is complicated
// because a certificate's public key may be too long for Java's default encryption strength.
try {
try {
// We successfully created the certificate, so track it and its corresponding SecCertificateRef.
} catch (CertificateException e) {
// The certificate will be skipped.
}
}
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException ioe) {
}
// We have our certificates in the List, so now extract them into an array of
// Certificates and SecCertificateRefs.
}
// If we don't have already have an item with this item's alias
// create a new one for it.
int uniqueVal = 1;
uniqueVal++;
}
}
private class CertKeychainItemPair {
long mCertificateRef;
}
}
/*
* Validate Certificate Chain
*/
{
return false;
}
return true;
}
private byte[] fetchPrivateKeyFromBag(byte[] privateKeyInfo) throws IOException, NoSuchAlgorithmException, CertificateException
{
byte[] returnValue = null;
int version = s.getInteger();
if (version != 3) {
throw new IOException("PKCS12 keystore not in version 3 format");
}
/*
* Read the authSafe.
*/
byte[] authSafeData;
} else /* signed data */ {
throw new IOException("public key protected PKCS12 not supported");
}
/*
* Spin over the ContentInfos.
*/
for (int i = 0; i < count; i++) {
byte[] safeContentsData;
// The password was used to export the private key from the keychain.
// The Keychain won't export the key with encrypted data, so we don't need
// to worry about it.
continue;
} else {
throw new IOException("public key protected PKCS12" +
" not supported");
}
}
return returnValue;
}
{
byte[] returnValue = null;
/*
* Spin over the SafeBags.
*/
for (int i = 0; i < count; i++) {
throw new IOException("unsupported PKCS12 bag value type "
}
// got what we were looking for. Return it.
} else {
// log error message for "unsupported PKCS12 bag type"
}
}
return returnValue;
}
/*
* Generate PBE Algorithm Parameters
*/
throws IOException
{
// create PBE parameters from salt and iteration count
try {
} catch (Exception e) {
new IOException("getAlgorithmParameters failed: " +
e.getMessage());
throw ioe;
}
return algParams;
}
// the source of randomness
/*
* Generate random salt
*/
private byte[] getSalt()
{
// Generate a random salt.
random = new SecureRandom();
}
return salt;
}
/*
* parse Algorithm Parameters
*/
throws IOException
{
try {
} else {
}
}
}
} catch (Exception e) {
new IOException("parseAlgParameters failed: " +
e.getMessage());
throw ioe;
}
return algParams;
}
/*
* Generate PBE key
*/
{
try {
} catch (Exception e) {
e.getMessage());
throw ioe;
}
return skey;
}
/*
* Encrypt private key using Password-based encryption (PBE)
* as defined in PKCS#5.
*
* NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
* used to derive the key and IV.
*
* @return encrypted private key encoded as EncryptedPrivateKeyInfo
*/
{
try {
// create AlgorithmParameters
getAlgorithmParameters("PBEWithSHA1AndDESede");
// Use JCE
// wrap encrypted private key in EncryptedPrivateKeyInfo
// as defined in PKCS#8
} catch (Exception e) {
new UnrecoverableKeyException("Encrypt Private Key failed: "
+ e.getMessage());
throw uke;
}
return ((byte[])key);
}
}