Example usage for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder

List of usage examples for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder.

Prototype

public JcaContentSignerBuilder(String signatureAlgorithm) 

Source Link

Usage

From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java

License:Open Source License

/**
 * Create a PKCS #10 certificate signing request (CSR) using the supplied
 * certificate, private key and signature algorithm.
 *
 * @param cert// w  ww .j  av  a 2  s.  c  o m
 *            The certificate
 * @param privateKey
 *            The private key
 * @param signatureType
 *            Signature
 * @param challenge
 *            Challenge, optional, pass null if not required
 * @param unstructuredName
 *            An optional company name, pass null if not required
 * @param useExtensions
 *            Use extensions from cert for extensionRequest attribute?
 * @throws CryptoException
 *             If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey,
        SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions,
        Provider provider) throws CryptoException {

    try {
        JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
                cert.getSubjectX500Principal(), cert.getPublicKey());

        // add challenge attribute
        if (challenge != null) {
            // PKCS#9 2.0: SHOULD use UTF8String encoding
            csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
        }

        if (unstructuredName != null) {
            csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
        }

        if (useExtensions) {
            // add extensionRequest attribute with all extensions from the certificate
            Certificate certificate = Certificate.getInstance(cert.getEncoded());
            Extensions extensions = certificate.getTBSCertificate().getExtensions();
            if (extensions != null) {
                csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
            }
        }

        // fall back to bouncy castle provider if given provider does not support the requested algorithm
        if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
            provider = new BouncyCastleProvider();
        }

        ContentSigner contentSigner = null;

        if (provider == null) {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
        } else {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider)
                    .build(privateKey);
        }

        PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);

        if (!verifyCsr(csr)) {
            throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
        }

        return csr;
    } catch (CertificateEncodingException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

License:Open Source License

private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey,
        X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider)
        throws CryptoException {

    try {/*from   ww  w.  j  av a 2 s  . c  o m*/
        List<X509Certificate> certList = new ArrayList<X509Certificate>();

        Collections.addAll(certList, certificateChain);

        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC")
                .build();
        JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce())
                .setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
        if (provider != null) {
            csb.setProvider(provider);
        }
        JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);

        // remove cmsAlgorithmProtect for compatibility reasons
        SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
        final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
        sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {
            @Override
            public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
                AttributeTable ret = sAttrGen.getAttributes(parameters);
                return ret.remove(CMSAttributes.cmsAlgorithmProtect);
            }
        }, sigGen.getUnsignedAttributeTableGenerator());

        CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
        dataGen.addSignerInfoGenerator(sigGen);
        dataGen.addCertificates(new JcaCertStore(certList));

        CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);

        // now let TSA time-stamp the signature
        if (tsaUrl != null && !tsaUrl.isEmpty()) {
            signedData = addTimestamp(tsaUrl, signedData);
        }

        return signedData.getEncoded();
    } catch (Exception ex) {
        throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertificateGenerator.java

License:Open Source License

private X509Certificate generateVersion1(X500Name subject, X500Name issuer, long validity, PublicKey publicKey,
        PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber) throws CryptoException {
    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + validity);

    JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore,
            notAfter, subject, publicKey);

    try {// w  w  w  .  j av  a2 s .  c  o  m
        ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC")
                .build(privateKey);
        return new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certBuilder.build(certSigner));
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    } catch (IllegalStateException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    } catch (OperatorCreationException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertificateGenerator.java

License:Open Source License

private X509Certificate generateVersion3(X500Name subject, X500Name issuer, long validity, PublicKey publicKey,
        PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber, X509Extension extensions,
        Provider provider) throws CryptoException, CertIOException {
    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + validity);

    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serialNumber, notBefore,
            notAfter, subject, publicKey);

    if (extensions != null) {
        for (String oid : extensions.getCriticalExtensionOIDs()) {
            certBuilder.addExtension(new ASN1ObjectIdentifier(oid), true, getExtensionValue(extensions, oid));
        }/* w w w  . j ava  2s. co  m*/

        for (String oid : extensions.getNonCriticalExtensionOIDs()) {
            certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false, getExtensionValue(extensions, oid));
        }
    }

    try {
        ContentSigner certSigner = null;

        if (provider == null) {
            certSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
        } else {
            certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider)
                    .build(privateKey);
        }

        return new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certBuilder.build(certSigner));
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    } catch (IllegalStateException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    } catch (OperatorCreationException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    }
}

From source file:net.sf.keystore_explorer.gui.dialogs.DViewCsr.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override/*from  w w  w . jav  a2s.  c o  m*/
        public void run() {
            try {
                KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
                KeyPair keyPair = keyGen.genKeyPair();
                JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
                        new X500Name("cn=test"), keyPair.getPublic());
                PKCS10CertificationRequest csr = csrBuilder.build(new JcaContentSignerBuilder("SHA256withRSA")
                        .setProvider("BC").build(keyPair.getPrivate()));

                DViewCsr dialog = new DViewCsr(new javax.swing.JFrame(), "Title", csr);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:net.sf.keystore_explorer.gui.dialogs.sign.DSignCsr.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override/* w ww.j  ava  2 s  . co  m*/
        public void run() {
            try {
                KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
                keyGen.initialize(1024);
                KeyPair keyPair = keyGen.genKeyPair();
                JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
                        new X500Name("cn=test"), keyPair.getPublic());
                PKCS10CertificationRequest csr = csrBuilder.build(new JcaContentSignerBuilder("SHA256withRSA")
                        .setProvider("BC").build(keyPair.getPrivate()));

                DSignCsr dialog = new DSignCsr(new javax.swing.JFrame(), csr,
                        new File(System.getProperty("user.dir"), "test.csr"), keyPair.getPrivate(),
                        KeyPairType.RSA, null, new BouncyCastleProvider());
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:net.sf.portecle.crypto.X509CertUtil.java

License:Open Source License

/**
 * Generate a self-signed X509 Version 1 certificate for the supplied key pair and signature algorithm.
 * /*from  w  w w .  j  a v  a 2 s  .  c om*/
 * @return The generated certificate
 * @param sCommonName Common name certificate attribute
 * @param sOrganisationUnit Organization Unit certificate attribute
 * @param sOrganisation Organization certificate attribute
 * @param sLocality Locality certificate
 * @param sState State certificate attribute
 * @param sEmailAddress Email Address certificate attribute
 * @param sCountryCode Country Code certificate attribute
 * @param iValidity Validity period of certificate in days
 * @param publicKey Public part of key pair
 * @param privateKey Private part of key pair
 * @param signatureType Signature Type
 * @throws CryptoException If there was a problem generating the certificate
 */
public static X509Certificate generateCert(String sCommonName, String sOrganisationUnit, String sOrganisation,
        String sLocality, String sState, String sCountryCode, String sEmailAddress, int iValidity,
        PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType) throws CryptoException {
    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    if (sEmailAddress != null) {
        nameBuilder.addRDN(BCStyle.E, sEmailAddress);
    }
    if (sCountryCode != null) {
        nameBuilder.addRDN(BCStyle.C, sCountryCode);
    }
    if (sState != null) {
        nameBuilder.addRDN(BCStyle.ST, sState);
    }
    if (sLocality != null) {
        nameBuilder.addRDN(BCStyle.L, sLocality);
    }
    if (sOrganisation != null) {
        nameBuilder.addRDN(BCStyle.O, sOrganisation);
    }
    if (sOrganisationUnit != null) {
        nameBuilder.addRDN(BCStyle.OU, sOrganisationUnit);
    }
    if (sCommonName != null) {
        nameBuilder.addRDN(BCStyle.CN, sCommonName);
    }

    BigInteger serial = generateX509SerialNumber();

    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(notBefore.getTime() + ((long) iValidity * 24 * 60 * 60 * 1000));

    JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(nameBuilder.build(), serial,
            notBefore, notAfter, nameBuilder.build(), publicKey);

    try {
        ContentSigner signer = new JcaContentSignerBuilder(signatureType.name()).build(privateKey);
        X509CertificateHolder certHolder = certBuilder.build(signer);

        return new JcaX509CertificateConverter().getCertificate(certHolder);
    } catch (CertificateException | OperatorCreationException ex) {
        throw new CryptoException(RB.getString("CertificateGenFailed.exception.message"), ex);
    }
}

From source file:net.sf.portecle.crypto.X509CertUtil.java

License:Open Source License

/**
 * Renew a self-signed X509 Version 1 certificate.
 * //w  w  w. j  ava2  s .c  o  m
 * @return The renewed certificate
 * @param oldCert old certificate
 * @param iValidity Validity period of certificate in days to add to the old cert's expiry date, or
 *            current time if the certificate has expired
 * @param publicKey Public part of key pair
 * @param privateKey Private part of key pair
 * @throws CryptoException If there was a problem generating the certificate
 */
public static X509Certificate renewCert(X509Certificate oldCert, int iValidity, PublicKey publicKey,
        PrivateKey privateKey) throws CryptoException {
    BigInteger serial = generateX509SerialNumber();

    // Valid before and after dates now to iValidity days in the future from now or existing expiry date
    Date notBefore = new Date();
    Date oldExpiry = oldCert.getNotAfter();
    if (oldExpiry == null || oldExpiry.before(notBefore)) {
        oldExpiry = notBefore;
    }
    Date notAfter = new Date(oldExpiry.getTime() + ((long) iValidity * 24 * 60 * 60 * 1000));

    // TODO: verify/force self-signedness

    JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(oldCert.getIssuerX500Principal(),
            serial, notBefore, notAfter, oldCert.getSubjectX500Principal(), publicKey);

    try {
        ContentSigner signer = new JcaContentSignerBuilder(oldCert.getSigAlgName()).build(privateKey);
        X509CertificateHolder certHolder = certBuilder.build(signer);

        return new JcaX509CertificateConverter().getCertificate(certHolder);
    } catch (CertificateException | OperatorCreationException ex) {
        throw new CryptoException(RB.getString("CertificateGenFailed.exception.message"), ex);
    }
}

From source file:net.sf.portecle.crypto.X509CertUtil.java

License:Open Source License

/**
 * Create a PKCS #10 certification request (CSR) using the supplied certificate and private key.
 * /*from w ww . ja  v  a  2 s  .co  m*/
 * @param cert The certificate
 * @param privateKey The private key
 * @throws CryptoException If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generatePKCS10CSR(X509Certificate cert, PrivateKey privateKey)
        throws CryptoException {
    X500Name subject = new X500Name(cert.getSubjectDN().toString());

    JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject,
            cert.getPublicKey());
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(cert.getSigAlgName());

    try {
        ContentVerifierProvider prov = new JcaContentVerifierProviderBuilder().build(cert);
        PKCS10CertificationRequest csr = csrBuilder.build(signerBuilder.build(privateKey));

        if (!csr.isSignatureValid(prov)) {
            throw new CryptoException(RB.getString("NoVerifyGenCsr.exception.message"));
        }

        return csr;
    } catch (OperatorCreationException | PKCSException ex) {
        throw new CryptoException(RB.getString("NoGenerateCsr.exception.message"), ex);
    }
}

From source file:net.sf.sahi.ssl.SSLHelper.java

License:Apache License

private X509Certificate createX509Certificate(X509v3CertificateBuilder certificateBuilder,
        PrivateKey privateRootKey) throws OperatorCreationException, CertificateException {
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .setProvider(bouncyCastleProvider).build(privateRootKey);
    return new JcaX509CertificateConverter().setProvider(bouncyCastleProvider)
            .getCertificate(certificateBuilder.build(signer));
}