Example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getEncoded

List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest getEncoded

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getEncoded.

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Usage

From source file:org.picketbox.keystore.util.CertificateUtil.java

License:Open Source License

/**
 * Create a certificate signing request/*from w w  w  .jav  a2 s  .  c  o m*/
 *
 * @throws CertificateException
 */
public byte[] createCSR(String dn, KeyPair keyPair) throws CertificateException {
    X500Name name = new X500Name(dn);
    try {

        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory
                .createKey(keyPair.getPrivate().getEncoded());

        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);

        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(name, subPubKeyInfo);
        PKCS10CertificationRequest csr = builder.build(sigGen);
        return csr.getEncoded();
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}

From source file:org.picketlink.pki.internal.DefaultCertificateRequest.java

License:Open Source License

public DefaultCertificateRequest(User user, CertificateAuthority certificateAuthority) {
    try {// ww  w .  jav  a2 s.  co  m
        KeyPair userKeyPair = certificateAuthority.getKeyAuthority().getKeyPair(user);
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
                .getInstance(userKeyPair.getPublic().getEncoded());
        ContentSigner sigGen = X509Util.createSigner(userKeyPair.getPrivate(),
                certificateAuthority.getConfiguration());
        X500Name userDN = new X500Name(
                "CN=" + user.getLoginName() + "," + certificateAuthority.getConfiguration().getBaseDN());
        PKCS10CertificationRequest build = new PKCS10CertificationRequestBuilder(userDN, subjectPublicKeyInfo)
                .build(sigGen);

        this.message = build.getEncoded();
    } catch (Exception e) {
        throw new RuntimeException("Could not create CSR", e);
    }

    this.user = user;
}

From source file:org.shredzone.acme4j.util.CertificateUtilsTest.java

License:Apache License

/**
 * Test if {@link CertificateUtils#readCSR(InputStream)} reads an identical CSR.
 *///from w  w w. j  ava2  s .c  o m
@Test
public void testReadCSR() throws IOException {
    KeyPair keypair = KeyPairUtils.createKeyPair(2048);

    CSRBuilder builder = new CSRBuilder();
    builder.addDomains("example.com", "example.org");
    builder.sign(keypair);

    PKCS10CertificationRequest original = builder.getCSR();
    byte[] pemFile;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        builder.write(baos);
        pemFile = baos.toByteArray();
    }

    try (ByteArrayInputStream bais = new ByteArrayInputStream(pemFile)) {
        PKCS10CertificationRequest read = CertificateUtils.readCSR(bais);
        assertThat(original.getEncoded(), is(equalTo(read.getEncoded())));
    }
}

From source file:org.shredzone.acme4j.util.CSRBuilderTest.java

License:Apache License

/**
 * Test if the generated CSR is plausible.
 *//*from  w  ww.ja v a  2 s.c  o  m*/
@Test
public void testGenerate() throws IOException {
    CSRBuilder builder = new CSRBuilder();
    builder.addDomain("abc.de");
    builder.addDomain("fg.hi");
    builder.addDomains("jklm.no", "pqr.st");
    builder.addDomains(Arrays.asList("uv.wx", "y.z"));

    builder.setCountry("XX");
    builder.setLocality("Testville");
    builder.setOrganization("Testing Co");
    builder.setOrganizationalUnit("Testunit");
    builder.setState("ABC");

    assertThat(builder.toString(), is("CN=abc.de,C=XX,L=Testville,O=Testing Co," + "OU=Testunit,ST=ABC,"
            + "DNS=abc.de,DNS=fg.hi,DNS=jklm.no,DNS=pqr.st,DNS=uv.wx,DNS=y.z"));

    builder.sign(testKey);

    PKCS10CertificationRequest csr = builder.getCSR();
    assertThat(csr, is(notNullValue()));
    assertThat(csr.getEncoded(), is(equalTo(builder.getEncoded())));

    csrTest(csr);
    writerTest(builder);
}

From source file:org.shredzone.acme4j.util.CSRBuilderTest.java

License:Apache License

/**
 * Test if the generated CSR is plausible using a ECDSA key.
 *///from   w w  w .  j av a  2 s .c o m
@Test
public void testECCGenerate() throws IOException {
    CSRBuilder builder = new CSRBuilder();
    builder.addDomain("abc.de");
    builder.addDomain("fg.hi");
    builder.addDomains("jklm.no", "pqr.st");
    builder.addDomains(Arrays.asList("uv.wx", "y.z"));

    builder.setCountry("XX");
    builder.setLocality("Testville");
    builder.setOrganization("Testing Co");
    builder.setOrganizationalUnit("Testunit");
    builder.setState("ABC");

    assertThat(builder.toString(), is("CN=abc.de,C=XX,L=Testville,O=Testing Co," + "OU=Testunit,ST=ABC,"
            + "DNS=abc.de,DNS=fg.hi,DNS=jklm.no,DNS=pqr.st,DNS=uv.wx,DNS=y.z"));

    builder.sign(testEcKey);

    PKCS10CertificationRequest csr = builder.getCSR();
    assertThat(csr, is(notNullValue()));
    assertThat(csr.getEncoded(), is(equalTo(builder.getEncoded())));

    csrTest(csr);
    writerTest(builder);
}

From source file:org.shredzone.acme4j.util.CSRBuilderTest.java

License:Apache License

/**
 * Checks if the {@link CSRBuilder#write(java.io.Writer)} method generates a correct
 * CSR PEM file./*from w  w  w. ja v  a2  s  .  c  o  m*/
 */
private void writerTest(CSRBuilder builder) throws IOException, PEMException {
    // Write CSR to PEM
    String pem;
    try (StringWriter out = new StringWriter()) {
        builder.write(out);
        pem = out.toString();
    }

    // Make sure PEM file is properly formatted
    assertThat(pem, RegexMatchers.matchesPattern("-----BEGIN CERTIFICATE REQUEST-----[\\r\\n]+"
            + "([a-zA-Z0-9/+=]+[\\r\\n]+)+" + "-----END CERTIFICATE REQUEST-----[\\r\\n]*"));

    // Read CSR from PEM
    PKCS10CertificationRequest readCsr;
    try (PEMParser parser = new PEMParser(new StringReader(pem))) {
        readCsr = (PKCS10CertificationRequest) parser.readObject();
    }

    // Verify that both keypairs are the same
    assertThat(builder.getCSR(), not(sameInstance(readCsr)));
    assertThat(builder.getEncoded(), is(equalTo(readCsr.getEncoded())));

    // OutputStream is identical?
    byte[] pemBytes;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        builder.write(baos);
        pemBytes = baos.toByteArray();
    }
    assertThat(new String(pemBytes, "utf-8"), is(equalTo(pem)));
}

From source file:org.signserver.server.cryptotokens.CryptoTokenBase.java

License:Open Source License

@Override
public ICertReqData genCertificateRequest(ISignerCertReqInfo info, final boolean explicitEccParameters,
        final boolean defaultKey) throws CryptoTokenOfflineException {
    Base64SignerCertReqData retval = null;
    if (info instanceof PKCS10CertReqInfo) {
        PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
        PKCS10CertificationRequest pkcs10;
        final int purpose = defaultKey ? PURPOSE_SIGN : PURPOSE_NEXTKEY;
        if (log.isDebugEnabled()) {
            log.debug("Purpose: " + purpose);
            log.debug("signatureAlgorithm: " + reqInfo.getSignatureAlgorithm());
            log.debug("subjectDN: " + reqInfo.getSubjectDN());
            log.debug("explicitEccParameters: " + explicitEccParameters);
        }//from  w  w w .  j  a va  2  s .  c o  m

        try {
            PublicKey publicKey = getPublicKey(purpose);

            // Handle ECDSA key with explicit parameters
            if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
                publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
            }
            // Generate request
            final JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
                    new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
            final ContentSigner contentSigner = new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                    .setProvider(getProvider(ICryptoToken.PROVIDERUSAGE_SIGN)).build(getPrivateKey(purpose));
            pkcs10 = builder.build(contentSigner);
            retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
        } catch (IOException e) {
            log.error("Certificate request error: " + e.getMessage(), e);
        } catch (OperatorCreationException e) {
            log.error("Certificate request error: signer could not be initialized", e);
        } catch (NoSuchAlgorithmException e) {
            log.error("Certificate request error: " + e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error("Certificate request error: " + e.getMessage(), e);
        }

    }
    return retval;
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

License:Open Source License

/**
 * Generate a certificate signing request (PKCS#10).
 * @param info A PKCS10CertReqInfo//from   w w  w .j  ava  2s. c  om
 * @param privateKey Private key for signing the request
 * @param signatureProvider Name of provider to sign with
 * @param publicKey Public key to include in the request
 * @param explicitEccParameters True if the EC domain parameters should be included (ie. not a named curve)
 * @return the certificate request data
 */
public static ICertReqData genCertificateRequest(ISignerCertReqInfo info, final PrivateKey privateKey,
        final String signatureProvider, PublicKey publicKey, final boolean explicitEccParameters)
        throws IllegalArgumentException {
    LOG.debug(">genCertificateRequest");
    final Base64SignerCertReqData retval;
    if (info instanceof PKCS10CertReqInfo) {
        PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
        PKCS10CertificationRequest pkcs10;

        if (LOG.isDebugEnabled()) {
            LOG.debug("signatureAlgorithm: " + reqInfo.getSignatureAlgorithm());
            LOG.debug("subjectDN: " + reqInfo.getSubjectDN());
            LOG.debug("explicitEccParameters: " + explicitEccParameters);
        }

        try {
            // Handle ECDSA key with explicit parameters
            if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
                publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Public key SHA1: " + createKeyHash(publicKey));
                LOG.debug("Public key SHA256: " + KeyUsageCounterHash.create(publicKey));
            }

            // Generate request
            final JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
                    new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
            final ContentSigner contentSigner = new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                    .setProvider(signatureProvider).build(privateKey);
            pkcs10 = builder.build(contentSigner);
            retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
        } catch (IOException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        } catch (OperatorCreationException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        }
        LOG.debug("<genCertificateRequest");
        return retval;
    } else {
        throw new IllegalArgumentException(
                "Unsupported certificate request info type: " + info.getClass().getName());
    }
}

From source file:org.signserver.server.cryptotokens.OldPKCS11CryptoToken.java

License:Open Source License

@Override
public ICertReqData genCertificateRequest(ISignerCertReqInfo info, final boolean explicitEccParameters,
        boolean defaultKey) throws CryptoTokenOfflineException {
    LOG.debug(">genCertificateRequest PKCS11CryptoToken");
    Base64SignerCertReqData retval = null;
    if (info instanceof PKCS10CertReqInfo) {
        PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
        PKCS10CertificationRequest pkcs10;

        final String alias;
        if (defaultKey) {
            alias = properties.getProperty("defaultKey");
        } else {//from  w  ww .j  a  v  a  2 s. c  o m
            alias = properties.getProperty("nextCertSignKey");
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("defaultKey: " + defaultKey);
            LOG.debug("alias: " + alias);
            LOG.debug("signatureAlgorithm: " + reqInfo.getSignatureAlgorithm());
            LOG.debug("subjectDN: " + reqInfo.getSubjectDN());
            LOG.debug("explicitEccParameters: " + explicitEccParameters);
        }

        try {
            final KeyStore keyStore = getKeyStore(authenticationCode);

            final PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, authenticationCode);
            final Certificate cert = keyStore.getCertificate(alias);
            if (cert == null) {
                throw new CryptoTokenOfflineException(
                        "Certificate request error: No key with the configured alias");
            }

            PublicKey publicKey = cert.getPublicKey();

            // Handle ECDSA key with explicit parameters
            if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
                publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Public key SHA1: " + CryptoTokenHelper.createKeyHash(cert.getPublicKey()));
                LOG.debug("Public key SHA256: " + KeyUsageCounterHash.create(cert.getPublicKey()));
            }

            // Generate request
            final JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
                    new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
            final ContentSigner contentSigner = new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                    .setProvider(getProvider(ICryptoToken.PROVIDERUSAGE_SIGN)).build(privateKey);
            pkcs10 = builder.build(contentSigner);
            retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
        } catch (IOException e) {
            LOG.error("Certificate request error: " + e.getMessage(), e);
        } catch (OperatorCreationException e) {
            LOG.error("Certificate request error: signer could not be initialized", e);
        } catch (UnrecoverableKeyException e) {
            LOG.error("Certificate request error: " + e.getMessage(), e);
        } catch (KeyStoreException e) {
            LOG.error("Certificate request error: " + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("Certificate request error: " + e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            LOG.error("Certificate request error: " + e.getMessage(), e);
        }

    }
    LOG.debug("<genCertificateRequest PKCS11CryptoToken");
    return retval;
}

From source file:org.signserver.server.cryptotokens.SoftCryptoToken.java

License:Open Source License

/**
 * Special method that generates a new key pair that is written to the worker configuration
 * before the request is generated. The new keys aren't activated until reload is issued.
 * //from  ww w. ja v  a 2  s.  co  m
 */
@Override
public ICertReqData genCertificateRequest(ISignerCertReqInfo info, final boolean explicitEccParameters,
        final boolean defaultKey) throws CryptoTokenOfflineException {
    Base64SignerCertReqData retval = null;

    try {
        KeyPair newKeys = KeyTools.genKeys(keySpec, keyAlg);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        byte[] pubKeyData = newKeys.getPublic().getEncoded();
        byte[] prvKeyData = newKeys.getPrivate().getEncoded();
        dos.writeInt(pubKeyData.length);
        dos.write(pubKeyData);
        dos.writeInt(prvKeyData.length);
        dos.write(prvKeyData);

        getWorkerSession().setWorkerProperty(workerId, PROPERTY_KEYDATA,
                new String(Base64.encode(baos.toByteArray())));

        if (info instanceof PKCS10CertReqInfo) {
            PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
            PKCS10CertificationRequest pkcs10;
            PublicKey publicKey = newKeys.getPublic();

            // Handle ECDSA key with explicit parameters
            if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
                publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
            }
            // Generate request
            // Generate request
            final JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
                    new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
            final ContentSigner contentSigner = new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                    .setProvider(getProvider(ICryptoToken.PROVIDERUSAGE_SIGN)).build(newKeys.getPrivate());
            pkcs10 = builder.build(contentSigner);
            retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
        }
    } catch (IOException e) {
        LOG.error("Certificate request error: " + e.getMessage(), e);
    } catch (OperatorCreationException e) {
        LOG.error("Certificate request error: signer could not be initialized", e);
    } catch (NoSuchAlgorithmException e1) {
        LOG.error("Error generating new certificate request : " + e1.getMessage(), e1);
    } catch (NoSuchProviderException e1) {
        LOG.error("Error generating new certificate request : " + e1.getMessage(), e1);
    } catch (InvalidAlgorithmParameterException e1) {
        LOG.error("Error generating new certificate request : " + e1.getMessage(), e1);
    } catch (NamingException e1) {
        LOG.error("Error generating new certificate request : " + e1.getMessage(), e1);
    }
    return retval;
}