Search in sources :

Example 26 with GeneralName

use of com.github.zhenwei.core.asn1.x509.GeneralName in project oxAuth by GluuFederation.

the class OCSPCertificateVerifier method getOCSPUrl.

@SuppressWarnings({ "deprecation", "resource" })
private String getOCSPUrl(X509Certificate certificate) throws IOException {
    ASN1Primitive obj;
    try {
        obj = getExtensionValue(certificate, Extension.authorityInfoAccess.getId());
    } catch (IOException ex) {
        log.error("Failed to get OCSP URL", ex);
        return null;
    }
    if (obj == null) {
        return null;
    }
    AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(obj);
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {
        boolean correctAccessMethod = accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod);
        if (!correctAccessMethod) {
            continue;
        }
        GeneralName name = accessDescription.getAccessLocation();
        if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
            continue;
        }
        DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
        return derStr.getString();
    }
    return null;
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) DERIA5String(org.bouncycastle.asn1.DERIA5String) AccessDescription(org.bouncycastle.asn1.x509.AccessDescription) IOException(java.io.IOException) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 27 with GeneralName

use of com.github.zhenwei.core.asn1.x509.GeneralName 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)

Example 28 with GeneralName

use of com.github.zhenwei.core.asn1.x509.GeneralName in project j2objc by google.

the class OCSP method getResponderURI.

static URI getResponderURI(X509CertImpl certImpl) {
    // Examine the certificate's AuthorityInfoAccess extension
    AuthorityInfoAccessExtension aia = certImpl.getAuthorityInfoAccessExtension();
    if (aia == null) {
        return null;
    }
    List<AccessDescription> descriptions = aia.getAccessDescriptions();
    for (AccessDescription description : descriptions) {
        if (description.getAccessMethod().equals((Object) AccessDescription.Ad_OCSP_Id)) {
            GeneralName generalName = description.getAccessLocation();
            if (generalName.getType() == GeneralNameInterface.NAME_URI) {
                URIName uri = (URIName) generalName.getName();
                return uri.getURI();
            }
        }
    }
    return null;
}
Also used : AuthorityInfoAccessExtension(sun.security.x509.AuthorityInfoAccessExtension) AccessDescription(sun.security.x509.AccessDescription) GeneralName(sun.security.x509.GeneralName) URIName(sun.security.x509.URIName)

Example 29 with GeneralName

use of com.github.zhenwei.core.asn1.x509.GeneralName in project acme4j by shred.

the class CSRBuilder method sign.

/**
 * Signs the completed CSR.
 *
 * @param keypair
 *            {@link KeyPair} to sign the CSR with
 */
public void sign(KeyPair keypair) throws IOException {
    Objects.requireNonNull(keypair, "keypair");
    if (namelist.isEmpty() && iplist.isEmpty()) {
        throw new IllegalStateException("No domain or IP address was set");
    }
    try {
        int ix = 0;
        GeneralName[] gns = new GeneralName[namelist.size() + iplist.size()];
        for (String name : namelist) {
            gns[ix++] = new GeneralName(GeneralName.dNSName, name);
        }
        for (InetAddress ip : iplist) {
            gns[ix++] = new GeneralName(GeneralName.iPAddress, ip.getHostAddress());
        }
        GeneralNames subjectAltName = new GeneralNames(gns);
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());
        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
        PrivateKey pk = keypair.getPrivate();
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(pk instanceof ECKey ? EC_SIGNATURE_ALG : SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);
        csr = p10Builder.build(signer);
    } catch (OperatorCreationException ex) {
        throw new IOException("Could not generate CSR", ex);
    }
}
Also used : JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) ECKey(java.security.interfaces.ECKey) IOException(java.io.IOException) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InetAddress(java.net.InetAddress)

Example 30 with GeneralName

use of com.github.zhenwei.core.asn1.x509.GeneralName in project acme4j by shred.

the class SMIMECSRBuilder method sign.

/**
 * Signs the completed S/MIME CSR.
 *
 * @param keypair
 *            {@link KeyPair} to sign the CSR with
 */
public void sign(KeyPair keypair) throws IOException {
    requireNonNull(keypair, "keypair");
    if (emaillist.isEmpty()) {
        throw new IllegalStateException("No email address was set");
    }
    try {
        int ix = 0;
        GeneralName[] gns = new GeneralName[emaillist.size()];
        for (InternetAddress email : emaillist) {
            gns[ix++] = new GeneralName(GeneralName.rfc822Name, email.getAddress());
        }
        GeneralNames subjectAltName = new GeneralNames(gns);
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());
        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
        KeyUsage keyUsage = new KeyUsage(keyUsageType.getKeyUsageBits());
        extensionsGenerator.addExtension(Extension.keyUsage, true, keyUsage);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
        PrivateKey pk = keypair.getPrivate();
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(pk instanceof ECKey ? EC_SIGNATURE_ALG : SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);
        csr = p10Builder.build(signer);
    } catch (OperatorCreationException ex) {
        throw new IOException("Could not generate CSR", ex);
    }
}
Also used : InternetAddress(jakarta.mail.internet.InternetAddress) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ECKey(java.security.interfaces.ECKey) IOException(java.io.IOException) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Aggregations

GeneralName (org.bouncycastle.asn1.x509.GeneralName)238 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)117 IOException (java.io.IOException)112 ArrayList (java.util.ArrayList)76 X500Name (org.bouncycastle.asn1.x500.X500Name)56 DERIA5String (org.bouncycastle.asn1.DERIA5String)53 X509Certificate (java.security.cert.X509Certificate)52 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)48 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)47 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)42 BigInteger (java.math.BigInteger)40 List (java.util.List)40 ContentSigner (org.bouncycastle.operator.ContentSigner)40 DEROctetString (org.bouncycastle.asn1.DEROctetString)37 Date (java.util.Date)31 X500Principal (javax.security.auth.x500.X500Principal)31 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)31 GeneralName (com.github.zhenwei.core.asn1.x509.GeneralName)30 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)29 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)29