Search in sources :

Example 1 with PrivateKey

use of org.mozilla.jss.crypto.PrivateKey in project jss by dogtagpki.

the class JSSKeyStoreSpi method engineGetKey.

@Override
public Key engineGetKey(String alias, char[] password) {
    logger.debug("JSSKeyStoreSpi: engineGetKey(" + alias + ")");
    try {
        CryptoManager cm = CryptoManager.getInstance();
        logger.debug("JSSKeyStoreSpi: searching for cert");
        try {
            X509Certificate cert = cm.findCertByNickname(alias);
            logger.debug("JSSKeyStoreSpi: found cert: " + alias);
            PrivateKey privateKey = cm.findPrivKeyByCert(cert);
            logger.debug("JSSKeyStoreSpi: found private key: " + alias);
            return privateKey;
        } catch (ObjectNotFoundException e) {
            logger.debug("JSSKeyStoreSpi: cert/key not found, searching for key");
        }
        String[] parts = parseAlias(alias);
        String tokenName = parts[0];
        String nickname = parts[1];
        CryptoToken token;
        if (tokenName == null) {
            token = cm.getInternalKeyStorageToken();
        } else {
            token = cm.getTokenByName(tokenName);
        }
        CryptoStore store = token.getCryptoStore();
        logger.debug("JSSKeyStoreSpi: searching for private key");
        for (PrivateKey privateKey : store.getPrivateKeys()) {
            // convert key ID into hexadecimal
            String keyID = Utils.HexEncode(privateKey.getUniqueID());
            logger.debug("JSSKeyStoreSpi: - " + keyID);
            if (nickname.equals(keyID)) {
                logger.debug("JSSKeyStoreSpi: found private key: " + nickname);
                return privateKey;
            }
        }
        logger.debug("JSSKeyStoreSpi: searching for symmetric key");
        for (SymmetricKey symmetricKey : store.getSymmetricKeys()) {
            logger.debug("JSSKeyStoreSpi: - " + symmetricKey.getNickName());
            if (nickname.equals(symmetricKey.getNickName())) {
                logger.debug("JSSKeyStoreSpi: found symmetric key: " + nickname);
                return new SecretKeyFacade(symmetricKey);
            }
        }
        logger.debug("JSSKeyStoreSpi: key not found: " + nickname);
        return null;
    } catch (NoSuchTokenException e) {
        throw new RuntimeException(e);
    } catch (NotInitializedException e) {
        throw new RuntimeException(e);
    } catch (TokenException e) {
        throw new RuntimeException(e);
    }
}
Also used : PrivateKey(org.mozilla.jss.crypto.PrivateKey) CryptoToken(org.mozilla.jss.crypto.CryptoToken) NotInitializedException(org.mozilla.jss.NotInitializedException) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) CryptoManager(org.mozilla.jss.CryptoManager) X509Certificate(org.mozilla.jss.crypto.X509Certificate) CryptoStore(org.mozilla.jss.crypto.CryptoStore) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) NoSuchTokenException(org.mozilla.jss.NoSuchTokenException) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) NoSuchTokenException(org.mozilla.jss.NoSuchTokenException) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) TokenException(org.mozilla.jss.crypto.TokenException)

Example 2 with PrivateKey

use of org.mozilla.jss.crypto.PrivateKey in project jss by dogtagpki.

the class JSSKeyStoreSpi method getAliases.

public Collection<String> getAliases() {
    logger.debug("JSSKeyStoreSpi: getAliases()");
    Set<String> aliases = new LinkedHashSet<>();
    try {
        List<CryptoToken> tokens = new ArrayList<>();
        CryptoManager cm = CryptoManager.getInstance();
        if (token == null) {
            logger.debug("JSSKeyStoreSpi: getting aliases from all tokens");
            Enumeration<CryptoToken> e = cm.getAllTokens();
            while (e.hasMoreElements()) {
                CryptoToken t = e.nextElement();
                if (t == cm.getInternalCryptoToken()) {
                    // exclude crypto token
                    continue;
                }
                tokens.add(t);
            }
        } else {
            logger.debug("JSSKeyStoreSpi: getting aliases from keystore token");
            tokens.add(token);
        }
        for (CryptoToken token : tokens) {
            String tokenName;
            if (token == cm.getInternalKeyStorageToken()) {
                tokenName = null;
                logger.debug("JSSKeyStoreSpi: token: internal");
            } else {
                tokenName = token.getName();
                logger.debug("JSSKeyStoreSpi: token: " + tokenName);
            }
            CryptoStore store = token.getCryptoStore();
            logger.debug("JSSKeyStoreSpi: - certificates:");
            for (X509Certificate cert : store.getCertificates()) {
                String nickname = cert.getNickname();
                logger.debug("JSSKeyStoreSpi:   - " + nickname);
                aliases.add(nickname);
            }
            logger.debug("JSSKeyStoreSpi: - private keys:");
            for (PrivateKey privateKey : store.getPrivateKeys()) {
                // convert key ID into hexadecimal
                String keyID = Utils.HexEncode(privateKey.getUniqueID());
                String nickname;
                if (tokenName == null) {
                    nickname = keyID;
                } else {
                    nickname = tokenName + ":" + keyID;
                }
                logger.debug("JSSKeyStoreSpi:   - " + nickname);
                aliases.add(nickname);
            }
        }
        return aliases;
    } catch (NotInitializedException e) {
        throw new RuntimeException(e);
    } catch (TokenException e) {
        throw new RuntimeException(e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) CryptoToken(org.mozilla.jss.crypto.CryptoToken) PrivateKey(org.mozilla.jss.crypto.PrivateKey) NotInitializedException(org.mozilla.jss.NotInitializedException) ArrayList(java.util.ArrayList) CryptoManager(org.mozilla.jss.CryptoManager) X509Certificate(org.mozilla.jss.crypto.X509Certificate) CryptoStore(org.mozilla.jss.crypto.CryptoStore) NoSuchTokenException(org.mozilla.jss.NoSuchTokenException) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) TokenException(org.mozilla.jss.crypto.TokenException)

Example 3 with PrivateKey

use of org.mozilla.jss.crypto.PrivateKey in project jss by dogtagpki.

the class JSSSignatureSpi method getSigContext.

private org.mozilla.jss.crypto.Signature getSigContext(java.security.PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, TokenException {
    CryptoToken token;
    PrivateKey privk;
    if (!(privateKey instanceof PrivateKey)) {
        throw new InvalidKeyException();
    }
    privk = (PrivateKey) privateKey;
    token = privk.getOwningToken();
    return token.getSignatureContext(alg);
}
Also used : CryptoToken(org.mozilla.jss.crypto.CryptoToken) PrivateKey(org.mozilla.jss.crypto.PrivateKey) InvalidKeyException(java.security.InvalidKeyException)

Example 4 with PrivateKey

use of org.mozilla.jss.crypto.PrivateKey in project jss by dogtagpki.

the class PKCS12Util method addKeyBag.

/**
 * Add a private key to the PKCS #12 object.
 *
 * The PKCS12KeyInfo object received comes about in two
 * different scenarios:
 *
 * - The private key could be in encrypted byte[] form (e.g.
 *   when we have merely loaded a PKCS #12 file for inspection
 *   or e.g. to delete a certificate and its associated key).
 *   In this case we simply re-use this encrypted private key
 *   info byte[].
 *
 * - The private key could be a be an NSS PrivateKey handle.  In
 *   this case we must export the PrivateKey from the token to
 *   obtain the EncryptedPrivateKeyInfo.
 *
 * The common final step is to add the encrypted private key
 * data to a "Shrouded Key Bag" to the PKCS #12 object.
 * Unencrypted key material is never seen.
 */
public void addKeyBag(PKCS12KeyInfo keyInfo, Password password, SEQUENCE encSafeContents) throws Exception {
    byte[] keyID = keyInfo.getID();
    logger.debug(" - Key ID: " + Utils.HexEncode(keyID));
    ASN1Value content;
    byte[] epkiBytes = keyInfo.getEncryptedPrivateKeyInfoBytes();
    if (epkiBytes != null) {
        // private key already encrypted
        content = new ANY(epkiBytes);
    } else {
        PrivateKey privateKey = keyInfo.getPrivateKey();
        if (privateKey == null) {
            throw new Exception("Missing private key for " + keyInfo.getFriendlyName());
        }
        CryptoToken token = CryptoManager.getInstance().getInternalKeyStorageToken();
        if (keyEncryption == PBEAlgorithm.PBE_SHA1_DES3_CBC) {
            content = create_EPKI_with_PBE_SHA1_DES3_CBC(token, privateKey, password);
        } else if (keyEncryption == PBEAlgorithm.PBE_PKCS5_PBES2) {
            content = create_EPKI_with_PBE_PKCS5_PBES2(token, privateKey, password);
        } else {
            throw new Exception("Unsupported key encryption: " + keyEncryption);
        }
    }
    SET keyAttrs = createKeyBagAttrs(keyInfo);
    SafeBag safeBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG, content, keyAttrs);
    encSafeContents.addElement(safeBag);
}
Also used : ASN1Value(org.mozilla.jss.asn1.ASN1Value) PrivateKey(org.mozilla.jss.crypto.PrivateKey) CryptoToken(org.mozilla.jss.crypto.CryptoToken) SET(org.mozilla.jss.asn1.SET) ANY(org.mozilla.jss.asn1.ANY) SafeBag(org.mozilla.jss.pkcs12.SafeBag) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) CertificateException(java.security.cert.CertificateException) InvalidNameException(javax.naming.InvalidNameException)

Example 5 with PrivateKey

use of org.mozilla.jss.crypto.PrivateKey in project jss by dogtagpki.

the class PKCS12Util method loadCertFromNSS.

public void loadCertFromNSS(PKCS12 pkcs12, X509Certificate cert, boolean includeKey, boolean includeChain, String friendlyName) throws Exception {
    CryptoManager cm = CryptoManager.getInstance();
    PKCS12CertInfo certInfo = createCertInfoFromNSS(cert, friendlyName);
    pkcs12.addCertInfo(certInfo, true);
    byte[] id = certInfo.getID();
    logger.debug(" - Certificate ID: " + Utils.HexEncode(id));
    logger.debug("   Friendly name: " + certInfo.getFriendlyName());
    logger.debug("   Trust flags: " + certInfo.getTrustFlags());
    if (includeKey) {
        try {
            PrivateKey privateKey = cm.findPrivKeyByCert(cert);
            PKCS12KeyInfo keyInfo = createKeyInfoFromNSS(cert, privateKey, friendlyName);
            pkcs12.addKeyInfo(keyInfo);
            byte[] keyID = keyInfo.getID();
            certInfo.setKeyID(keyID);
            logger.debug("   Key ID: " + Utils.HexEncode(keyID));
        } catch (ObjectNotFoundException e) {
            logger.debug("Certificate has no private key");
        }
    }
    if (includeChain) {
        // load cert chain
        X509Certificate[] certChain = cm.buildCertificateChain(cert);
        if (certChain.length > 1) {
            logger.debug("   Certificate Chain:");
        }
        for (int i = 1; i < certChain.length; i++) {
            X509Certificate caCert = certChain[i];
            PKCS12CertInfo caCertInfo = createCertInfoFromNSS(caCert);
            pkcs12.addCertInfo(caCertInfo, false);
            byte[] caCertID = caCertInfo.getID();
            logger.debug("   - Certificate ID: " + Utils.HexEncode(caCertID));
            logger.debug("     Friendly name: " + caCertInfo.getFriendlyName());
            logger.debug("     Trust flags: " + caCertInfo.getTrustFlags());
        }
    }
}
Also used : PrivateKey(org.mozilla.jss.crypto.PrivateKey) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) CryptoManager(org.mozilla.jss.CryptoManager) X509Certificate(org.mozilla.jss.crypto.X509Certificate)

Aggregations

PrivateKey (org.mozilla.jss.crypto.PrivateKey)6 CryptoToken (org.mozilla.jss.crypto.CryptoToken)5 CryptoManager (org.mozilla.jss.CryptoManager)4 NoSuchItemOnTokenException (org.mozilla.jss.crypto.NoSuchItemOnTokenException)4 ObjectNotFoundException (org.mozilla.jss.crypto.ObjectNotFoundException)4 X509Certificate (org.mozilla.jss.crypto.X509Certificate)4 NoSuchTokenException (org.mozilla.jss.NoSuchTokenException)3 NotInitializedException (org.mozilla.jss.NotInitializedException)3 CryptoStore (org.mozilla.jss.crypto.CryptoStore)3 TokenException (org.mozilla.jss.crypto.TokenException)3 InvalidKeyException (java.security.InvalidKeyException)1 KeyStoreException (java.security.KeyStoreException)1 PublicKey (java.security.PublicKey)1 CertificateException (java.security.cert.CertificateException)1 ArrayList (java.util.ArrayList)1 LinkedHashSet (java.util.LinkedHashSet)1 InvalidNameException (javax.naming.InvalidNameException)1 ANY (org.mozilla.jss.asn1.ANY)1 ASN1Value (org.mozilla.jss.asn1.ASN1Value)1 SET (org.mozilla.jss.asn1.SET)1