Search in sources :

Example 61 with Key

use of java.security.Key in project zaproxy by zaproxy.

the class ZapNTLMEngineImpl method lmResponse.

/**
     * Creates the LM Response from the given hash and Type 2 challenge.
     *
     * @param hash
     *            The LM or NTLM Hash.
     * @param challenge
     *            The server challenge from the Type 2 message.
     *
     * @return The response (either LM or NTLM, depending on the provided hash).
     */
private static byte[] lmResponse(final byte[] hash, final byte[] challenge) throws AuthenticationException {
    try {
        final byte[] keyBytes = new byte[21];
        System.arraycopy(hash, 0, keyBytes, 0, 16);
        final Key lowKey = createDESKey(keyBytes, 0);
        final Key middleKey = createDESKey(keyBytes, 7);
        final Key highKey = createDESKey(keyBytes, 14);
        final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
        des.init(Cipher.ENCRYPT_MODE, lowKey);
        final byte[] lowResponse = des.doFinal(challenge);
        des.init(Cipher.ENCRYPT_MODE, middleKey);
        final byte[] middleResponse = des.doFinal(challenge);
        des.init(Cipher.ENCRYPT_MODE, highKey);
        final byte[] highResponse = des.doFinal(challenge);
        final byte[] lmResponse = new byte[24];
        System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
        System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
        System.arraycopy(highResponse, 0, lmResponse, 16, 8);
        return lmResponse;
    } catch (Exception e) {
        throw new AuthenticationException(e.getMessage(), e);
    }
}
Also used : AuthenticationException(org.apache.commons.httpclient.auth.AuthenticationException) Cipher(javax.crypto.Cipher) Key(java.security.Key) AuthenticationException(org.apache.commons.httpclient.auth.AuthenticationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 62 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class ConfigServiceCertificateStore method certFromData.

private X509Certificate certFromData(byte[] data) {
    X509Certificate retVal = null;
    try {
        // first check for wrapped data
        final CertContainer container = CertUtils.toCertContainer(data);
        if (container.getWrappedKeyData() != null) {
            // make sure we have a KeyStoreManager configured
            if (this.mgr == null) {
                throw new NHINDException(AgentError.Unexpected, "Resolved certifiate has wrapped data, but resolver has not been configured to unwrap it.");
            }
            // create a new wrapped certificate object
            retVal = WrappedOnDemandX509CertificateEx.fromX509Certificate(mgr, container.getCert(), container.getWrappedKeyData());
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
            localKeyStore.load(bais, "".toCharArray());
            Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias 
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                Key key = localKeyStore.getKey(alias, "".toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
                } else
                    retVal = cert;
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (retVal == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
        }
        bais.close();
    } catch (Exception e) {
        throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) NHINDException(org.nhindirect.stagent.NHINDException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) Key(java.security.Key) PrivateKey(java.security.PrivateKey) CacheException(org.apache.jcs.access.exception.CacheException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 63 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class RESTSmtpAgentConfigFunctional_Test method loadPkcs12FromCertAndKey.

private static byte[] loadPkcs12FromCertAndKey(String certFileName, String keyFileName) throws Exception {
    byte[] retVal = null;
    try {
        KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
        localKeyStore.load(null, null);
        byte[] certData = loadCertificateData(certFileName);
        byte[] keyData = loadCertificateData(keyFileName);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream inStr = new ByteArrayInputStream(certData);
        java.security.cert.Certificate cert = cf.generateCertificate(inStr);
        inStr.close();
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyData);
        Key privKey = kf.generatePrivate(keysp);
        char[] array = "".toCharArray();
        localKeyStore.setKeyEntry("privCert", privKey, array, new java.security.cert.Certificate[] { cert });
        ByteArrayOutputStream outStr = new ByteArrayOutputStream();
        localKeyStore.store(outStr, array);
        retVal = outStr.toByteArray();
        outStr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return retVal;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyFactory(java.security.KeyFactory) Key(java.security.Key)

Example 64 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class CertStoreUtils method certFromData.

public static X509Certificate certFromData(KeyStoreProtectionManager mgr, byte[] data) {
    X509Certificate retVal = null;
    try {
        // first check for wrapped data
        final CertContainer container = CertUtils.toCertContainer(data);
        if (container.getWrappedKeyData() != null) {
            // make sure we have a KeyStoreManager configured
            if (mgr == null) {
                throw new NHINDException(AgentError.Unexpected, "Resolved certifiate has wrapped data, but resolver has not been configured to unwrap it.");
            }
            // create a new wrapped certificate object
            retVal = WrappedOnDemandX509CertificateEx.fromX509Certificate(mgr, container.getCert(), container.getWrappedKeyData());
            return retVal;
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
            localKeyStore.load(bais, "".toCharArray());
            Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias 
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                Key key = localKeyStore.getKey(alias, "".toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
                } else
                    retVal = cert;
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (retVal == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
        }
        bais.close();
        // look in the keystore manager to check if they private key is store in the token
        if (mgr != null && !(retVal instanceof X509CertificateEx)) {
            // make sure this a mutable manager
            if (mgr instanceof MutableKeyStoreProtectionManager) {
                try {
                    final KeyStore ks = ((MutableKeyStoreProtectionManager) mgr).getKS();
                    // check to see if this certificate exists in the key store
                    final String alias = ks.getCertificateAlias(retVal);
                    if (!StringUtils.isEmpty(alias)) {
                        // get the private key if it exits
                        final PrivateKey pKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
                        if (pKey != null)
                            retVal = X509CertificateEx.fromX509Certificate(retVal, pKey);
                    }
                } catch (Exception e) {
                    LOGGER.warn("Could not retrieve the private key from the PKCS11 token: " + e.getMessage(), e);
                }
            }
        }
    } catch (Exception e) {
        throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) WrappedOnDemandX509CertificateEx(org.nhindirect.stagent.cert.WrappedOnDemandX509CertificateEx) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) NHINDException(org.nhindirect.stagent.NHINDException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException)

Example 65 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class PKCS11Commands method exportPrivateKey.

@Command(name = "ExportPrivateKey", usage = EXPORT_PRIVATE_KEY)
public void exportPrivateKey(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String wrapperAlias = StringArrayUtil.getRequiredValue(args, 1);
    final String file = StringArrayUtil.getOptionalValue(args, 2, alias + "-privKey.der");
    try {
        final KeyStore ks = mgr.getKS();
        // get the wrapper key
        final Key wrapperKey = mgr.getKey(wrapperAlias);
        if (wrapperKey == null) {
            System.out.println("Wrapper key with name " + wrapperKey + " does not exist.");
            return;
        }
        if (!ks.containsAlias(alias)) {
            System.out.println("Private key with name " + alias + " does not exist.");
            return;
        }
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Key name " + alias + " does not contain a private key");
            return;
        }
        // the algorithm used to wrap the key depends on the key type
        Cipher myWrapper = null;
        if (wrapperKey.getAlgorithm().startsWith("AES")) {
            myWrapper = Cipher.getInstance("AES/CBC/PKCS5Padding", ks.getProvider().getName());
            AlgorithmParameters mAlgParams = null;
            try {
                mAlgParams = AlgorithmParameters.getInstance("IV", ks.getProvider().getName());
                mAlgParams.init(new IvParameterSpec(AbstractPKCS11TokenKeyStoreProtectionManager.IV_BYTES));
            } catch (Exception e) {
            }
            if (mAlgParams == null)
                myWrapper.init(Cipher.WRAP_MODE, wrapperKey, new IvParameterSpec(AbstractPKCS11TokenKeyStoreProtectionManager.IV_BYTES));
            else
                myWrapper.init(Cipher.WRAP_MODE, wrapperKey, mAlgParams);
        } else if (wrapperKey.getAlgorithm().startsWith("RSA")) {
            myWrapper = Cipher.getInstance("RSA/ECB/NoPadding", ks.getProvider().getName());
            myWrapper.init(Cipher.WRAP_MODE, wrapperKey);
        }
        byte[] wrappedKey = null;
        try {
            wrappedKey = myWrapper.wrap(privKey);
        } catch (Exception e) {
            System.out.println("Private key with name " + alias + " could not be extracted.  Your hardware may not allow exporting of private keys or " + "attributes on the key may not allow the key to be exported.  \r\nError message: " + e.getMessage());
            e.printStackTrace();
            return;
        }
        final File fl = new File(file);
        FileUtils.writeByteArrayToFile(fl, wrappedKey);
        System.out.println("Wrapped private key written to file " + fl.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to export private key: " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyStore(java.security.KeyStore) File(java.io.File) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) AlgorithmParameters(java.security.AlgorithmParameters) Command(org.nhindirect.common.tooling.Command)

Aggregations

Key (java.security.Key)302 PrivateKey (java.security.PrivateKey)112 SecretKey (javax.crypto.SecretKey)83 KeyStore (java.security.KeyStore)64 PublicKey (java.security.PublicKey)62 Cipher (javax.crypto.Cipher)60 X509Certificate (java.security.cert.X509Certificate)57 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)50 Test (org.junit.Test)44 IOException (java.io.IOException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 SecretKeySpec (javax.crypto.spec.SecretKeySpec)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)32 KeyGenerator (javax.crypto.KeyGenerator)32 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 KeyStoreException (java.security.KeyStoreException)22 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)21