Search in sources :

Example 6 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project supply-chain-tools by secure-device-onboard.

the class OnDieSignatureValidator method checkRevocations.

private boolean checkRevocations(List<Certificate> certificateList) {
    // Check revocations first.
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        for (Certificate cert : certificateList) {
            X509Certificate x509cert = (X509Certificate) cert;
            X509CertificateHolder certHolder = new X509CertificateHolder(x509cert.getEncoded());
            CRLDistPoint cdp = CRLDistPoint.fromExtensions(certHolder.getExtensions());
            if (cdp != null) {
                DistributionPoint[] distPoints = cdp.getDistributionPoints();
                for (DistributionPoint dp : distPoints) {
                    GeneralName[] generalNames = GeneralNames.getInstance(dp.getDistributionPoint().getName()).getNames();
                    for (GeneralName generalName : generalNames) {
                        byte[] crlBytes = onDieCache.getCertOrCrl(generalName.toString());
                        if (crlBytes == null) {
                            LoggerFactory.getLogger(getClass()).error("CRL ({}) not found in cache for cert: {}", generalName.getName().toString(), x509cert.getIssuerX500Principal().getName());
                            return false;
                        } else {
                            CRL crl = certificateFactory.generateCRL(new ByteArrayInputStream(crlBytes));
                            if (crl.isRevoked(cert)) {
                                return false;
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException | CertificateException | CRLException ex) {
        return false;
    }
    return true;
}
Also used : CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) CRL(java.security.cert.CRL) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) CRLException(java.security.cert.CRLException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 7 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project ca3sCore by kuehne-trustable-de.

the class ScepServletImpl method insertSANs.

private void insertSANs(ScepOrder scepOrder, final PKCS10CertificationRequest csr) {
    Set<GeneralName> generalNameSet = CSRUtil.getSANList(csr.getAttributes());
    String allSans = "";
    LOGGER.debug("putting SANs into ScepOrderAttributes");
    for (GeneralName gName : generalNameSet) {
        String sanValue = gName.getName().toString();
        if (GeneralName.otherName == gName.getTagNo()) {
            sanValue = "--other value--";
        }
        if (allSans.length() > 0) {
            allSans += ";";
        }
        allSans += sanValue;
        scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_SAN, sanValue, true);
        if (GeneralName.dNSName == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "DNS:" + sanValue, true);
        } else if (GeneralName.iPAddress == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "IP:" + sanValue, true);
        } else if (GeneralName.ediPartyName == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "EDI:" + sanValue, true);
        } else if (GeneralName.otherName == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "other:" + sanValue, true);
        } else if (GeneralName.registeredID == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "regID:" + sanValue, true);
        } else if (GeneralName.rfc822Name == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "rfc822:" + sanValue, true);
        } else if (GeneralName.uniformResourceIdentifier == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "URI:" + sanValue, true);
        } else if (GeneralName.x400Address == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "X400:" + sanValue, true);
        } else if (GeneralName.directoryName == gName.getTagNo()) {
            scepOrderUtil.setOrderAttribute(scepOrder, CsrAttribute.ATTRIBUTE_TYPED_SAN, "DirName:" + sanValue, true);
        } else {
            LOGGER.info("unexpected name / tag '{}' in SANs", gName.getTagNo());
        }
    }
}
Also used : GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 8 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project identity-credential by google.

the class CertificateGenerator method generateCertificate.

static X509Certificate generateCertificate(DataMaterial data, CertificateMaterial certMaterial, KeyMaterial keyMaterial) throws CertIOException, CertificateException, OperatorCreationException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    Optional<X509Certificate> issuerCert = keyMaterial.issuerCertificate();
    X500Name subjectDN = new X500Name(data.subjectDN());
    // doesn't work, get's reordered
    // issuerCert.isPresent() ? new X500Name(issuerCert.get().getSubjectX500Principal().getName()) : subjectDN;
    X500Name issuerDN = new X500Name(data.issuerDN());
    ContentSigner contentSigner = new JcaContentSignerBuilder(keyMaterial.signingAlgorithm()).build(keyMaterial.signingKey());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, certMaterial.serialNumber(), certMaterial.startDate(), certMaterial.endDate(), subjectDN, keyMaterial.publicKey());
    // Extensions --------------------------
    JcaX509ExtensionUtils jcaX509ExtensionUtils;
    try {
        jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    if (issuerCert.isPresent()) {
        try {
            // adds 3 more fields, not present in other cert
            // AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get());
            AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get().getPublicKey());
            certBuilder.addExtension(Extension.authorityKeyIdentifier, NOT_CRITICAL, authorityKeyIdentifier);
        } catch (IOException e) {
            // CertificateEncodingException |
            throw new RuntimeException(e);
        }
    }
    SubjectKeyIdentifier subjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyMaterial.publicKey());
    certBuilder.addExtension(Extension.subjectKeyIdentifier, NOT_CRITICAL, subjectKeyIdentifier);
    KeyUsage keyUsage = new KeyUsage(certMaterial.keyUsage());
    certBuilder.addExtension(Extension.keyUsage, CRITICAL, keyUsage);
    // IssuerAlternativeName
    Optional<String> issuerAlternativeName = data.issuerAlternativeName();
    if (issuerAlternativeName.isPresent()) {
        GeneralNames issuerAltName = new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, issuerAlternativeName.get()));
        certBuilder.addExtension(Extension.issuerAlternativeName, NOT_CRITICAL, issuerAltName);
    }
    // Basic Constraints
    int pathLengthConstraint = certMaterial.pathLengthConstraint();
    if (pathLengthConstraint != CertificateMaterial.PATHLENGTH_NOT_A_CA) {
        // TODO doesn't work for certificate chains != 2 in size
        BasicConstraints basicConstraints = new BasicConstraints(pathLengthConstraint);
        certBuilder.addExtension(Extension.basicConstraints, CRITICAL, basicConstraints);
    }
    Optional<String> extendedKeyUsage = certMaterial.extendedKeyUsage();
    if (extendedKeyUsage.isPresent()) {
        KeyPurposeId keyPurpose = KeyPurposeId.getInstance(new ASN1ObjectIdentifier(extendedKeyUsage.get()));
        ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(new KeyPurposeId[] { keyPurpose });
        certBuilder.addExtension(Extension.extendedKeyUsage, CRITICAL, extKeyUsage);
    }
    // DEBUG setProvider(bcProvider) removed before getCertificate
    return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Provider(java.security.Provider) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 9 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project wildfly-elytron by wildfly-security.

the class AcmeClientSpi method obtainCertificateChain.

/**
 * Obtain a certificate chain using the given ACME account.
 *
 * @param account the ACME account information to use (must not be {@code null})
 * @param staging whether or not the staging server URL should be used
 * @param keyAlgorithmName the optional key algorithm name to use when generating the key pair (may be {@code null})
 * @param keySize the optional key size to use when generating the key pair (-1 to indicate that the default key size should be used)
 * @param domainNames the domain names to request the certificate for (must not be {@code null})
 * @return the X509 certificate chain and private key
 * @throws AcmeException if an occur occurs while attempting to obtain the certificate
 */
public X509CertificateChainAndSigningKey obtainCertificateChain(AcmeAccount account, boolean staging, String keyAlgorithmName, int keySize, String... domainNames) throws AcmeException {
    Assert.checkNotNullParam("account", account);
    Assert.checkNotNullParam("domainNames", domainNames);
    final LinkedHashSet<String> domainNamesSet = getDomainNames(domainNames);
    // create a new order
    final String newOrderUrl = getResourceUrl(account, AcmeResource.NEW_ORDER, staging).toString();
    JsonArrayBuilder identifiersBuilder = Json.createArrayBuilder();
    for (String domainName : domainNamesSet) {
        JsonObject identifier = Json.createObjectBuilder().add(TYPE, DNS).add(VALUE, domainName).build();
        identifiersBuilder.add(identifier);
    }
    JsonObjectBuilder payloadBuilder = Json.createObjectBuilder().add(IDENTIFIERS, identifiersBuilder.build());
    HttpURLConnection connection = sendPostRequestWithRetries(account, staging, newOrderUrl, false, getEncodedJson(payloadBuilder.build()), HttpURLConnection.HTTP_CREATED);
    final String orderUrl = getLocation(connection, ORDER);
    JsonObject jsonResponse = getJsonResponse(connection);
    final String finalizeOrderUrl = jsonResponse.getString(FINALIZE);
    final JsonArray authorizationsArray = jsonResponse.getJsonArray(AUTHORIZATIONS);
    final List<String> authorizationUrls = new ArrayList<>(authorizationsArray.size());
    for (JsonString authorization : authorizationsArray.getValuesAs(JsonString.class)) {
        authorizationUrls.add(authorization.getString());
    }
    // respond to challenges for each authorization resource
    List<AcmeChallenge> selectedChallenges = new ArrayList<>(authorizationUrls.size());
    try {
        for (String authorizationUrl : authorizationUrls) {
            connection = sendPostAsGetRequest(account, staging, authorizationUrl, JSON_CONTENT_TYPE, HttpURLConnection.HTTP_OK);
            jsonResponse = getJsonResponse(connection);
            AcmeChallenge selectedChallenge = respondToChallenges(account, staging, jsonResponse);
            if (selectedChallenge != null) {
                selectedChallenges.add(selectedChallenge);
            }
        }
        // poll the authorization resources until server has finished validating the challenge responses
        for (String authorizationUrl : authorizationUrls) {
            jsonResponse = pollResourceUntilFinalized(account, staging, authorizationUrl);
            if (!jsonResponse.getString(STATUS).equals(VALID)) {
                throw acme.challengeResponseFailedValidationByAcmeServer();
            }
        }
        // create and submit a CSR now that we've fulfilled the server's requirements
        List<GeneralName> generalNames = new ArrayList<>(domainNamesSet.size());
        for (String domainName : domainNamesSet) {
            generalNames.add(new GeneralName.DNSName(domainName));
        }
        X500PrincipalBuilder principalBuilder = new X500PrincipalBuilder();
        principalBuilder.addItem(X500AttributeTypeAndValue.create(X500.OID_AT_COMMON_NAME, ASN1Encodable.ofUtf8String(((GeneralName.DNSName) generalNames.get(0)).getName())));
        X500Principal dn = principalBuilder.build();
        if (keyAlgorithmName == null) {
            keyAlgorithmName = DEFAULT_KEY_ALGORITHM_NAME;
        }
        if (keySize == -1) {
            if (keyAlgorithmName.equals("EC")) {
                keySize = DEFAULT_EC_KEY_SIZE;
            } else {
                keySize = DEFAULT_KEY_SIZE;
            }
        }
        SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder().setDn(dn).setKeyAlgorithmName(keyAlgorithmName).setKeySize(keySize).build();
        PKCS10CertificateSigningRequest.Builder csrBuilder = PKCS10CertificateSigningRequest.builder().setCertificate(selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate()).setSigningKey(selfSignedX509CertificateAndSigningKey.getSigningKey()).setSubjectDn(dn);
        csrBuilder.addExtension(new SubjectAlternativeNamesExtension(false, generalNames));
        payloadBuilder = Json.createObjectBuilder().add(CSR, base64UrlEncode(csrBuilder.build().getEncoded()));
        connection = sendPostRequestWithRetries(account, staging, finalizeOrderUrl, false, getEncodedJson(payloadBuilder.build()), HttpURLConnection.HTTP_OK);
        // poll the order resource until the server has made the certificate chain available
        jsonResponse = pollResourceUntilFinalized(account, staging, orderUrl);
        if (!jsonResponse.getString(STATUS).equals(VALID)) {
            throw acme.noCertificateWillBeIssuedByAcmeServer();
        }
        // download the certificate chain
        String certificateUrl = getOptionalJsonString(jsonResponse, CERTIFICATE);
        if (certificateUrl == null) {
            throw acme.noCertificateUrlProvidedByAcmeServer();
        }
        connection = sendPostAsGetRequest(account, staging, certificateUrl, PEM_CERTIFICATE_CHAIN_CONTENT_TYPE, HttpURLConnection.HTTP_OK);
        X509Certificate[] certificateChain = getPemCertificateChain(connection);
        PrivateKey privateKey = selfSignedX509CertificateAndSigningKey.getSigningKey();
        return new X509CertificateChainAndSigningKey(certificateChain, privateKey);
    } finally {
        // clean up
        for (AcmeChallenge challenge : selectedChallenges) {
            cleanupAfterChallenge(account, challenge);
        }
    }
}
Also used : PrivateKey(java.security.PrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) ArrayList(java.util.ArrayList) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) SubjectAlternativeNamesExtension(org.wildfly.security.x500.cert.SubjectAlternativeNamesExtension) HttpURLConnection(java.net.HttpURLConnection) PKCS10CertificateSigningRequest(org.wildfly.security.x500.cert.PKCS10CertificateSigningRequest) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) SelfSignedX509CertificateAndSigningKey(org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey) X509Certificate(java.security.cert.X509Certificate) JsonArray(javax.json.JsonArray) X509CertificateChainAndSigningKey(org.wildfly.security.x500.cert.X509CertificateChainAndSigningKey) X500Principal(javax.security.auth.x500.X500Principal) JsonString(javax.json.JsonString) GeneralName(org.wildfly.security.x500.GeneralName) X500PrincipalBuilder(org.wildfly.security.x500.X500PrincipalBuilder)

Example 10 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project wildfly-elytron by wildfly-security.

the class AuthorityKeyIdentifierExtension method encodeTo.

public void encodeTo(final ASN1Encoder encoder) {
    encoder.startSequence();
    if (keyIdentifier != null) {
        encoder.encodeImplicit(0);
        encoder.encodeOctetString(keyIdentifier);
    }
    if (generalNames != null && !generalNames.isEmpty()) {
        encoder.encodeImplicit(1);
        encoder.startSequence();
        for (GeneralName generalName : generalNames) {
            generalName.encodeTo(encoder);
        }
        encoder.endSequence();
    }
    if (serialNumber != null) {
        encoder.encodeImplicit(2);
        encoder.encodeInteger(serialNumber);
    }
    encoder.endSequence();
}
Also used : GeneralName(org.wildfly.security.x500.GeneralName)

Aggregations

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