Search in sources :

Example 16 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project oxTrust by GluuFederation.

the class UpdateTrustRelationshipAction method getCertForGeneratedSP.

/**
 * If there is no certificate selected, or certificate is invalid -
 * generates one.
 *
 * @author �Oleksiy Tataryn�
 * @return certificate for generated SP
 * @throws IOException
 * @throws CertificateEncodingException
 */
public String getCertForGeneratedSP() throws IOException {
    X509Certificate cert = null;
    if ((certWrapper != null) && (certWrapper.getInputStream() != null)) {
        try {
            cert = sslService.getPEMCertificate(certWrapper.getInputStream());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    if ((cert == null) && (trustRelationship.getUrl() != null)) {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
            keyPairGen.initialize(2048);
            KeyPair pair = keyPairGen.generateKeyPair();
            StringWriter keyWriter = new StringWriter();
            PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
            pemFormatWriter.writeObject(pair.getPrivate());
            pemFormatWriter.close();
            String url = trustRelationship.getUrl().replaceFirst(".*//", "");
            X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
            org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
            byte[] derCert = cert.getEncoded();
            String pemCertPre = new String(encoder.encode(derCert));
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
            log.debug(pemCertPre);
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
            shibboleth3ConfService.saveCert(trustRelationship, pemCertPre);
            shibboleth3ConfService.saveKey(trustRelationship, keyWriter.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    // String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
    // + "-shib.crt";
    // File certFile = new File(certName);
    // if (certFile.exists()) {
    // cert = SSLService.instance().getPEMCertificate(certName);
    // }
    }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
            log.info("##### certificate = " + certificate);
        } catch (CertificateEncodingException e) {
            certificate = null;
            facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
            log.error("Failed to encode certificate to DER", e);
        }
    } else {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }
    return certificate;
}
Also used : KeyPair(java.security.KeyPair) Base64(org.bouncycastle.util.encoders.Base64) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) PEMWriter(org.bouncycastle.openssl.PEMWriter) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) CertificateEncodingException(java.security.cert.CertificateEncodingException) BaseMappingException(org.gluu.persist.exception.mapping.BaseMappingException) IOException(java.io.IOException) Date(java.util.Date) StringWriter(java.io.StringWriter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 17 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project oxTrust by GluuFederation.

the class TrustRelationshipWebService method generateCertForGeneratedSP.

/**
 * @return certificate for generated SP
 * @throws IOException
 * @throws CertificateEncodingException
 */
public String generateCertForGeneratedSP(GluuSAMLTrustRelationship trustRelationship) throws IOException {
    X509Certificate cert = null;
    // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    try {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGen.initialize(2048);
        KeyPair pair = keyPairGen.generateKeyPair();
        StringWriter keyWriter = new StringWriter();
        PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
        pemFormatWriter.writeObject(pair.getPrivate());
        pemFormatWriter.close();
        String url = trustRelationship.getUrl().replaceFirst(".*//", "");
        X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
        cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
        org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
        byte[] derCert = cert.getEncoded();
        String pemCertPre = new String(encoder.encode(derCert));
        logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
        logger.debug(pemCertPre);
        logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
        shibboleth3ConfService.saveCert(trustRelationship, pemCertPre);
        shibboleth3ConfService.saveKey(trustRelationship, keyWriter.toString());
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Failed to generate certificate", e);
    }
    // String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
    // + "-shib.crt";
    // File certFile = new File(certName);
    // if (certFile.exists()) {
    // cert = SSLService.instance().getPEMCertificate(certName);
    // }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
            logger.info("##### certificate = " + certificate);
        } catch (CertificateEncodingException e) {
            certificate = null;
            // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
            logger.error("Failed to encode certificate to DER", e);
        }
    } else {
    // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }
    return certificate;
}
Also used : KeyPair(java.security.KeyPair) Base64(org.bouncycastle.util.encoders.Base64) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) PEMWriter(org.bouncycastle.openssl.PEMWriter) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) CertificateEncodingException(java.security.cert.CertificateEncodingException) BaseMappingException(org.gluu.persist.exception.mapping.BaseMappingException) IOException(java.io.IOException) StringWriter(java.io.StringWriter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 18 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project jetty-bootstrap by teknux-org.

the class JettyKeystoreGeneratorBuilder method generateCertificate.

private static Certificate generateCertificate(KeyPair keyPair, String domainName, String signatureAlgorithm, String rdnOuValue, String rdnOValue, int dateNotBeforeNumberOfDays, int dateNotAfterNumberOfDays) throws JettyKeystoreException {
    X500NameBuilder issuerX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
    if (rdnOuValue != null) {
        issuerX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
    }
    if (rdnOValue != null) {
        issuerX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
    }
    X500Name issuer = issuerX500Namebuilder.addRDN(BCStyle.CN, domainName).build();
    BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
    Date dateNotBefore = new Date(System.currentTimeMillis() - (dateNotBeforeNumberOfDays * DAY_IN_MILLIS));
    Date dateNotAfter = new Date(System.currentTimeMillis() + (dateNotAfterNumberOfDays * DAY_IN_MILLIS));
    X500NameBuilder subjectX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
    if (rdnOuValue != null) {
        subjectX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
    }
    if (rdnOValue != null) {
        subjectX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
    }
    X500Name subject = subjectX500Namebuilder.addRDN(BCStyle.CN, domainName).build();
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial, dateNotBefore, dateNotAfter, subject, publicKeyInfo);
    Provider provider = new BouncyCastleProvider();
    try {
        ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(keyPair.getPrivate());
        return new JcaX509CertificateConverter().setProvider(provider).getCertificate(x509v3CertificateBuilder.build(signer));
    } catch (OperatorCreationException | CertificateException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_CREATE_CERTIFICATE, "Can not generate certificate", e);
    }
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) Provider(java.security.Provider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) BigInteger(java.math.BigInteger) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 19 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project tomee by apache.

the class HttpsConnectionTest method createKeyStore.

private File createKeyStore() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    dropKeyStore();
    File keyStore = new File(STORE_PATH);
    keyStore.getParentFile().mkdirs();
    try (final FileOutputStream fos = new FileOutputStream(keyStore)) {
        final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
        keyGenerator.initialize(1024);
        final KeyPair pair = keyGenerator.generateKeyPair();
        final boolean addBc = Security.getProvider("BC") == null;
        if (addBc) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            final X509v1CertificateBuilder x509v1CertificateBuilder = new JcaX509v1CertificateBuilder(new X500Name("cn=" + SERVER), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)), new X500Name("cn=" + SERVER), pair.getPublic());
            final X509CertificateHolder certHldr = x509v1CertificateBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(pair.getPrivate()));
            final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHldr);
            final KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null, STORE_PWD.toCharArray());
            ks.setKeyEntry(SERVER, pair.getPrivate(), STORE_PWD.toCharArray(), new Certificate[] { cert });
            ks.store(fos, STORE_PWD.toCharArray());
        } finally {
            if (addBc) {
                Security.removeProvider("BC");
            }
        }
    } catch (final Exception e) {
        Assert.fail(e.getMessage());
    }
    return keyStore;
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) FileOutputStream(java.io.FileOutputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) File(java.io.File) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 20 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project Openfire by igniterealtime.

the class KeystoreTestUtils method generateTestCertificate.

private static X509Certificate generateTestCertificate(final boolean isValid, final KeyPair issuerKeyPair, final KeyPair subjectKeyPair, int indexAwayFromEndEntity) throws Exception {
    // Issuer and Subject.
    final X500Name subject = new X500Name("CN=" + Base64.encodeBytes(subjectKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
    final X500Name issuer = new X500Name("CN=" + Base64.encodeBytes(issuerKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
    // Validity
    final Date notBefore;
    final Date notAfter;
    if (isValid) {
        // 30 days ago
        notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30));
        // 99 days from now.
        notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99));
    } else {
        // Generate a certificate for which the validate period has expired.
        // 40 days ago
        notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 40));
        // 10 days ago
        notAfter = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 10));
    }
    // The new certificate should get a unique serial number.
    final BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, subjectKeyPair.getPublic());
    // When this certificate is used to sign another certificate, basic constraints need to be set.
    if (indexAwayFromEndEntity > 0) {
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(indexAwayFromEndEntity - 1));
    }
    final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(issuerKeyPair.getPrivate());
    final X509CertificateHolder certificateHolder = builder.build(contentSigner);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
}
Also used : JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) Date(java.util.Date)

Aggregations

JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)30 ContentSigner (org.bouncycastle.operator.ContentSigner)23 Date (java.util.Date)22 X509Certificate (java.security.cert.X509Certificate)21 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)21 X500Name (org.bouncycastle.asn1.x500.X500Name)18 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)17 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)17 BigInteger (java.math.BigInteger)13 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)13 KeyPair (java.security.KeyPair)11 KeyStore (java.security.KeyStore)10 IOException (java.io.IOException)9 SecureRandom (java.security.SecureRandom)9 PrivateKey (java.security.PrivateKey)8 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)8 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)8 KeyPairGenerator (java.security.KeyPairGenerator)7 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)7 File (java.io.File)6