Search in sources :

Example 76 with Certificate

use of org.bouncycastle.asn1.x509.Certificate in project xabber-android by redsolution.

the class CustomDomainVerifier method verify.

public boolean verify(String domain, String hostname, SSLSession sslSession) {
    try {
        Certificate[] chain = sslSession.getPeerCertificates();
        if (chain.length == 0 || !(chain[0] instanceof X509Certificate)) {
            return false;
        }
        X509Certificate certificate = (X509Certificate) chain[0];
        if (isSelfSigned(certificate)) {
            List<String> domains = getCommonNames(certificate);
            if (domains.size() == 1 && domains.get(0).equals(domain)) {
                Log.d(LOGTAG, "accepted CN in cert self signed cert for " + domain);
                return true;
            }
        }
        Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
        List<String> xmppAddrs = new ArrayList<>();
        List<String> srvNames = new ArrayList<>();
        List<String> domains = new ArrayList<>();
        if (alternativeNames != null) {
            for (List<?> san : alternativeNames) {
                Integer type = (Integer) san.get(0);
                if (type == 0) {
                    Pair<String, String> otherName = parseOtherName((byte[]) san.get(1));
                    if (otherName != null) {
                        switch(otherName.first) {
                            case SRVName:
                                srvNames.add(otherName.second);
                                break;
                            case xmppAddr:
                                xmppAddrs.add(otherName.second);
                                break;
                            default:
                                Log.d(LOGTAG, "oid: " + otherName.first + " value: " + otherName.second);
                        }
                    }
                } else if (type == 2) {
                    Object value = san.get(1);
                    if (value instanceof String) {
                        domains.add((String) value);
                    }
                }
            }
        }
        if (srvNames.size() == 0 && xmppAddrs.size() == 0 && domains.size() == 0) {
            domains.addAll(domains);
        }
        Log.d(LOGTAG, "searching for " + domain + " in srvNames: " + srvNames + " xmppAddrs: " + xmppAddrs + " domains:" + domains);
        if (hostname != null) {
            Log.d(LOGTAG, "also trying to verify hostname " + hostname);
        }
        return xmppAddrs.contains(domain) || srvNames.contains("_xmpp-client." + domain) || matchDomain(domain, domains) || (hostname != null && matchDomain(hostname, domains));
    } catch (Exception e) {
        return false;
    }
}
Also used : ArrayList(java.util.ArrayList) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) CertificateEncodingException(java.security.cert.CertificateEncodingException) ArrayList(java.util.ArrayList) List(java.util.List) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 77 with Certificate

use of org.bouncycastle.asn1.x509.Certificate in project syncany by syncany.

the class CipherUtil method generateSelfSignedCertificate.

/**
 * Generates a self-signed certificate, given a public/private key pair.
 *
 * @see <a href="https://code.google.com/p/gitblit/source/browse/src/com/gitblit/MakeCertificate.java?r=88598bb2f779b73479512d818c675dea8fa72138">Original source of this method</a>
 */
public static X509Certificate generateSelfSignedCertificate(String commonName, KeyPair keyPair) throws OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    // Certificate CN, O and OU
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.CN, commonName);
    builder.addRDN(BCStyle.O, CipherParams.CERTIFICATE_ORGANIZATION);
    builder.addRDN(BCStyle.OU, CipherParams.CERTIFICATE_ORGUNIT);
    // Dates and serial
    Date notBefore = new Date(System.currentTimeMillis() - 1 * 24 * 60 * 60 * 1000L);
    Date notAfter = new Date(System.currentTimeMillis() + 5 * 365 * 24 * 60 * 60 * 1000L);
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    // Issuer and subject (identical, because self-signed)
    X500Name issuer = builder.build();
    X500Name subject = issuer;
    X509v3CertificateBuilder certificateGenerator = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, keyPair.getPublic());
    ContentSigner signatureGenerator = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(CipherParams.CRYPTO_PROVIDER).build(keyPair.getPrivate());
    X509Certificate certificate = new JcaX509CertificateConverter().setProvider(CipherParams.CRYPTO_PROVIDER).getCertificate(certificateGenerator.build(signatureGenerator));
    certificate.checkValidity(new Date());
    certificate.verify(certificate.getPublicKey());
    return certificate;
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) 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) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 78 with Certificate

use of org.bouncycastle.asn1.x509.Certificate 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 79 with Certificate

use of org.bouncycastle.asn1.x509.Certificate 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 80 with Certificate

use of org.bouncycastle.asn1.x509.Certificate 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)

Aggregations

X509Certificate (java.security.cert.X509Certificate)95 IOException (java.io.IOException)82 ArrayList (java.util.ArrayList)46 X500Name (org.bouncycastle.asn1.x500.X500Name)43 Date (java.util.Date)33 List (java.util.List)33 CertificateParsingException (java.security.cert.CertificateParsingException)30 GeneralName (org.bouncycastle.asn1.x509.GeneralName)29 BigInteger (java.math.BigInteger)28 CertificateException (java.security.cert.CertificateException)27 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)26 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)25 CertificateEncodingException (java.security.cert.CertificateEncodingException)24 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)24 GeneralSecurityException (java.security.GeneralSecurityException)23 PrivateKey (java.security.PrivateKey)23 Enumeration (java.util.Enumeration)23 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)23 ContentSigner (org.bouncycastle.operator.ContentSigner)23 Certificate (java.security.cert.Certificate)22