/*
* 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 "PKCS12".
* Implements the PKCS#12 PFX protected using the Password privacy mode.
* The contents are protected using Password integrity mode.
*
* Currently we support following PBE algorithms:
* - pbeWithSHAAnd3KeyTripleDESCBC to encrypt private keys
* - pbeWithSHAAnd40BitRC2CBC to encrypt certificates
*
* Supported encryption of various implementations :
*
* Software and mode. Certificate encryption Private key encryption
* ---------------------------------------------------------------------
* MSIE4 (domestic 40 bit RC2. 40 bit RC2
* and xport versions)
* PKCS#12 export.
*
* MSIE4, 5 (domestic 40 bit RC2, 40 bit RC2,
* and export versions) 3 key triple DES 3 key triple DES
* PKCS#12 import.
*
* MSIE5 40 bit RC2 3 key triple DES,
* PKCS#12 export. with SHA1 (168 bits)
*
* Netscape Communicator 40 bit RC2 3 key triple DES,
* (domestic and export with SHA1 (168 bits)
* versions) PKCS#12 export
*
* Netscape Communicator 40 bit ciphers only All.
* (export version)
* PKCS#12 import.
*
* Netscape Communicator All. All.
* (domestic or fortified
* version) PKCS#12 import.
*
* OpenSSL PKCS#12 code. All. All.
* ---------------------------------------------------------------------
*
* NOTE: Currently PKCS12 KeyStore does not support TrustedCertEntries.
* PKCS#12 is mainly used to deliver private keys with their associated
* certificate chain and aliases. In a PKCS12 keystore, entries are
* identified by the alias, and a localKeyId is required to match the
* private key with the certificate.
*
* @author Seema Malkani
* @author Jeff Nisewanger
* @author Jan Luehe
*
* @see KeyProtector
* @see java.security.KeyStoreSpi
* @see KeyTool
*
*
*/
private static final int pbeWithSHAAnd40BitRC2CBC[] =
{1, 2, 840, 113549, 1, 12, 1, 6};
private static final int pbeWithSHAAnd3KeyTripleDESCBC[] =
{1, 2, 840, 113549, 1, 12, 1, 3};
// private key count
// Note: This is a workaround to allow null localKeyID attribute
// in pkcs12 with one private key entry and associated cert-chain
// the source of randomness
static {
try {
} catch (IOException ioe) {
// should not happen
}
}
// Private keys and their supporting certificate chains
private static class KeyEntry {
byte[] protectedPrivKey;
byte[] keyId;
};
// A certificate with its PKCS #9 attributes
private static class CertEntry {
final byte[] keyId;
}
}
/**
* Private keys and certificates are stored in a hashtable.
* Hash entries are keyed by alias names.
*/
/**
* 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;
}
// get the encoded private key
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;
}
try {
byte[] privateKeyInfo;
while (true) {
try {
// Use JCE
break;
} catch (Exception e) {
// Retry using an empty password
// without a NULL terminator.
password = new char[1];
continue;
}
throw e;
}
}
/*
* Parse the key algorithm and then use a JCA key factory
* to create the private key.
*/
int i = in.getInteger();
} catch (Exception e) {
new UnrecoverableKeyException("Get Key failed: " +
e.getMessage());
throw uke;
}
return key;
}
/**
* 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.
*/
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
*/
} 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
*/
throws KeyStoreException
{
try {
if (key instanceof PrivateKey) {
// Encrypt the private key
} else {
throw new KeyStoreException("Private key is not encoded" +
"as PKCS#8");
}
} else {
throw new KeyStoreException("Key is not a PrivateKey");
}
// clone the chain
// validate cert-chain
throw new KeyStoreException("Certificate chain is " +
"not validate");
}
// set the keyId to current date
// set the alias
// add the entry
" algorithm not found: " + nsae);
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
{
// key must be encoded as EncryptedPrivateKeyInfo
// as defined in PKCS#8
try {
new EncryptedPrivateKeyInfo(key);
} catch (IOException ioe) {
+ " stored as PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
throw ke;
}
try {
// set the keyId to current date
} catch (UnsupportedEncodingException ex) {
// Won't happen
}
// set the alias
}
// add the entry
}
/*
* Generate random salt
*/
private byte[] getSalt()
{
// Generate a random salt.
random = new SecureRandom();
}
return salt;
}
/*
* 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;
}
/*
* 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 key;
}
/**
* 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
* identify a <i>key entry</i>, or on an attempt to create a
* <i>trusted cert entry</i> which is currently not supported.
*/
{
throw new KeyStoreException("Cannot overwrite own certificate");
} else
throw new KeyStoreException("TrustedCertEntry not supported");
}
/**
* 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
{
}
/**
* 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.
*/
// TrustedCertEntry is not supported
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.
*/
}
return alias;
}
}
return null;
}
/**
* Stores this keystore to the given output stream, and protects its
* integrity with the given password.
*
* @param stream 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
*/
{
// password is mandatory when storing
throw new IllegalArgumentException("password can't be null");
}
// -- Create PFX
// PFX version (always write the latest version)
// -- Create AuthSafe
// -- Create ContentInfos
// -- create safeContent Data ContentInfo
byte[] safeContentData = createSafeContent();
// -- create EncryptedContentInfo
// wrap as SequenceOf ContentInfos
// Create Encapsulated ContentInfo
// -- MAC
// write PFX to output stream
}
/*
* Generate Hash.
*/
{
try {
} catch (Exception e) {
throw ioe;
}
return digest;
}
/*
* Calculate MAC using HMAC algorithm (required for password integrity)
*
* Hash-based MAC algorithm combines secret key with message digest to
* create a message authentication code (MAC)
*/
throws IOException
{
try {
// Generate a random salt.
// generate MAC (MAC key is generated within JCE)
// encode as MacData
} catch (Exception e) {
throw ioe;
}
return mData;
}
/*
* Validate Certificate Chain
*/
{
return false;
}
return true;
}
/*
* Create PKCS#12 Attributes, friendlyName and localKeyId.
*
* Although attributes are optional, they could be required.
* For e.g. localKeyId attribute is required to match the
* private key with the associated end-entity certificate.
*
* PKCS8ShroudedKeyBags include unique localKeyID and friendlyName.
* CertBags may or may not include attributes depending on the type
* of Certificate. In end-entity certificates, localKeyID should be
* unique, and the corresponding private key should have the same
* localKeyID. For trusted CA certs in the cert-chain, localKeyID
* attribute is not required, hence most vendors don't include it.
* ignore it.
*
* Here is a list of pkcs12 attribute values in CertBags.
*
* --------------------------------------------------------------
* LocalKeyId
* (In EE cert only,
* NULL in CA certs) true true true true
*
* friendlyName unique same/ same/ unique
* unique unique/
* null
*
* Note: OpenSSL adds friendlyName for end-entity cert only, and
* removes the localKeyID and friendlyName for CA certs.
* If the CertBag did not have a friendlyName, most vendors will
* add it, and assign it to the DN of the cert.
*/
throws IOException {
byte[] localKeyID = null;
byte[] friendlyName = null;
// return null if both attributes are null
return null;
}
// SafeBag Attributes
// Encode the friendlyname oid.
}
// Encode the localkeyId oid.
}
if (friendlyName != null) {
}
if (localKeyID != null) {
}
return bagAttrs.toByteArray();
}
/*
* Create EncryptedData content type, that contains EncryptedContentInfo.
* Includes certificates in individual SafeBags of type CertBag.
* Each CertBag may include pkcs12 attributes
* (see comments in getBagAttributes)
*/
throws CertificateException, IOException
{
// certificate chain
int chainLen;
chainLen = 0;
} else {
}
for (int i = 0; i < chainLen; i++) {
// create SafeBag of Type CertBag
// create a CertBag
// write encoded certs in a context-specific tag
true, (byte) 0), certValue);
// wrap CertBag in a Sequence
// Wrap the CertBag encoding in a context-specific tag.
// write SafeBag Value
true, (byte) 0), bagValue);
// write SafeBag Attributes
// All Certs should have a unique friendlyName.
// This change is made to meet NSS requirements.
if (i == 0) {
// Only End-Entity Cert should have a localKeyId.
} else {
// Trusted root CA certs and Intermediate CA certs do not
// need to have a localKeyId, and hence localKeyId is null
// NSS pkcs12 library requires trusted CA certs in the
// certificate chain to have unique or null localKeyID.
}
}
// wrap as Sequence
} // for cert-chain
}
// wrap as SequenceOf SafeBag
// encrypt the content (EncryptedContentInfo)
// -- SEQUENCE of EncryptedData
return encrDataContent.toByteArray();
}
/*
* Create SafeContent Data content type.
* Includes encrypted private key in a SafeBag of type PKCS8ShroudedKeyBag.
* Each PKCS8ShroudedKeyBag includes pkcs12 attributes
* (see comments in getBagAttributes)
*/
private byte[] createSafeContent()
throws CertificateException, IOException {
// Create SafeBag of type pkcs8ShroudedKeyBag
// get the encrypted private key
try {
} catch (IOException ioe) {
throw new IOException("Private key not stored as "
}
// Wrap the EncryptedPrivateKeyInfo in a context-specific tag.
true, (byte) 0), bagValue);
// write SafeBag Attributes
// wrap as Sequence
}
// wrap as Sequence
return safeBagValue.toByteArray();
}
/*
* Encrypt the contents using Password-based (PBE) encryption
* as defined in PKCS #5.
*
* NOTE: Currently pbeWithSHAAnd40BiteRC2-CBC algorithmID is used
* to derive the key and IV.
*
* @return encrypted contents encoded as EncryptedContentInfo
*/
throws IOException {
byte[] encryptedData = null;
// create AlgorithmParameters
getAlgorithmParameters("PBEWithSHA1AndRC2_40");
try {
// Use JCE
} catch (Exception e) {
" safe contents entry: " + e);
throw ioe;
}
// create EncryptedContentInfo
// Wrap encrypted data in a context-specific tag.
false, (byte)0), tmpout2);
// wrap EncryptedContentInfo in a Sequence
return out.toByteArray();
}
/**
* Loads the keystore from the given input stream.
*
* <p>If a password is given, it is used to check the integrity of the
* keystore data. Otherwise, the integrity of the keystore is not checked.
*
* @param stream the input stream from which the keystore is loaded
* @param password the (optional) password used to check the integrity of
* the keystore.
*
* @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
*/
{
return;
// reset the counter
counter = 0;
int version = s.getInteger();
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");
}
// reset the count at the start
privateKeyCount = 0;
/*
* Spin over the ContentInfos.
*/
for (int i = 0; i < count; i++) {
byte[] safeContentsData;
continue;
}
throw new IOException("encrypted content not present!");
}
newTag |= 0x20;
// parse Algorithm parameters
while (true) {
try {
// Use JCE
break;
} catch (Exception e) {
// Retry using an empty password
// without a NULL terminator.
password = new char[1];
continue;
}
throw new IOException(
"failed to decrypt safe contents entry: " + e, e);
}
}
} else {
throw new IOException("public key protected PKCS12" +
" not supported");
}
}
// The MacData is optional.
try {
algName = "SHA1";
}
// generate MAC (MAC key is created within JCE)
macData.getIterations());
m.update(authSafeData);
throw new SecurityException("Failed PKCS12" +
" integrity checking");
}
} catch (Exception e) {
new IOException("Integrity check failed: " + e);
throw ioe;
}
}
/*
* Match up private keys with certificate chains.
*/
new ArrayList<X509Certificate>();
break;
}
}
/* Update existing KeyEntry in entries table */
}
}
certEntries.clear();
}
/**
* Locates a matched CertEntry from certEntries, and returns its cert.
* @param entry the KeyEntry to match
* @return a certificate, null if not found
*/
keyIdMatch = ce;
// Full match!
}
aliasMatch = ce;
}
}
// keyId match first, for compatibility
else return null;
}
{
/*
* Spin over the SafeBags.
*/
for (int i = 0; i < count; i++) {
throw new IOException("unsupported PKCS12 bag value type "
}
throw new IOException("unsupported PKCS12 cert value type "
}
} else {
// log error message for "unsupported PKCS12 bag type"
}
try {
} catch (IOException e) {
// entry does not have attributes
// Note: CA certs can have no attributes
// OpenSSL generates pkcs12 with no attr for CA certs.
}
try {
} catch (IOException e) {
" should have a value " + e.getMessage());
}
} else {
// log error message for "unknown attr"
}
}
}
/*
* As per PKCS12 v1.0 friendlyname (alias) and localKeyId (keyId)
* are optional PKCS12 bagAttributes. But entries in the keyStore
* are identified by their alias. Hence we need to have an
* Unfriendlyname in the alias, if alias is null. The keyId
* attribute is required to match the private key with the
* certificate. If we get a bagItem of type KeyEntry with a
* null keyId, we should skip it entirely.
*/
// Insert a localKeyID for the privateKey
// Note: This is a workaround to allow null localKeyID
// attribute in pkcs12 with one private key entry and
// associated cert-chain
if (privateKeyCount == 1) {
} else {
continue;
}
}
// restore date if it exists
try {
} catch (Exception e) {
}
}
}
alias = getUnfriendlyName();
} else if (bagItem instanceof X509Certificate) {
// Insert a localKeyID for the corresponding cert
// Note: This is a workaround to allow null localKeyID
// attribute in pkcs12 with one private key entry and
// associated cert-chain
// insert localKeyID only for EE cert or self-signed cert
if (i == 0) {
}
}
}
}
}
}
}
counter++;
}
}