Search in sources :

Example 21 with TokenException

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

the class JSSCipherSpi method engineInit.

@Override
public void engineInit(int opmode, Key key, AlgorithmParameterSpec givenParams, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    try {
        // throw away any previous state
        cipher = null;
        wrapper = null;
        params = givenParams;
        if (algFamily == null) {
            throw new InvalidAlgorithmParameterException("incorrectly specified algorithm");
        }
        if (opmode != Cipher.ENCRYPT_MODE && opmode != Cipher.DECRYPT_MODE && opmode != Cipher.WRAP_MODE && opmode != Cipher.UNWRAP_MODE) {
            throw new InvalidKeyException("Invalid opmode");
        }
        StringBuffer buf = new StringBuffer();
        buf.append(algFamily);
        if (algMode != null) {
            buf.append('/');
            buf.append(algMode);
        }
        if (algPadding != null) {
            buf.append('/');
            buf.append(algPadding);
        }
        if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.DECRYPT_MODE) {
            if (!(key instanceof SecretKeyFacade)) {
                key = importKey(key);
            }
            SymmetricKey symkey = ((SecretKeyFacade) key).key;
            // lookup the encryption algorithm
            keyStrength = symkey.getStrength();
            encAlg = EncryptionAlgorithm.lookup(algFamily, algMode, algPadding, keyStrength);
            blockSize = encAlg.getBlockSize();
            if (!token.doesAlgorithm(encAlg)) {
                throw new NoSuchAlgorithmException(encAlg.toString() + " is not supported by this token " + token.getName());
            }
            cipher = token.getCipherContext(encAlg);
            if (opmode == Cipher.ENCRYPT_MODE) {
                if (params == noAlgParams) {
                    // we're supposed to generate some params
                    params = generateAlgParams(encAlg, blockSize);
                }
                cipher.initEncrypt(symkey, params);
            } else if (opmode == Cipher.DECRYPT_MODE) {
                if (params == noAlgParams) {
                    params = null;
                }
                cipher.initDecrypt(symkey, params);
            }
        } else {
            assert (opmode == Cipher.WRAP_MODE || opmode == Cipher.UNWRAP_MODE);
            wrapAlg = KeyWrapAlgorithm.fromString(buf.toString());
            blockSize = wrapAlg.getBlockSize();
            wrapper = token.getKeyWrapper(wrapAlg);
            // generate params if necessary
            if (params == noAlgParams) {
                if (opmode == Cipher.WRAP_MODE) {
                    params = generateAlgParams(wrapAlg, blockSize);
                } else {
                    assert (opmode == Cipher.UNWRAP_MODE);
                    params = null;
                }
            }
            if (key instanceof org.mozilla.jss.crypto.PrivateKey) {
                if (opmode != Cipher.UNWRAP_MODE) {
                    throw new InvalidKeyException("Private key can only be used for unwrapping");
                }
                wrapper.initUnwrap((org.mozilla.jss.crypto.PrivateKey) key, params);
            } else if (key instanceof PublicKey) {
                if (opmode != Cipher.WRAP_MODE) {
                    throw new InvalidKeyException("Public key can only be used for wrapping");
                }
                wrapper.initWrap((PublicKey) key, params);
            } else if (key instanceof org.mozilla.jss.crypto.SecretKeyFacade) {
                org.mozilla.jss.crypto.SecretKeyFacade sk = (org.mozilla.jss.crypto.SecretKeyFacade) key;
                if (opmode == Cipher.WRAP_MODE) {
                    wrapper.initWrap(sk.key, params);
                } else {
                    assert (opmode == Cipher.UNWRAP_MODE);
                    wrapper.initUnwrap(sk.key, params);
                }
            } else {
                throw new InvalidKeyException("Invalid key type: " + key.getClass().getName());
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidAlgorithmParameterException(e.getMessage());
    } catch (TokenException te) {
        throw new TokenRuntimeException(te.getMessage());
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) TokenRuntimeException(org.mozilla.jss.crypto.TokenRuntimeException) TokenException(org.mozilla.jss.crypto.TokenException)

Example 22 with TokenException

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

the class JSSSecretKeyFactorySpi method engineGenerateSecret.

@Override
public SecretKey engineGenerateSecret(KeySpec spec) throws InvalidKeySpecException {
    try {
        if (spec instanceof PBEKeySpec || spec instanceof PBEKeyGenParams) {
            PBEKeyGenParams params;
            if (spec instanceof PBEKeySpec) {
                params = makePBEKeyGenParams((PBEKeySpec) spec);
            } else {
                params = (org.mozilla.jss.crypto.PBEKeyGenParams) spec;
            }
            org.mozilla.jss.crypto.KeyGenerator gen = token.getKeyGenerator(alg);
            gen.initialize(params);
            SymmetricKey symk = gen.generate();
            params.clear();
            return new SecretKeyFacade(symk);
        } else if (spec instanceof DESedeKeySpec) {
            if (alg != KeyGenAlgorithm.DES3) {
                throw new InvalidKeySpecException("Incorrect KeySpec type (" + spec.getClass().getName() + ") for algorithm (" + alg.toString() + ")");
            }
            return generateKeyFromBits(((DESedeKeySpec) spec).getKey(), SymmetricKey.Type.DES3);
        } else if (spec instanceof DESKeySpec) {
            if (alg != KeyGenAlgorithm.DES) {
                throw new InvalidKeySpecException("Incorrect KeySpec type (" + spec.getClass().getName() + ") for algorithm (" + alg.toString() + ")");
            }
            return generateKeyFromBits(((DESKeySpec) spec).getKey(), SymmetricKey.Type.DES);
        } else if (spec instanceof SecretKeySpec) {
            SecretKeySpec kspec = (SecretKeySpec) spec;
            SymmetricKey.Type type = SymmetricKey.Type.fromName(kspec.getAlgorithm());
            return generateKeyFromBits(kspec.getEncoded(), type);
        } else {
            throw new InvalidKeySpecException("Unsupported KeySpec: " + spec.getClass().getName());
        }
    } catch (TokenException te) {
        throw new TokenRuntimeException(te.getMessage());
    } catch (InvalidAlgorithmParameterException iape) {
        throw new InvalidKeySpecException("InvalidAlgorithmParameterException: " + iape.getMessage());
    } catch (IllegalStateException e) {
        throw (TokenRuntimeException) new TokenRuntimeException("IllegalStateException: " + e.getMessage()).initCause(e);
    } catch (CharConversionException e) {
        throw new InvalidKeySpecException("CharConversionException: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeySpecException("NoSuchAlgorithmException: " + e.getMessage(), e);
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CharConversionException(java.io.CharConversionException) PBEKeyGenParams(org.mozilla.jss.crypto.PBEKeyGenParams) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) TokenRuntimeException(org.mozilla.jss.crypto.TokenRuntimeException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) TokenException(org.mozilla.jss.crypto.TokenException) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) DESKeySpec(javax.crypto.spec.DESKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 23 with TokenException

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

the class EncryptedPrivateKeyInfo method createPBE.

/**
 * Creates a new EncryptedPrivateKeyInfo, where the data is encrypted
 * with a password-based key-
 *       with wrapping/unwrapping happening on token.
 *
 * @param pbeAlg The algorithm for generating a symmetric key from
 *      a password, salt, and iteration count.
 * @param password The password to use in generating the key.
 * @param salt The salt to use in generating the key.
 * @param iterationCount The number of hashing iterations to perform
 *      while generating the key.
 * @param charToByteConverter The mechanism for converting the characters
 *      in the password into bytes.  If null, the default mechanism
 *      will be used, which is UTF8.
 * @param pri The PrivateKey to be encrypted and stored in the
 *      EncryptedContentInfo.
 */
public static EncryptedPrivateKeyInfo createPBE(PBEAlgorithm pbeAlg, Password password, byte[] salt, int iterationCount, KeyGenerator.CharToByteConverter charToByteConverter, PrivateKey pri, CryptoToken token) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, CharConversionException {
    try {
        // generate key
        KeyGenerator kg = token.getKeyGenerator(pbeAlg);
        PBEKeyGenParams pbekgParams = new PBEKeyGenParams(password, salt, iterationCount);
        if (charToByteConverter != null) {
            kg.setCharToByteConverter(charToByteConverter);
        }
        kg.initialize(pbekgParams);
        kg.temporaryKeys(true);
        SymmetricKey key = kg.generate();
        // generate IV
        EncryptionAlgorithm encAlg = pbeAlg.getEncryptionAlg();
        AlgorithmParameterSpec params = null;
        Class<?>[] paramClasses = encAlg.getParameterClasses();
        for (int i = 0; i < paramClasses.length; i++) {
            if (paramClasses[i].equals(javax.crypto.spec.IvParameterSpec.class)) {
                params = new IVParameterSpec(kg.generatePBE_IV());
                break;
            }
        }
        // wrap the key
        KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.fromOID(encAlg.toOID()));
        wrapper.initWrap(key, params);
        byte[] encrypted = wrapper.wrap(pri);
        // make encryption algorithm identifier
        PBEParameter pbeParam = new PBEParameter(salt, iterationCount);
        AlgorithmIdentifier encAlgID = new AlgorithmIdentifier(pbeAlg.toOID(), pbeParam);
        // create EncryptedPrivateKeyInfo
        EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encAlgID, new OCTET_STRING(encrypted));
        return epki;
    } catch (Exception e) {
        System.out.println("createPBE: exception:" + e.toString());
        throw new RuntimeException("Exception in EncryptedPrivateKeyInfo" + ".createPBE: " + e.getMessage(), e);
    }
}
Also used : IVParameterSpec(org.mozilla.jss.crypto.IVParameterSpec) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IllegalBlockSizeException(org.mozilla.jss.crypto.IllegalBlockSizeException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) CharConversionException(java.io.CharConversionException) TokenException(org.mozilla.jss.crypto.TokenException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NotInitializedException(org.mozilla.jss.NotInitializedException) InvalidKeyException(java.security.InvalidKeyException) KeyWrapper(org.mozilla.jss.crypto.KeyWrapper) PBEKeyGenParams(org.mozilla.jss.crypto.PBEKeyGenParams) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) EncryptionAlgorithm(org.mozilla.jss.crypto.EncryptionAlgorithm) KeyGenerator(org.mozilla.jss.crypto.KeyGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 24 with TokenException

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

the class JSSKeyStoreSpi method engineDeleteEntry.

@Override
public void engineDeleteEntry(String alias) throws KeyStoreException {
    try {
        CryptoManager manager = CryptoManager.getInstance();
        try {
            logger.debug("JSSKeyStoreSpi: searching for cert");
            X509Certificate cert = manager.findCertByNickname(alias);
            CryptoToken token;
            if (cert instanceof TokenCertificate) {
                TokenCertificate tokenCert = (TokenCertificate) cert;
                token = tokenCert.getOwningToken();
            } else {
                token = manager.getInternalKeyStorageToken();
            }
            CryptoStore store = token.getCryptoStore();
            logger.debug("JSSKeyStoreSpi: deleting cert: " + alias);
            store.deleteCertOnly(cert);
            return;
        } catch (ObjectNotFoundException e) {
            logger.debug("JSSKeyStoreSpi: cert not found, searching for key");
        }
        String[] parts = parseAlias(alias);
        String tokenName = parts[0];
        String nickname = parts[1];
        CryptoToken token;
        if (tokenName == null) {
            token = manager.getInternalKeyStorageToken();
        } else {
            token = manager.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)) {
                continue;
            }
            try {
                logger.debug("JSSKeyStoreSpi: searching for public key: " + nickname);
                PublicKey publicKey = store.findPublicKey(privateKey);
                logger.debug("JSSKeyStoreSpi: deleting public key: " + nickname);
                store.deletePublicKey(publicKey);
            } catch (ObjectNotFoundException e) {
                logger.debug("JSSKeyStoreSpi: public key not found: " + nickname);
            }
            logger.debug("JSSKeyStoreSpi: deleting private key: " + nickname);
            store.deletePrivateKey(privateKey);
            return;
        }
        logger.debug("JSSKeyStoreSpi: entry not found: " + alias);
        throw new KeyStoreException("Entry not found: " + alias);
    } catch (NotInitializedException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchTokenException e) {
        throw new KeyStoreException(e);
    } catch (TokenException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchItemOnTokenException e) {
        throw new KeyStoreException(e);
    }
}
Also used : CryptoToken(org.mozilla.jss.crypto.CryptoToken) PrivateKey(org.mozilla.jss.crypto.PrivateKey) NotInitializedException(org.mozilla.jss.NotInitializedException) PublicKey(java.security.PublicKey) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) CryptoManager(org.mozilla.jss.CryptoManager) KeyStoreException(java.security.KeyStoreException) X509Certificate(org.mozilla.jss.crypto.X509Certificate) CryptoStore(org.mozilla.jss.crypto.CryptoStore) 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) TokenCertificate(org.mozilla.jss.crypto.TokenCertificate)

Example 25 with TokenException

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

the class JSSKeyStoreSpi method engineIsCertificateEntry.

/**
 * Returns true if there is a cert with this nickname but there is no
 * key associated with the cert.
 */
@Override
public boolean engineIsCertificateEntry(String alias) {
    logger.debug("JSSKeyStoreSpi: engineIsCertificateEntry(" + alias + ")");
    try {
        CryptoManager cm = CryptoManager.getInstance();
        cm.findCertByNickname(alias);
        logger.debug("JSSKeyStoreSpi: cert found: " + alias);
        return true;
    } catch (ObjectNotFoundException e) {
        logger.debug("JSSKeyStoreSpi: cert not found: " + alias);
        return false;
    } catch (NotInitializedException e) {
        throw new RuntimeException(e);
    } catch (TokenException e) {
        throw new RuntimeException(e);
    }
}
Also used : NotInitializedException(org.mozilla.jss.NotInitializedException) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) NoSuchTokenException(org.mozilla.jss.NoSuchTokenException) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) TokenException(org.mozilla.jss.crypto.TokenException) CryptoManager(org.mozilla.jss.CryptoManager)

Aggregations

TokenException (org.mozilla.jss.crypto.TokenException)28 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11 NoSuchItemOnTokenException (org.mozilla.jss.crypto.NoSuchItemOnTokenException)10 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)9 CryptoManager (org.mozilla.jss.CryptoManager)9 NotInitializedException (org.mozilla.jss.NotInitializedException)9 InvalidKeyException (java.security.InvalidKeyException)8 NoSuchTokenException (org.mozilla.jss.NoSuchTokenException)8 CryptoToken (org.mozilla.jss.crypto.CryptoToken)8 ObjectNotFoundException (org.mozilla.jss.crypto.ObjectNotFoundException)8 X509Certificate (org.mozilla.jss.crypto.X509Certificate)8 SymmetricKey (org.mozilla.jss.crypto.SymmetricKey)7 SecretKeyFacade (org.mozilla.jss.crypto.SecretKeyFacade)5 CharConversionException (java.io.CharConversionException)4 TokenRuntimeException (org.mozilla.jss.crypto.TokenRuntimeException)4 CertificateException (java.security.cert.CertificateException)3 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)3 PBEKeyGenParams (org.mozilla.jss.crypto.PBEKeyGenParams)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2