Example usage for java.security KeyFactory generatePrivate

List of usage examples for java.security KeyFactory generatePrivate

Introduction

In this page you can find the example usage for java.security KeyFactory generatePrivate.

Prototype

public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a private key object from the provided key specification (key material).

Usage

From source file:org.ejbca.ui.cli.CMPKeyUpdateStressTest.java

@Override
protected void execute(String[] args) {
    final String hostName;
    final String keystoreFile;
    final String keystorePassword;
    final String certNameInKeystore;
    final int numberOfThreads;
    final int waitTime;
    final int port;
    final String urlPath;
    final String resultFilePrefix;
    if (args.length < 5) {
        System.out.println(args[0]
                + " <host name> <keystore (p12)> <keystore password> <friendlyname in keystore> [<number of threads>] [<wait time (ms) between each thread is started>] [<port>] [<URL path of servlet. use 'null' to get EJBCA (not proxy) default>] [<certificate file prefix. set this if you want all received certificates stored on files>]");
        System.out.println(/*from ww w. ja v  a 2s. c o m*/
                "EJBCA build configuration requirements: cmp.operationmode=normal, cmp.allowraverifypopo=true, cmp.allowautomatickeyupdate=true, cmp.allowupdatewithsamekey=true");
        //            System.out.println("EJBCA build configuration optional: cmp.ra.certificateprofile=KeyId cmp.ra.endentityprofile=KeyId (used when the KeyId argument should be used as profile name).");
        System.out.println(
                "Ejbca expects the following: There exists an end entity with a generated certificate. The end entity's certificate and its private key are stored in the keystore used "
                        + "in the commandline. The end entity's certificate's 'friendly name' in the keystore is the one used in the command line. Such keystore can be obtained, for example, by specifying "
                        + "the token to be 'P12' when creating the end entity and then download the keystore by choosing 'create keystore' from the public web");
        return;
    }
    hostName = args[1];
    keystoreFile = args[2];
    keystorePassword = args[3];
    certNameInKeystore = args[4];
    numberOfThreads = args.length > 5 ? Integer.parseInt(args[5].trim()) : 1;
    waitTime = args.length > 6 ? Integer.parseInt(args[6].trim()) : 0;
    port = args.length > 7 ? Integer.parseInt(args[7].trim()) : 8080;
    //        isHttp = true;
    urlPath = args.length > 8 && args[8].toLowerCase().indexOf("null") < 0 ? args[8].trim() : null;
    resultFilePrefix = args.length > 9 ? args[9].trim() : null;

    CryptoProviderTools.installBCProviderIfNotAvailable();

    Certificate cacert = null;
    Certificate extracert = null;
    PrivateKey oldCertKey = null;

    FileInputStream file_inputstream;
    try {
        file_inputstream = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, keystorePassword.toCharArray());
        Key key = keyStore.getKey(certNameInKeystore, keystorePassword.toCharArray());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        oldCertKey = keyFactory.generatePrivate(keySpec);
        //extracert = keyStore.getCertificate(certNameInKeystore);

        Certificate[] certs = keyStore.getCertificateChain(certNameInKeystore);
        extracert = certs[0];
        cacert = certs[1];

    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
        System.exit(-1);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    try {
        new StressTest(hostName, port, numberOfThreads, waitTime, urlPath, resultFilePrefix, keystorePassword,
                cacert, oldCertKey, extracert);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.jmeter.protocol.oauth.sampler.PrivateKeyReader.java

/**
 * Read the PEM file and return the key//  w  w w.ja v a 2s.  co m
 * 
 * @return
 * @throws IOException
 */
private PrivateKey read() throws IOException {

    String line;

    KeyFactory factory;
    try {
        factory = KeyFactory.getInstance("RSA"); //$NON-NLS-1$
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("JCE error: " + e.getMessage()); //$NON-NLS-1$
    }

    while ((line = server.readLine(fileName)) != null) {
        if (line.indexOf(P1_BEGIN_MARKER) != -1) {
            byte[] keyBytes = readKeyMaterial(P1_END_MARKER);
            RSAPrivateCrtKeySpec keySpec = getRSAKeySpec(keyBytes);

            try {
                return factory.generatePrivate(keySpec);
            } catch (InvalidKeySpecException e) {
                throw new IOException("Invalid PKCS#1 PEM file: " + e.getMessage()); //$NON-NLS-1$
            }
        }

        if (line.indexOf(P8_BEGIN_MARKER) != -1) {
            byte[] keyBytes = readKeyMaterial(P8_END_MARKER);
            EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

            try {
                return factory.generatePrivate(keySpec);
            } catch (InvalidKeySpecException e) {
                throw new IOException("Invalid PKCS#8 PEM file: " + e.getMessage()); //$NON-NLS-1$
            }
        }

    }

    throw new IOException("Invalid PEM file: no begin marker"); //$NON-NLS-1$
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

void importPrivateKey(String keyAlias, String keyPassword, InputStream fl, InputStream certstream)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException,
        KeyStoreException {/* w w  w  .  j a  v  a  2 s  . com*/
    KeyInfoManager keyInfoManager = null;

    writeLock.lock();
    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        // loading Key
        byte[] keyBytes = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(keyBytes, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey key = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        @SuppressWarnings("rawtypes")
        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        certs = (Certificate[]) c.toArray(new Certificate[0]);

        // storing keystore
        ks.setKeyEntry(keyAlias, key, keyPassword.toCharArray(), certs);

        if (logger.isDebugEnabled()) {
            logger.debug("Key and certificate stored.");
            logger.debug("Alias:" + keyAlias);
        }

        ks.store(new FileOutputStream(getKeyStoreParameters().getLocation()), keyPassword.toCharArray());
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }

        writeLock.unlock();
    }
}

From source file:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;//from   w ww . java 2  s.c  o m
    SpfeURL = "https://" + spfeAddr + "/";
    // Setting up client certificate and key

    X509Certificate[] chain = { cert };

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(key);

    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain);

    //This adds no security but Java requires to password-protect the key
    byte[] password_bytes = new byte[16];
    (new java.security.SecureRandom()).nextBytes(password_bytes);
    // String password = (new BASE64Encoder()).encode(password_bytes);
    String password = (new Base64()).encodeToString(password_bytes);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);

    keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray()));
    keyManagerFactory.init(keyStore, password.toCharArray());

    SPFEContext = SSLContext.getInstance("TLS");

    // Making rootCA certificate
    InputStream is = null;
    CertificateFactory cf;
    X509Certificate rootCA = null;
    try {
        is = new ByteArrayInputStream(WWPassCA_DER);
        cf = CertificateFactory.getInstance("X.509");
        rootCA = (X509Certificate) cf.generateCertificate(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    //Creating TrustManager for this CA
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setCertificateEntry("WWPass Root CA", rootCA);

    trustManagerFactory.init(ks);

    SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new java.security.SecureRandom());
}

From source file:org.panbox.core.pairing.PAKCorePairingRequester.java

@Override
public void runOperation(Cipher cipher, SecretKeySpec spec) throws Exception {
    logger.debug("PAKCorePairingHandler : runOperation : Started to request pairing");

    KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.ASYMMETRIC_ALGORITHM_ALGO_ONLY);
    CertificateFactory certificateFactory = CertificateFactory.getInstance(KeyConstants.CERTIFICATE_ENCODING);

    cipher.init(Cipher.DECRYPT_MODE, spec);

    String base64received;//  w  w w.j  ava2  s  .com

    base64received = (String) dataInputStream.readObject();
    logger.debug("PAKCorePairingRequester : runOperation : Received pairingType: " + base64received);
    byte[] encType = Base64.decodeBase64(base64received);
    String strType = new String(cipher.doFinal(encType));
    type = PairingType.valueOf(strType);

    switch (type) {
    case MASTER:
        logger.info("PAKCorePairingRequester : runOperation : This device will be paired as master device!");

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received email: " + base64received);
        eMail = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received firstname: " + base64received);
        firstName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received lastname: " + base64received);
        lastName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received devicename: " + base64received);
        deviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received keyPassword: " + base64received);

        keyPassword = Utils.toChars(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerKeyEnc: " + base64received);
        PKCS8EncodedKeySpec ownerKeyEncSpec = new PKCS8EncodedKeySpec(
                cipher.doFinal(Base64.decodeBase64(base64received)));
        PrivateKey pKey = keyFactory.generatePrivate(ownerKeyEncSpec);
        ownerKeyEnc = CryptCore.privateKeyToKeyPair(pKey);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerKeySign: " + base64received);
        PKCS8EncodedKeySpec ownerKeySignSpec = new PKCS8EncodedKeySpec(
                cipher.doFinal(Base64.decodeBase64(base64received)));
        pKey = keyFactory.generatePrivate(ownerKeySignSpec);
        ownerKeySign = CryptCore.privateKeyToKeyPair(pKey);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received numOfDevices: " + base64received);

        int numOfDevices = Integer.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64received))));

        knownDevices = new HashMap<String, X509Certificate>();

        for (int i = 0; i < numOfDevices; ++i) {
            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device name (" + i + "): "
                    + base64received);

            String knownDeviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device certificate (" + i + "): "
                    + base64received);

            InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
            X509Certificate knownDeviceCert = (X509Certificate) certificateFactory.generateCertificate(is);

            knownDevices.put(knownDeviceName, knownDeviceCert);
            logger.debug("PAKCorePairingRequester : runOperation : Added device (" + i + "): " + knownDeviceName
                    + ": " + knownDeviceCert);
        }

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received contacts: " + base64received);

        InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));

        knownContacts = Ezvcard.parse(is).all();

        // --- SEND Device Type and Key ---

        cipher.init(Cipher.ENCRYPT_MODE, spec);

        byte[] encDevType = cipher.doFinal(devType.toString().getBytes());

        devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(),
                new PairingIPersonDummy(eMail, firstName, lastName));

        byte[] encDevCert = cipher.doFinal(devCert.getEncoded());

        String base64encDevType = Base64.encodeBase64String(encDevType);
        String base64encDevCert = Base64.encodeBase64String(encDevCert);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicetype: " + base64encDevType);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicecert: " + base64encDevCert);

        dataOutputStream.writeObject(base64encDevType);
        dataOutputStream.flush();
        dataOutputStream.writeObject(base64encDevCert);
        dataOutputStream.flush();

        break;
    case SLAVE:
        logger.info("PAKCorePairingRequester : runOperation : This device will be paired as slave device!");

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received email: " + base64received);
        eMail = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received firstname: " + base64received);
        firstName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received lastname: " + base64received);
        lastName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received devicename: " + base64received);
        deviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerCertEnc: " + base64received);
        is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
        ownerCertEnc = (X509Certificate) certificateFactory.generateCertificate(is);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerCertSign: " + base64received);
        is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
        ownerCertSign = (X509Certificate) certificateFactory.generateCertificate(is);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received numOfDevices: " + base64received);

        numOfDevices = Integer.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64received))));

        knownDevices = new HashMap<String, X509Certificate>();

        for (int i = 0; i < numOfDevices; ++i) {
            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device name (" + i + "): "
                    + base64received);

            String knownDeviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device certificate (" + i + "): "
                    + base64received);

            is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
            X509Certificate knownDeviceCert = (X509Certificate) certificateFactory.generateCertificate(is);

            knownDevices.put(knownDeviceName, knownDeviceCert);
            logger.debug("PAKCorePairingRequester : runOperation : Added device (" + i + "): " + knownDeviceName
                    + ": " + knownDeviceCert);
        }

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received contacts: " + base64received);

        is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));

        knownContacts = Ezvcard.parse(is).all();

        // --- SEND Device Type and Key ---

        cipher.init(Cipher.ENCRYPT_MODE, spec);

        encDevType = cipher.doFinal(devType.toString().getBytes());

        devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(),
                new PairingIPersonDummy(eMail, firstName, lastName));

        encDevCert = cipher.doFinal(devCert.getEncoded());

        base64encDevType = Base64.encodeBase64String(encDevType);
        base64encDevCert = Base64.encodeBase64String(encDevCert);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicetype: " + base64encDevType);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicecert: " + base64encDevCert);

        dataOutputStream.writeObject(base64encDevType);
        dataOutputStream.flush();
        dataOutputStream.writeObject(base64encDevCert);
        dataOutputStream.flush();
        break;
    default:
        logger.error("PAKCorePairingRequester : runOperation : Unknown pairing type!");
        break;
    }

    logger.debug(
            "PAKCorePairingRequester : runOperation : Pairing finished. Will wait for session to be closed!.");

    try {
        dataInputStream.readBoolean();
    } catch (Exception ex) {
        // Connection has been closed successfully! Pairing done :)
    }
}