apple.security.KeychainStore Maven / Gradle / Ivy
Show all versions of qbicc-rt-java.base Show documentation
/*
* Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved.
* 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
* 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.
*/
package apple.security;
import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.security.spec.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.security.auth.x500.*;
import sun.security.pkcs.*;
import sun.security.pkcs.EncryptedPrivateKeyInfo;
import sun.security.util.*;
import sun.security.x509.*;
/**
* 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.
*/
public final class KeychainStore extends KeyStoreSpi {
// 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.
static class KeyEntry {
Date date; // the creation date of this entry
byte[] protectedPrivKey;
char[] password;
long keyRef; // SecKeyRef for this key
Certificate chain[];
long chainRefs[]; // SecCertificateRefs for this key's chain.
};
// Trusted certificates
static class TrustedCertEntry {
Date date; // the creation date of this entry
Certificate cert;
long certRef; // SecCertificateRef for this key
};
/**
* Entries that have been deleted. When something calls engineStore we'll
* remove them from the keychain.
*/
private Hashtable deletedEntries = new Hashtable<>();
/**
* Entries that have been added. When something calls engineStore we'll
* add them to the keychain.
*/
private Hashtable addedEntries = new Hashtable<>();
/**
* Private keys and certificates are stored in a hashtable.
* Hash entries are keyed by alias names.
*/
private Hashtable entries = new Hashtable<>();
/**
* Algorithm identifiers and corresponding OIDs for the contents of the
* PKCS12 bag we get from the Keychain.
*/
private static ObjectIdentifier PKCS8ShroudedKeyBag_OID =
ObjectIdentifier.of(KnownOIDs.PKCS8ShroudedKeyBag);
private static ObjectIdentifier pbeWithSHAAnd3KeyTripleDESCBC_OID =
ObjectIdentifier.of(KnownOIDs.PBEWithSHA1AndDESede);
/**
* Constnats used in PBE decryption.
*/
private static final int iterationCount = 1024;
private static final int SALT_LEN = 20;
private static final Debug debug = Debug.getInstance("keystore");
static {
jdk.internal.loader.BootLoader.loadLibrary("osxsecurity");
}
private static void permissionCheck() {
@SuppressWarnings("removal")
SecurityManager sec = System.getSecurityManager();
if (sec != null) {
sec.checkPermission(new RuntimePermission("useKeychainStore"));
}
}
/**
* 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. This password is
* used internally as the key is exported in a PKCS12 format.
*
* @return the requested key, or null if the given alias does not exist
* or does not identify a key entry.
*
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* key cannot be found
* @exception UnrecoverableKeyException if the key cannot be recovered
* (e.g., the given password is wrong).
*/
public Key engineGetKey(String alias, char[] password)
throws NoSuchAlgorithmException, UnrecoverableKeyException
{
permissionCheck();
// An empty password is rejected by MacOS API, no private key data
// is exported. If no password is passed (as is the case when
// this implementation is used as browser keystore in various
// deployment scenarios like Webstart, JFX and applets), create
// a dummy password so MacOS API is happy.
if (password == null || password.length == 0) {
// Must not be a char array with only a 0, as this is an empty
// string.
if (random == null) {
random = new SecureRandom();
}
password = Long.toString(random.nextLong()).toCharArray();
}
Object entry = entries.get(alias.toLowerCase());
if (entry == null || !(entry instanceof KeyEntry)) {
return null;
}
// This call gives us a PKCS12 bag, with the key inside it.
byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry)entry).keyRef, password);
if (exportedKeyInfo == null) {
return null;
}
PrivateKey returnValue = null;
try {
byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);
byte[] encryptedKey;
AlgorithmParameters algParams;
ObjectIdentifier algOid;
try {
// get the encrypted private key
EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);
encryptedKey = encrInfo.getEncryptedData();
// parse Algorithm parameters
DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
DerInputStream in = val.toDerInputStream();
algOid = in.getOID();
algParams = parseAlgParameters(in);
} catch (IOException ioe) {
UnrecoverableKeyException uke =
new UnrecoverableKeyException("Private key not stored as "
+ "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
uke.initCause(ioe);
throw uke;
}
// Use JCE to decrypt the data using the supplied password.
SecretKey skey = getPBEKey(password);
Cipher cipher = Cipher.getInstance(algOid.toString());
cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);
PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);
// Parse the key algorithm and then use a JCA key factory to create the private key.
DerValue val = new DerValue(decryptedPrivateKey);
DerInputStream in = val.toDerInputStream();
// Ignore this -- version should be 0.
int i = in.getInteger();
// Get the Algorithm ID next
DerValue[] value = in.getSequence(2);
if (value.length < 1 || value.length > 2) {
throw new IOException("Invalid length for AlgorithmIdentifier");
}
AlgorithmId algId = new AlgorithmId(value[0].getOID());
String algName = algId.getName();
// Get a key factory for this algorithm. It's likely to be 'RSA'.
KeyFactory kfac = KeyFactory.getInstance(algName);
returnValue = kfac.generatePrivate(kspec);
} catch (Exception e) {
UnrecoverableKeyException uke =
new UnrecoverableKeyException("Get Key failed: " +
e.getMessage());
uke.initCause(e);
throw uke;
}
return returnValue;
}
private native byte[] _getEncodedKeyData(long secKeyRef, char[] password);
/**
* 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 trusted certificate entry or a
* key entry without a certificate chain).
*/
public Certificate[] engineGetCertificateChain(String alias) {
permissionCheck();
Object entry = entries.get(alias.toLowerCase());
if (entry != null && entry instanceof KeyEntry) {
if (((KeyEntry)entry).chain == null) {
return null;
} else {
return ((KeyEntry)entry).chain.clone();
}
} else {
return null;
}
}
/**
* Returns the certificate associated with the given alias.
*
* If the given alias name identifies a
* trusted certificate entry, the certificate associated with that
* entry is returned. If the given alias name identifies a
* key entry, 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) {
permissionCheck();
Object entry = entries.get(alias.toLowerCase());
if (entry != null) {
if (entry instanceof TrustedCertEntry) {
return ((TrustedCertEntry)entry).cert;
} else {
KeyEntry ke = (KeyEntry)entry;
if (ke.chain == null || ke.chain.length == 0) {
return null;
}
return ke.chain[0];
}
} else {
return null;
}
}
/**
* Returns the creation date of the entry identified by the given alias.
*
* @param alias the alias name
*
* @return the creation date of this entry, or null if the given alias does
* not exist
*/
public Date engineGetCreationDate(String alias) {
permissionCheck();
Object entry = entries.get(alias.toLowerCase());
if (entry != null) {
if (entry instanceof TrustedCertEntry) {
return new Date(((TrustedCertEntry)entry).date.getTime());
} else {
return new Date(((KeyEntry)entry).date.getTime());
}
} else {
return null;
}
}
/**
* Assigns the given key to the given alias, protecting it with the given
* password.
*
*
If the given key is of type java.security.PrivateKey
,
* it must be accompanied by a certificate chain certifying the
* corresponding public key.
*
*
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
* java.security.PrivateKey
).
*
* @exception KeyStoreException if the given key cannot be protected, or
* this operation fails for some other reason
*/
public void engineSetKeyEntry(String alias, Key key, char[] password,
Certificate[] chain)
throws KeyStoreException
{
permissionCheck();
synchronized(entries) {
try {
KeyEntry entry = new KeyEntry();
entry.date = new Date();
if (key instanceof PrivateKey) {
if ((key.getFormat().equals("PKCS#8")) ||
(key.getFormat().equals("PKCS8"))) {
entry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), password);
entry.password = password.clone();
} else {
throw new KeyStoreException("Private key is not encoded as PKCS#8");
}
} else {
throw new KeyStoreException("Key is not a PrivateKey");
}
// clone the chain
if (chain != null) {
if ((chain.length > 1) && !validateChain(chain)) {
throw new KeyStoreException("Certificate chain does not validate");
}
entry.chain = chain.clone();
entry.chainRefs = new long[entry.chain.length];
}
String lowerAlias = alias.toLowerCase();
if (entries.get(lowerAlias) != null) {
deletedEntries.put(lowerAlias, entries.get(lowerAlias));
}
entries.put(lowerAlias, entry);
addedEntries.put(lowerAlias, entry);
} catch (Exception nsae) {
KeyStoreException ke = new KeyStoreException("Key protection algorithm not found: " + nsae);
ke.initCause(nsae);
throw ke;
}
}
}
/**
* Assigns the given key (that has already been protected) to the given
* alias.
*
*
If the protected key is of type
* java.security.PrivateKey
, it must be accompanied by a
* certificate chain certifying the corresponding public key. If the
* underlying keystore implementation is of type jks
,
* key
must be encoded as an
* EncryptedPrivateKeyInfo
as defined in the PKCS #8 standard.
*
*
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
* java.security.PrivateKey
).
*
* @exception KeyStoreException if this operation fails.
*/
public void engineSetKeyEntry(String alias, byte[] key,
Certificate[] chain)
throws KeyStoreException
{
permissionCheck();
synchronized(entries) {
// key must be encoded as EncryptedPrivateKeyInfo as defined in
// PKCS#8
KeyEntry entry = new KeyEntry();
try {
EncryptedPrivateKeyInfo privateKey = new EncryptedPrivateKeyInfo(key);
entry.protectedPrivKey = privateKey.getEncoded();
} catch (IOException ioe) {
throw new KeyStoreException("key is not encoded as "
+ "EncryptedPrivateKeyInfo");
}
entry.date = new Date();
if ((chain != null) &&
(chain.length != 0)) {
entry.chain = chain.clone();
entry.chainRefs = new long[entry.chain.length];
}
String lowerAlias = alias.toLowerCase();
if (entries.get(lowerAlias) != null) {
deletedEntries.put(lowerAlias, entries.get(alias));
}
entries.put(lowerAlias, entry);
addedEntries.put(lowerAlias, entry);
}
}
/**
* Assigns the given certificate to the given alias.
*
*
If the given alias already exists in this keystore and identifies a
* trusted certificate entry, 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 trusted certificate entry, or this operation
* fails for some other reason.
*/
public void engineSetCertificateEntry(String alias, Certificate cert)
throws KeyStoreException
{
permissionCheck();
synchronized(entries) {
Object entry = entries.get(alias.toLowerCase());
if ((entry != null) && (entry instanceof KeyEntry)) {
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.
Collection