Search in sources :

Example 16 with X500Name

use of sun.security.x509.X500Name in project robovm by robovm.

the class X509CRLObject method loadCRLEntries.

private Set loadCRLEntries() {
    Set entrySet = new HashSet();
    Enumeration certs = c.getRevokedCertificateEnumeration();
    // the issuer
    X500Name previousCertificateIssuer = null;
    while (certs.hasMoreElements()) {
        TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) certs.nextElement();
        X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer);
        entrySet.add(crlEntry);
        if (isIndirect && entry.hasExtensions()) {
            Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer);
            if (currentCaName != null) {
                previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName());
            }
        }
    }
    return entrySet;
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) HashSet(java.util.HashSet) Set(java.util.Set) Enumeration(java.util.Enumeration) TBSCertList(org.bouncycastle.asn1.x509.TBSCertList) X500Name(org.bouncycastle.asn1.x500.X500Name) X509CRLEntry(java.security.cert.X509CRLEntry) HashSet(java.util.HashSet)

Example 17 with X500Name

use of sun.security.x509.X500Name in project Conversations by siacs.

the class XmppDomainVerifier method verify.

@Override
public boolean verify(String domain, SSLSession sslSession) {
    try {
        Certificate[] chain = sslSession.getPeerCertificates();
        if (chain.length == 0 || !(chain[0] instanceof X509Certificate)) {
            return false;
        }
        X509Certificate certificate = (X509Certificate) chain[0];
        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) {
            X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
            RDN[] rdns = x500name.getRDNs(BCStyle.CN);
            for (int i = 0; i < rdns.length; ++i) {
                domains.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[i].getFirst().getValue()));
            }
        }
        Log.d(LOGTAG, "searching for " + domain + " in srvNames: " + srvNames + " xmppAddrs: " + xmppAddrs + " domains:" + domains);
        return xmppAddrs.contains(domain) || srvNames.contains("_xmpp-client." + domain) || matchDomain(domain, domains);
    } catch (Exception e) {
        return false;
    }
}
Also used : ArrayList(java.util.ArrayList) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) ArrayList(java.util.ArrayList) List(java.util.List) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) RDN(org.bouncycastle.asn1.x500.RDN) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 18 with X500Name

use of sun.security.x509.X500Name 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 19 with X500Name

use of sun.security.x509.X500Name in project gitblit by gitblit.

the class X509Utils method newCertificateRevocationList.

/**
	 * Creates a new certificate revocation list (CRL).  This function will
	 * destroy any existing CRL file.
	 *
	 * @param caRevocationList
	 * @param storeFile
	 * @param keystorePassword
	 * @return
	 */
public static void newCertificateRevocationList(File caRevocationList, File caKeystoreFile, String caKeystorePassword) {
    try {
        // read the Gitblit CA key and certificate
        KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
        PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
        X509Certificate caCert = (X509Certificate) store.getCertificate(CA_ALIAS);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
        // build and sign CRL with CA private key
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509CRLHolder crl = crlBuilder.build(signer);
        File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(tmpFile);
            fos.write(crl.getEncoded());
            fos.flush();
            fos.close();
            if (caRevocationList.exists()) {
                caRevocationList.delete();
            }
            tmpFile.renameTo(caRevocationList);
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to create new certificate revocation list " + caRevocationList, e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) X509v2CRLBuilder(org.bouncycastle.cert.X509v2CRLBuilder) File(java.io.File)

Example 20 with X500Name

use of sun.security.x509.X500Name in project gitblit by gitblit.

the class X509Utils method newClientCertificate.

/**
	 * Creates a new client certificate PKCS#12 and PEM store.  Any existing
	 * stores are destroyed.
	 *
	 * @param clientMetadata a container for dynamic parameters needed for generation
	 * @param caKeystoreFile
	 * @param caKeystorePassword
	 * @param targetFolder
	 * @return
	 */
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
    try {
        KeyPair pair = newKeyPair();
        X500Name userDN = buildDistinguishedName(clientMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        // create a new certificate signed by the Gitblit CA certificate
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore, clientMetadata.notAfter, userDN, pair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        if (!StringUtils.isEmpty(clientMetadata.emailAddress)) {
            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        // confirm the validity of the user certificate
        userCert.checkValidity();
        userCert.verify(caCert.getPublicKey());
        userCert.getIssuerDN().equals(caCert.getSubjectDN());
        // verify user certificate chain
        verifyChain(userCert, caCert);
        targetFolder.mkdirs();
        // save certificate, stamped with unique name
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String id = date;
        File certFile = new File(targetFolder, id + ".cer");
        int count = 0;
        while (certFile.exists()) {
            id = date + "_" + Character.toString((char) (0x61 + count));
            certFile = new File(targetFolder, id + ".cer");
            count++;
        }
        // save user private key, user certificate and CA certificate to a PKCS#12 store
        File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
        if (p12File.exists()) {
            p12File.delete();
        }
        KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
        userStore.setKeyEntry(MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[] { userCert });
        userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
        saveKeyStore(p12File, userStore, clientMetadata.password);
        // save user private key, user certificate, and CA certificate to a PEM store
        File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
        if (pemFile.exists()) {
            pemFile.delete();
        }
        JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
        builder.setSecureRandom(new SecureRandom());
        PEMEncryptor pemEncryptor = builder.build(clientMetadata.password.toCharArray());
        JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(pemFile));
        pemWriter.writeObject(pair.getPrivate(), pemEncryptor);
        pemWriter.writeObject(userCert);
        pemWriter.writeObject(caCert);
        pemWriter.flush();
        pemWriter.close();
        // save certificate after successfully creating the key stores
        saveCertificate(userCert, certFile);
        // update serial number in metadata object
        clientMetadata.serialNumber = userCert.getSerialNumber().toString();
        return userCert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate client certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) FileWriter(java.io.FileWriter) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) PEMEncryptor(org.bouncycastle.openssl.PEMEncryptor) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) JcePEMEncryptorBuilder(org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder) KeyPair(java.security.KeyPair) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)54 X509Certificate (java.security.cert.X509Certificate)38 X500Name (sun.security.x509.X500Name)30 IOException (java.io.IOException)22 Date (java.util.Date)21 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)20 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)18 BigInteger (java.math.BigInteger)17 SecureRandom (java.security.SecureRandom)16 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)15 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)15 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)15 KeyPair (java.security.KeyPair)12 PrivateKey (java.security.PrivateKey)12 CertificateEncodingException (java.security.cert.CertificateEncodingException)12 RDN (org.bouncycastle.asn1.x500.RDN)12 KeyStore (java.security.KeyStore)11 ContentSigner (org.bouncycastle.operator.ContentSigner)11 ArrayList (java.util.ArrayList)10 GeneralName (org.bouncycastle.asn1.x509.GeneralName)10