Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *//* w  ww  .j a v a  2 s .c o  m*/
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}

From source file:mitm.common.security.ca.handlers.comodo.ComodoCertificateRequestHandler.java

private void handleWaitingForRequest(CertificateRequest request, DataWrapper data)
        throws HierarchicalPropertiesException, CAException {
    logger.debug("handling state: " + data.getState());

    try {//ww  w.  ja v  a  2s  .  c  om
        ComodoSettings settings = settingsProvider.getSettings();

        assertEnabled(settings);

        KeyPair keyPair = request.getKeyPair(encryptor);

        if (keyPair == null) {
            keyPair = generateKeyPair(request.getKeyLength());
        }

        /* 
         * We must store the generated keypair.
         */
        request.setKeyPair(keyPair, encryptor);

        PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
                X500PrincipalUtils.toX500Name(request.getSubject()),
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

        PKCS10CertificationRequest pkcs10 = requestBuilder
                .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

        String base64PKCS10 = MiscStringUtils.toAsciiString(Base64.encodeBase64(pkcs10.getEncoded()));

        ApplyCustomClientCert applier = new ApplyCustomClientCert(connectionSettings);

        applier.setAP(settings.getAP());
        applier.setCACertificateID(settings.getCACertificateID());
        applier.setDays(request.getValidity());
        applier.setPkcs10(base64PKCS10);

        boolean success = applier.apply();

        if (success) {
            logger.info("Certificate request for user " + request.getEmail() + " was sent. Order number: "
                    + applier.getOrderNumber());

            data.setOrderNumber(applier.getOrderNumber());

            data.setState(settings.isAutoAuthorize() ? ComodoRequestState.WAITING_FOR_AUTHORIZATION
                    : ComodoRequestState.WAITING_FOR_RETRIEVAL);

            request.setInfo("Order number: " + applier.getOrderNumber());
        } else {
            String errorMessage = "Error requesting certificate. Message: " + applier.getErrorMessage();

            logger.warn(errorMessage);

            request.setLastMessage(MiscStringUtils.restrictLength(errorMessage, 1024));
        }
    } catch (OperatorCreationException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (NoSuchProviderException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (KeyEncoderException e) {
        throw new CAException("Error encrypting the key pair", e);
    } catch (CustomClientCertException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (IOException e) {
        throw new CAException("Error requesting a certificate", e);
    }
}

From source file:org.signserver.module.xades.validator.XAdESValidator2UnitTest.java

/**
 * Setting up key-pairs, mocked crypto tokens, certificates and CRLs used
 * by the tests.//from  w  ww  . j  a va 2s. co  m
 */
@BeforeClass
public static void setUpClass() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    JcaX509CertificateConverter conv = new JcaX509CertificateConverter();

    // Root CA, sub CA
    rootcaCRLFile = File.createTempFile("xadestest-", "-rootca.crl");
    LOG.debug("rootcaCRLFile: " + rootcaCRLFile);
    subca1CRLFile = File.createTempFile("xadestest-", "-subca.crl");
    LOG.debug("subcaCRLFile: " + subca1CRLFile);
    rootcaKeyPair = CryptoUtils.generateRSA(1024);
    anotherKeyPair = CryptoUtils.generateRSA(1024);
    rootcaCert = new CertBuilder().setSelfSignKeyPair(rootcaKeyPair).setSubject("CN=Root, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.keyUsage, false,
                    new X509KeyUsage(
                            X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign | X509KeyUsage.digitalSignature)))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(true))).build();
    final KeyPair subca1KeyPair = CryptoUtils.generateRSA(1024);
    subca1Cert = new CertBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).setSubjectPublicKey(subca1KeyPair.getPublic())
            .addCDPURI(rootcaCRLFile.toURI().toURL().toExternalForm())
            .setSubject("CN=Sub 1, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.keyUsage, false,
                    new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(true))).build();
    subca2KeyPair = CryptoUtils.generateRSA(1024);
    subca2Cert = new CertBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).setSubjectPublicKey(subca2KeyPair.getPublic())
            .setSubject("CN=Sub 2, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.keyUsage, false,
                    new X509KeyUsage(
                            X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign | X509KeyUsage.digitalSignature)))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(true)))
            .addExtension(new CertExt(Extension.authorityInfoAccess, false,
                    new AuthorityInformationAccess(AccessDescription.id_ad_ocsp,
                            new GeneralName(GeneralName.uniformResourceIdentifier, "http://ocsp.example.com"))))
            .build();

    // Signer 1 is issued directly by the root CA
    final KeyPair signer1KeyPair = CryptoUtils.generateRSA(1024);
    final X509CertificateHolder signer1Cert = new CertBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).setSubjectPublicKey(signer1KeyPair.getPublic())
            .setSubject("CN=Signer 1, O=XAdES Test, C=SE")
            .addCDPURI(rootcaCRLFile.toURI().toURL().toExternalForm())
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false))).build();
    final List<Certificate> chain1 = Arrays.<Certificate>asList(conv.getCertificate(signer1Cert),
            conv.getCertificate(rootcaCert));
    token1 = new MockedCryptoToken(signer1KeyPair.getPrivate(), signer1KeyPair.getPublic(),
            conv.getCertificate(signer1Cert), chain1, "BC");
    LOG.debug("Chain 1: \n" + new String(CertTools.getPEMFromCerts(chain1), "ASCII") + "\n");

    // Sign a document by signer 1
    XAdESSigner instance = new MockedXAdESSigner(token1);
    WorkerConfig config = new WorkerConfig();
    instance.init(4712, config, null, null);
    RequestContext requestContext = new RequestContext();
    requestContext.put(RequestContext.TRANSACTION_ID, "0000-201-1");
    GenericSignRequest request = new GenericSignRequest(201, "<test201/>".getBytes("UTF-8"));
    GenericSignResponse response = (GenericSignResponse) instance.processData(request, requestContext);
    byte[] data = response.getProcessedData();
    signedXml1 = new String(data);
    LOG.debug("Signed document by signer 1:\n\n" + signedXml1 + "\n");

    // Signer 2 is issued by the sub CA
    final KeyPair signer2KeyPair = CryptoUtils.generateRSA(1024);
    final X509CertificateHolder signer2Cert = new CertBuilder().setIssuerPrivateKey(subca1KeyPair.getPrivate())
            .setIssuer(subca1Cert.getSubject()).setSubjectPublicKey(signer2KeyPair.getPublic())
            .setSubject("CN=Signer 2, O=XAdES Test, C=SE")
            .addCDPURI(subca1CRLFile.toURI().toURL().toExternalForm())
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false))).build();
    final List<Certificate> chain2 = Arrays.<Certificate>asList(conv.getCertificate(signer2Cert),
            conv.getCertificate(subca1Cert), conv.getCertificate(rootcaCert));
    token2 = new MockedCryptoToken(signer2KeyPair.getPrivate(), signer2KeyPair.getPublic(),
            conv.getCertificate(signer2Cert), chain2, "BC");
    LOG.debug("Chain 2: \n" + new String(CertTools.getPEMFromCerts(chain2)) + "\n");

    // Sign a document by signer 2
    instance = new MockedXAdESSigner(token2);
    config = new WorkerConfig();
    instance.init(4713, config, null, null);
    requestContext = new RequestContext();
    requestContext.put(RequestContext.TRANSACTION_ID, "0000-202-1");
    request = new GenericSignRequest(202, "<test202/>".getBytes("UTF-8"));
    response = (GenericSignResponse) instance.processData(request, requestContext);
    data = response.getProcessedData();
    signedXml2 = new String(data);
    LOG.debug("Signed document by signer 2:\n\n" + signedXml2 + "\n");

    // CRL with all active (empty CRL)
    rootcaCRLEmpty = new CRLBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).build();
    subca1CRLEmpty = new CRLBuilder().setIssuerPrivateKey(subca1KeyPair.getPrivate())
            .setIssuer(subca1Cert.getSubject()).build();
    rootcaCRLSubCAAndSigner1Revoked = new CRLBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject())
            .addCRLEntry(subca1Cert.getSerialNumber(), new Date(), CRLReason.keyCompromise)
            .addCRLEntry(signer1Cert.getSerialNumber(), new Date(), CRLReason.keyCompromise).build();
    subca1CRLSigner2Revoked = new CRLBuilder().setIssuerPrivateKey(subca1KeyPair.getPrivate())
            .setIssuer(subca1Cert.getSubject())
            .addCRLEntry(signer2Cert.getSerialNumber(), new Date(), CRLReason.keyCompromise).build();
    otherCRL = new CRLBuilder().setIssuer(subca1Cert.getSubject()) // Setting Sub CA DN all though an other key will be used
            .build();

    // signer 3, issued by the root CA with an OCSP authority information access in the signer cert
    final KeyPair signer3KeyPair = CryptoUtils.generateRSA(1024);
    signer3Cert = new CertBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).setSubjectPublicKey(signer3KeyPair.getPublic())
            .setSubject("CN=Signer 3, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.authorityInfoAccess, false,
                    new AuthorityInformationAccess(AccessDescription.id_ad_ocsp,
                            new GeneralName(GeneralName.uniformResourceIdentifier, "http://ocsp.example.com"))))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false))).build();
    final List<Certificate> chain3 = Arrays.<Certificate>asList(conv.getCertificate(signer3Cert),
            conv.getCertificate(rootcaCert));
    token3 = new MockedCryptoToken(signer3KeyPair.getPrivate(), signer3KeyPair.getPublic(),
            conv.getCertificate(signer3Cert), chain3, "BC");
    LOG.debug("Chain 3: \n" + new String(CertTools.getPEMFromCerts(chain3)) + "\n");

    // signer 4, issued by the sub CA2 with an OCSP authority information access in the signer cert
    final KeyPair signer4KeyPair = CryptoUtils.generateRSA(1024);
    signer4Cert = new CertBuilder().setIssuerPrivateKey(subca2KeyPair.getPrivate())
            .setIssuer(subca2Cert.getSubject()).setSubjectPublicKey(signer4KeyPair.getPublic())
            .setSubject("CN=Signer 4, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.authorityInfoAccess, false,
                    new AuthorityInformationAccess(AccessDescription.id_ad_ocsp,
                            new GeneralName(GeneralName.uniformResourceIdentifier, "http://ocsp.example.com"))))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false))).build();
    final List<Certificate> chain4 = Arrays.<Certificate>asList(conv.getCertificate(signer4Cert),
            conv.getCertificate(subca2Cert), conv.getCertificate(rootcaCert));
    token4 = new MockedCryptoToken(signer4KeyPair.getPrivate(), signer4KeyPair.getPublic(),
            conv.getCertificate(signer4Cert), chain4, "BC");
    LOG.debug("Chain 4: \n" + new String(CertTools.getPEMFromCerts(chain4)) + "\n");

    // ocspSigner 1, OCSP responder issued by the root CA with an ocsp-nocheck in the signer cert
    ocspSigner1KeyPair = CryptoUtils.generateRSA(1024);
    ocspSigner1Cert = new CertBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).setSubjectPublicKey(ocspSigner1KeyPair.getPublic())
            .setSubject("CN=OCSP Responder 1, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false)))
            .addExtension(new CertExt(Extension.extendedKeyUsage, false,
                    new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning)))
            .addExtension(new CertExt(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, new DERNull()))
            .build();

    // ocspSigner 2, OCSP responder issued by the sub CA2 with an ocsp-nocheck in the signer cert
    ocspSigner2KeyPair = CryptoUtils.generateRSA(1024);
    ocspSigner2Cert = new CertBuilder().setIssuerPrivateKey(subca2KeyPair.getPrivate())
            .setIssuer(subca2Cert.getSubject()).setSubjectPublicKey(ocspSigner2KeyPair.getPublic())
            .setSubject("CN=OCSP Responder 2, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false)))
            .addExtension(new CertExt(Extension.extendedKeyUsage, false,
                    new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning)))
            .addExtension(new CertExt(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, new DERNull()))
            .build();

    // Sign a document by signer 3
    instance = new MockedXAdESSigner(token3);
    config = new WorkerConfig();
    instance.init(4714, config, null, null);
    requestContext = new RequestContext();
    requestContext.put(RequestContext.TRANSACTION_ID, "0000-203-1");
    request = new GenericSignRequest(202, "<test203/>".getBytes("UTF-8"));
    response = (GenericSignResponse) instance.processData(request, requestContext);
    data = response.getProcessedData();
    signedXml3 = new String(data);
    LOG.debug("Signed document by signer 3:\n\n" + signedXml3 + "\n");

    // Sign a document by signer 4
    instance = new MockedXAdESSigner(token4);
    config = new WorkerConfig();
    instance.init(4715, config, null, null);
    requestContext = new RequestContext();
    requestContext.put(RequestContext.TRANSACTION_ID, "0000-204-1");
    request = new GenericSignRequest(203, "<test204/>".getBytes("UTF-8"));
    response = (GenericSignResponse) instance.processData(request, requestContext);
    data = response.getProcessedData();
    signedXml4 = new String(data);
    LOG.debug("Signed document by signer 4:\n\n" + signedXml4 + "\n");

    // Signer 5 is issued directly by the root CA
    final KeyPair signer5KeyPair = CryptoUtils.generateRSA(1024);
    signer5Cert = new CertBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).setSubjectPublicKey(signer5KeyPair.getPublic())
            .setSubject("CN=Signer 5, O=XAdES Test, C=SE")
            .addCDPURI(rootcaCRLFile.toURI().toURL().toExternalForm())
            .addExtension(new CertExt(Extension.authorityInfoAccess, false,
                    new AuthorityInformationAccess(AccessDescription.id_ad_ocsp,
                            new GeneralName(GeneralName.uniformResourceIdentifier, "http://ocsp.example.com"))))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false))).build();
    final List<Certificate> chain5 = Arrays.<Certificate>asList(conv.getCertificate(signer5Cert),
            conv.getCertificate(rootcaCert));
    token5 = new MockedCryptoToken(signer5KeyPair.getPrivate(), signer5KeyPair.getPublic(),
            conv.getCertificate(signer1Cert), chain5, "BC");
    LOG.debug("Chain 5: \n" + new String(CertTools.getPEMFromCerts(chain5)) + "\n");

    // Sign a document by signer 5
    instance = new MockedXAdESSigner(token5);
    config = new WorkerConfig();
    instance.init(4712, config, null, null);
    requestContext = new RequestContext();
    requestContext.put(RequestContext.TRANSACTION_ID, "0000-205-1");
    request = new GenericSignRequest(205, "<test205/>".getBytes("UTF-8"));
    response = (GenericSignResponse) instance.processData(request, requestContext);
    data = response.getProcessedData();
    signedXml5 = new String(data);
    LOG.debug("Signed document by signer 5:\n\n" + signedXml5 + "\n");

    // CRL with signer 5 revoked
    rootcaCRLSigner5Revoked = new CRLBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject())
            .addCRLEntry(signer5Cert.getSerialNumber(), new Date(), CRLReason.keyCompromise).build();
}

From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java

/**
 * 1- Sends a revocation request signed by RA2Admin to RA1. Expected: Fail
 * 2- Sends a revocation request signed by RA1Admin to RA1. Expected: Success
 * //from   w w  w . ja v a2 s  . com
 * @throws Exception
 */
@Test
public void test03RevocationRequest() throws Exception {

    String username = "ra1testuser";
    String fingerprintCert = null;
    try {

        // Issue a cert by CA1
        String userDN = "CN=" + username;
        createUser(username, userDN, "foo123", true, ca1.getCAId(),
                endEntityProfileSession.getEndEntityProfileId(EEP1),
                certProfileSession.getCertificateProfileId(CP1));
        KeyPair userkeys = KeyTools.genKeys("1024", "RSA");
        Certificate cert = signSession.createCertificate(ADMIN, username, "foo123",
                new PublicKeyWrapper(userkeys.getPublic()));
        assertNotNull("No certificate to revoke.", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genRevReq(ca1.getSubjectDN(), new X500Name(userDN), CertTools.getSerialNumber(cert),
                ca1.getCACertificate(), nonce, transid, false, pAlg, null);
        assertNotNull("Generating revocation request failed.", msg);

        // Sign the revocation request with RA2 Admin
        CMPCertificate[] extraCert = getCMPCert(ra2admincert);
        PKIMessage protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert,
                ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed.", protectedMsg);

        // Send the CMP request to RA1. Expected: Fail
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(protectedMsg);
        byte[] ba = bao.toByteArray();
        byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, null);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        final PKIMessage respObject;
        try {
            respObject = PKIMessage.getInstance(asn1InputStream.readObject());
        } finally {
            asn1InputStream.close();
        }
        assertNotNull("Reading CMP response failed.", respObject);
        PKIBody body = respObject.getBody();
        assertEquals(PKIBody.TYPE_ERROR, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
        assertEquals(expectedErrMsg, errMsg);

        // Sign the revocation request with RA1 Admin
        extraCert = getCMPCert(ra1admincert);
        protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed.", protectedMsg);

        // Send the CMP request to RA1. Expected: Success
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(protectedMsg);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200, RA1_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(ca1.getSubjectDN(), CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);
    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, username, ReasonFlags.unused);
    }
}

From source file:org.hyperledger.fabric.sdk.MemberServicesImpl.java

/**
  * Enroll the member with member service
  * @param req Enrollment request with the following fields: name, enrollmentSecret
  * @return enrollment//from  w  w  w .j a  va  2s .co  m
  */
public Enrollment enroll(EnrollmentRequest req) throws EnrollmentException {
    logger.debug(String.format("[MemberServicesImpl.enroll] [%s]", req));
    if (StringUtil.isNullOrEmpty(req.getEnrollmentID())) {
        throw new RuntimeException("req.enrollmentID is not set");
    }
    if (StringUtil.isNullOrEmpty(req.getEnrollmentSecret())) {
        throw new RuntimeException("req.enrollmentSecret is not set");
    }

    logger.debug("[MemberServicesImpl.enroll] Generating keys...");

    try {
        // generate ECDSA keys: signing and encryption keys
        KeyPair signingKeyPair = cryptoPrimitives.ecdsaKeyGen();
        KeyPair encryptionKeyPair = cryptoPrimitives.ecdsaKeyGen();

        logger.debug("[MemberServicesImpl.enroll] Generating keys...done!");

        // create the proto message
        ECertCreateReq.Builder eCertCreateRequestBuilder = ECertCreateReq.newBuilder()
                .setTs(Timestamp.newBuilder().setSeconds(new java.util.Date().getTime()))
                .setId(Identity.newBuilder().setId(req.getEnrollmentID()).build())
                .setTok(Token.newBuilder().setTok(ByteString.copyFrom(req.getEnrollmentSecret(), "UTF8")))
                .setSign(PublicKey.newBuilder()
                        .setKey(ByteString.copyFrom(signingKeyPair.getPublic().getEncoded()))
                        .setType(CryptoType.ECDSA))
                .setEnc(PublicKey.newBuilder()
                        .setKey(ByteString.copyFrom(encryptionKeyPair.getPublic().getEncoded()))
                        .setType(CryptoType.ECDSA));

        ECertCreateResp eCertCreateResp = this.ecapClient
                .createCertificatePair(eCertCreateRequestBuilder.build());

        byte[] cipherText = eCertCreateResp.getTok().getTok().toByteArray();
        byte[] decryptedTokBytes = cryptoPrimitives.eciesDecrypt(encryptionKeyPair, cipherText);

        eCertCreateRequestBuilder = eCertCreateRequestBuilder
                .setTok(Token.newBuilder().setTok(ByteString.copyFrom(decryptedTokBytes)));

        ECertCreateReq certReq = eCertCreateRequestBuilder.buildPartial();
        byte[] buf = certReq.toByteArray();

        BigInteger[] sig = cryptoPrimitives.ecdsaSign(signingKeyPair.getPrivate(), buf);
        Signature protoSig = Signature.newBuilder().setType(CryptoType.ECDSA)
                .setR(ByteString.copyFrom(sig[0].toString().getBytes()))
                .setS(ByteString.copyFrom(sig[1].toString().getBytes())).build();
        eCertCreateRequestBuilder = eCertCreateRequestBuilder.setSig(protoSig);

        eCertCreateResp = ecapClient.createCertificatePair(eCertCreateRequestBuilder.build());

        logger.debug("[MemberServicesImpl.enroll] eCertCreateResp : [%s]" + eCertCreateResp.toByteString());

        Enrollment enrollment = new Enrollment();
        enrollment.setKey(Hex.toHexString(signingKeyPair.getPrivate().getEncoded()));
        enrollment.setCert(Hex.toHexString(eCertCreateResp.getCerts().getSign().toByteArray()));
        enrollment.setChainKey(Hex.toHexString(eCertCreateResp.getPkchain().toByteArray()));
        enrollment.setQueryStateKey(Hex.toHexString(cryptoPrimitives.generateNonce()));

        logger.debug("Enrolled successfully: " + enrollment);
        return enrollment;

    } catch (Exception e) {
        throw new EnrollmentException("Failed to enroll user", e);
    }
}

From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java

private static MockedCryptoToken generateToken(final KeyType keyType) throws Exception {
    final KeyPair signerKeyPair;
    final String signatureAlgorithm;

    switch (keyType) {
    case RSA://from  ww w .  j  a  va 2  s.  c o  m
        signerKeyPair = CryptoUtils.generateRSA(1024);
        signatureAlgorithm = "SHA1withRSA";
        break;
    case DSA:
        signerKeyPair = CryptoUtils.generateDSA(1024);
        signatureAlgorithm = "SHA1withDSA";
        break;
    case ECDSA:
        signerKeyPair = CryptoUtils.generateEcCurve("prime256v1");
        signatureAlgorithm = "SHA1withECDSA";
        break;
    default:
        throw new NoSuchAlgorithmException("Invalid key algorithm");
    }

    final Certificate[] certChain = new Certificate[] {
            new JcaX509CertificateConverter().getCertificate(new CertBuilder().setSelfSignKeyPair(signerKeyPair)
                    .setNotBefore(new Date(MockedTimeStampTokenProvider.TIMESTAMP))
                    .setSignatureAlgorithm(signatureAlgorithm).build()) };
    final Certificate signerCertificate = certChain[0];
    return new MockedCryptoToken(signerKeyPair.getPrivate(), signerKeyPair.getPublic(), signerCertificate,
            Arrays.asList(certChain), "BC");

}

From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString());
        log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo);
    }//from  w ww . j  a v  a 2 s  .  co m

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();
    KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    myCertTemplate.setSubject(userDN);

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (includePopo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg);
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);

        DERBitString bs = new DERBitString(sig.sign());

        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(""));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

/**
 * generateCertificationRequest/*www.ja  va  2s.  c om*/
 *
 * @param subject The subject to be added to the certificate
 * @param pair    Public private key pair
 * @return PKCS10CertificationRequest Certificate Signing Request.
 * @throws OperatorCreationException
 */

public String generateCertificationRequest(String subject, KeyPair pair) throws InvalidArgumentException {

    try {
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
                new X500Principal("CN=" + subject), pair.getPublic());

        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withECDSA");

        if (null != SECURITY_PROVIDER) {
            csBuilder.setProvider(SECURITY_PROVIDER);
        }
        ContentSigner signer = csBuilder.build(pair.getPrivate());

        return certificationRequestToPEM(p10Builder.build(signer));
    } catch (Exception e) {

        logger.error(e);
        throw new InvalidArgumentException(e);

    }

}

From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandalone.java

public void createNifiKeystoresAndTrustStores(StandaloneConfig standaloneConfig)
        throws GeneralSecurityException, IOException {
    File baseDir = standaloneConfig.getBaseDir();
    if (!baseDir.exists() && !baseDir.mkdirs()) {
        throw new IOException(baseDir + " doesn't exist and unable to create it.");
    }// w w w. ja  v a2  s  .c  om

    if (!baseDir.isDirectory()) {
        throw new IOException("Expected directory to output to");
    }

    String signingAlgorithm = standaloneConfig.getSigningAlgorithm();
    int days = standaloneConfig.getDays();
    String keyPairAlgorithm = standaloneConfig.getKeyPairAlgorithm();
    int keySize = standaloneConfig.getKeySize();

    File nifiCert = new File(baseDir, NIFI_CERT + ".pem");
    File nifiKey = new File(baseDir, NIFI_KEY + ".key");

    X509Certificate certificate;
    KeyPair caKeyPair;

    if (logger.isInfoEnabled()) {
        logger.info("Running standalone certificate generation with output directory " + baseDir);
    }
    if (nifiCert.exists()) {
        if (!nifiKey.exists()) {
            throw new IOException(nifiCert + " exists already, but " + nifiKey
                    + " does not, we need both certificate and key to continue with an existing CA.");
        }
        try (FileReader pemEncodedCertificate = new FileReader(nifiCert)) {
            certificate = TlsHelper.parseCertificate(pemEncodedCertificate);
        }
        try (FileReader pemEncodedKeyPair = new FileReader(nifiKey)) {
            caKeyPair = TlsHelper.parseKeyPair(pemEncodedKeyPair);
        }

        certificate.verify(caKeyPair.getPublic());
        if (!caKeyPair.getPublic().equals(certificate.getPublicKey())) {
            throw new IOException("Expected " + nifiKey + " to correspond to CA certificate at " + nifiCert);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Using existing CA certificate " + nifiCert + " and key " + nifiKey);
        }
    } else if (nifiKey.exists()) {
        throw new IOException(nifiKey + " exists already, but " + nifiCert
                + " does not, we need both certificate and key to continue with an existing CA.");
    } else {
        TlsCertificateAuthorityManager tlsCertificateAuthorityManager = new TlsCertificateAuthorityManager(
                standaloneConfig);
        KeyStore.PrivateKeyEntry privateKeyEntry = tlsCertificateAuthorityManager
                .getOrGenerateCertificateAuthority();
        certificate = (X509Certificate) privateKeyEntry.getCertificateChain()[0];
        caKeyPair = new KeyPair(certificate.getPublicKey(), privateKeyEntry.getPrivateKey());

        try (PemWriter pemWriter = new PemWriter(
                new OutputStreamWriter(outputStreamFactory.create(nifiCert)))) {
            pemWriter.writeObject(new JcaMiscPEMGenerator(certificate));
        }

        try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiKey)))) {
            pemWriter.writeObject(new JcaMiscPEMGenerator(caKeyPair));
        }

        if (logger.isInfoEnabled()) {
            logger.info("Generated new CA certificate " + nifiCert + " and key " + nifiKey);
        }
    }

    NiFiPropertiesWriterFactory niFiPropertiesWriterFactory = standaloneConfig.getNiFiPropertiesWriterFactory();
    boolean overwrite = standaloneConfig.isOverwrite();

    List<InstanceDefinition> instanceDefinitions = standaloneConfig.getInstanceDefinitions();
    if (instanceDefinitions.isEmpty() && logger.isInfoEnabled()) {
        logger.info("No " + TlsToolkitStandaloneCommandLine.HOSTNAMES_ARG
                + " specified, not generating any host certificates or configuration.");
    }
    for (InstanceDefinition instanceDefinition : instanceDefinitions) {
        String hostname = instanceDefinition.getHostname();
        File hostDir;
        int hostIdentifierNumber = instanceDefinition.getInstanceIdentifier().getNumber();
        if (hostIdentifierNumber == 1) {
            hostDir = new File(baseDir, hostname);
        } else {
            hostDir = new File(baseDir, hostname + "_" + hostIdentifierNumber);
        }

        TlsClientConfig tlsClientConfig = new TlsClientConfig(standaloneConfig);
        File keystore = new File(hostDir, "keystore." + tlsClientConfig.getKeyStoreType().toLowerCase());
        File truststore = new File(hostDir, "truststore." + tlsClientConfig.getTrustStoreType().toLowerCase());

        if (hostDir.exists()) {
            if (!hostDir.isDirectory()) {
                throw new IOException(hostDir + " exists but is not a directory.");
            } else if (overwrite) {
                if (logger.isInfoEnabled()) {
                    logger.info("Overwriting any existing ssl configuration in " + hostDir);
                }
                keystore.delete();
                if (keystore.exists()) {
                    throw new IOException("Keystore " + keystore + " already exists and couldn't be deleted.");
                }
                truststore.delete();
                if (truststore.exists()) {
                    throw new IOException(
                            "Truststore " + truststore + " already exists and couldn't be deleted.");
                }
            } else {
                throw new IOException(hostDir + " exists and overwrite is not set.");
            }
        } else if (!hostDir.mkdirs()) {
            throw new IOException("Unable to make directory: " + hostDir.getAbsolutePath());
        } else if (logger.isInfoEnabled()) {
            logger.info("Writing new ssl configuration to " + hostDir);
        }

        tlsClientConfig.setKeyStore(keystore.getAbsolutePath());
        tlsClientConfig.setKeyStorePassword(instanceDefinition.getKeyStorePassword());
        tlsClientConfig.setKeyPassword(instanceDefinition.getKeyPassword());
        tlsClientConfig.setTrustStore(truststore.getAbsolutePath());
        tlsClientConfig.setTrustStorePassword(instanceDefinition.getTrustStorePassword());
        TlsClientManager tlsClientManager = new TlsClientManager(tlsClientConfig);
        KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
        Extensions sanDnsExtensions = StringUtils.isBlank(tlsClientConfig.getDomainAlternativeNames()) ? null
                : TlsHelper.createDomainAlternativeNamesExtensions(tlsClientConfig.getDomainAlternativeNames());
        tlsClientManager.addPrivateKeyToKeyStore(keyPair, NIFI_KEY,
                CertificateUtils.generateIssuedCertificate(tlsClientConfig.calcDefaultDn(hostname),
                        keyPair.getPublic(), sanDnsExtensions, certificate, caKeyPair, signingAlgorithm, days),
                certificate);
        tlsClientManager.setCertificateEntry(NIFI_CERT, certificate);
        tlsClientManager.addClientConfigurationWriter(
                new NifiPropertiesTlsClientConfigWriter(niFiPropertiesWriterFactory,
                        new File(hostDir, "nifi.properties"), hostname, instanceDefinition.getNumber()));
        tlsClientManager.write(outputStreamFactory);
        if (logger.isInfoEnabled()) {
            logger.info("Successfully generated TLS configuration for " + hostname + " " + hostIdentifierNumber
                    + " in " + hostDir);
        }
    }

    List<String> clientDns = standaloneConfig.getClientDns();
    if (standaloneConfig.getClientDns().isEmpty() && logger.isInfoEnabled()) {
        logger.info("No " + TlsToolkitStandaloneCommandLine.CLIENT_CERT_DN_ARG
                + " specified, not generating any client certificates.");
    }

    List<String> clientPasswords = standaloneConfig.getClientPasswords();
    for (int i = 0; i < clientDns.size(); i++) {
        String reorderedDn = CertificateUtils.reorderDn(clientDns.get(i));
        String clientDnFile = getClientDnFile(reorderedDn);
        File clientCertFile = new File(baseDir, clientDnFile + ".p12");

        if (clientCertFile.exists()) {
            if (overwrite) {
                if (logger.isInfoEnabled()) {
                    logger.info("Overwriting existing client cert " + clientCertFile);
                }
            } else {
                throw new IOException(clientCertFile + " exists and overwrite is not set.");
            }
        } else if (logger.isInfoEnabled()) {
            logger.info("Generating new client certificate " + clientCertFile);
        }
        KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
        X509Certificate clientCert = CertificateUtils.generateIssuedCertificate(reorderedDn,
                keyPair.getPublic(), null, certificate, caKeyPair, signingAlgorithm, days);
        KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString());
        keyStore.load(null, null);
        keyStore.setKeyEntry(NIFI_KEY, keyPair.getPrivate(), null,
                new Certificate[] { clientCert, certificate });
        String password = TlsHelper.writeKeyStore(keyStore, outputStreamFactory, clientCertFile,
                clientPasswords.get(i), standaloneConfig.isClientPasswordsGenerated());

        try (FileWriter fileWriter = new FileWriter(new File(baseDir, clientDnFile + ".password"))) {
            fileWriter.write(password);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Successfully generated client certificate " + clientCertFile);
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info("tls-toolkit standalone completed successfully");
    }
}