Search in sources :

Example 36 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project keywhiz by square.

the class ClientAuthenticator method getSpiffeIdFromCertificate.

static Optional<URI> getSpiffeIdFromCertificate(X509Certificate cert) {
    Collection<List<?>> sans;
    try {
        sans = cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        logger.warn("Error parsing SANs from principal", e);
        return Optional.empty();
    }
    if (sans == null || sans.isEmpty()) {
        return Optional.empty();
    }
    // The sub-lists returned by getSubjectAlternativeNames have an integer for the first
    // entry, representing a field, and the value as a string as the second entry.
    List<String> providedUris = sans.stream().filter(sanPair -> sanPair.get(0).equals(URINAME_SAN)).map(sanPair -> (String) sanPair.get(1)).collect(Collectors.toUnmodifiableList());
    List<String> spiffeUriNames = spiffeUriNames(providedUris);
    if (spiffeUriNames.size() > 1) {
        logger.warn("Got multiple SPIFFE URIs from certificate: {}", spiffeUriNames);
        return Optional.empty();
    } else if (spiffeUriNames.size() == 1 && providedUris.size() > 1) {
        logger.warn("Multiple URIs are not allowed in a certificate that includes a SPIFFE URI (URIs: {})", providedUris);
        return Optional.empty();
    }
    return spiffeUriNames.stream().findFirst().flatMap(uri -> {
        try {
            return Optional.of(new URI(uri));
        } catch (URISyntaxException e) {
            logger.warn(format("Error parsing SPIFFE URI (%s) from certificate as a URI", uri), e);
            return Optional.empty();
        }
    });
}
Also used : X509Certificate(java.security.cert.X509Certificate) Logger(org.slf4j.Logger) ClientDAO(keywhiz.service.daos.ClientDAO) RDN(org.bouncycastle.asn1.x500.RDN) ClientAuthConfig(keywhiz.service.config.ClientAuthConfig) IETFUtils(org.bouncycastle.asn1.x500.style.IETFUtils) URISyntaxException(java.net.URISyntaxException) Collection(java.util.Collection) CertificatePrincipal(keywhiz.auth.mutualssl.CertificatePrincipal) SpiffePrincipal(keywhiz.auth.mutualssl.SpiffePrincipal) LoggerFactory(org.slf4j.LoggerFactory) CertificateParsingException(java.security.cert.CertificateParsingException) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) List(java.util.List) X500Name(org.bouncycastle.asn1.x500.X500Name) Principal(java.security.Principal) Optional(java.util.Optional) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) URI(java.net.URI) Client(keywhiz.api.model.Client) CertificateParsingException(java.security.cert.CertificateParsingException) List(java.util.List) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 37 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project Openfire by igniterealtime.

the class IdentityStore method generateCSR.

/**
 * Creates a Certificate Signing Request based on the private key and certificate identified by the provided alias.
 *
 * When the alias does not identify a private key and/or certificate, this method will throw an exception.
 *
 * The certificate that is identified by the provided alias can be an unsigned certificate, but also a certificate
 * that is already signed. The latter implies that the generated request is a request for certificate renewal.
 *
 * An invocation of this method does not change the state of the underlying store.
 *
 * @param alias An identifier for a private key / certificate in this store (cannot be null).
 * @return A PEM-encoded Certificate Signing Request (never null).
 * @throws CertificateStoreConfigException if there was a problem generating the CSR
 */
public String generateCSR(String alias) throws CertificateStoreConfigException {
    // Input validation
    if (alias == null || alias.trim().isEmpty()) {
        throw new IllegalArgumentException("Argument 'alias' cannot be null or an empty String.");
    }
    alias = alias.trim();
    try {
        if (!store.containsAlias(alias)) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': the alias does not exist in the store.");
        }
        final Certificate certificate = store.getCertificate(alias);
        if (certificate == null || (!(certificate instanceof X509Certificate))) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': there is no corresponding certificate in the store, or it is not an X509 certificate.");
        }
        final Key key = store.getKey(alias, configuration.getPassword());
        if (key == null || (!(key instanceof PrivateKey))) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': there is no corresponding key in the store, or it is not a private key.");
        }
        final String pemCSR = CertificateManager.createSigningRequest((X509Certificate) certificate, (PrivateKey) key);
        return pemCSR;
    } catch (IOException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | OperatorCreationException | CertificateParsingException e) {
        throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "'", e);
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 38 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project Openfire by igniterealtime.

the class CertificateManager method createSigningRequest.

/**
 * Creates and returns the content of a new singing request for the specified certificate. Signing
 * requests are required by Certificate Authorities as part of their signing process. The signing request
 * contains information about the certificate issuer, subject DN, subject alternative names and public key.
 * Private keys are not included. After the Certificate Authority verified and signed the certificate a new
 * certificate is going to be returned.
 *
 * @param cert the certificate to create a signing request.
 * @param privKey the private key of the certificate.
 * @return the content of a new singing request for the specified certificate.
 * @throws OperatorCreationException if there was a problem creating the CSR
 * @throws IOException if there was a problem creating the CSR
 * @throws CertificateParsingException if there was a problem creating the CSR
 */
public static String createSigningRequest(X509Certificate cert, PrivateKey privKey) throws OperatorCreationException, IOException, CertificateParsingException {
    JcaPKCS10CertificationRequestBuilder csrBuilder = new // 
    JcaPKCS10CertificationRequestBuilder(// 
    cert.getSubjectX500Principal(), // 
    cert.getPublicKey());
    // Add SubjectAlternativeNames (SANs)
    final ASN1EncodableVector subjectAlternativeNames = new ASN1EncodableVector();
    final Collection<List<?>> certSans = cert.getSubjectAlternativeNames();
    if (certSans != null) {
        for (final List<?> certSan : certSans) {
            final int nameType = (Integer) certSan.get(0);
            // this is either a string, or a byte-array that represents the ASN.1 DER encoded form.
            final Object value = certSan.get(1);
            switch(nameType) {
                case 0:
                    // OtherName: search for "id-on-xmppAddr" or 'sRVName' or 'userPrincipalName'
                    try (final ASN1InputStream decoder = new ASN1InputStream((byte[]) value)) {
                        // By specification, OtherName instances must always be an ASN.1 Sequence.
                        final ASN1Primitive object = decoder.readObject();
                        final ASN1Sequence otherNameSeq = (ASN1Sequence) object;
                        // By specification, an OtherName instance consists of:
                        // - the type-id (which is an Object Identifier), followed by:
                        // - a tagged value, of which the tag number is 0 (zero) and the value is defined by the type-id.
                        final ASN1ObjectIdentifier typeId = (ASN1ObjectIdentifier) otherNameSeq.getObjectAt(0);
                        final ASN1TaggedObject taggedValue = (ASN1TaggedObject) otherNameSeq.getObjectAt(1);
                        final int tagNo = taggedValue.getTagNo();
                        if (tagNo != 0) {
                            throw new IllegalArgumentException("subjectAltName 'otherName' sequence's second object is expected to be a tagged value of which the tag number is 0. The tag number that was detected: " + tagNo);
                        }
                        subjectAlternativeNames.add(new DERTaggedObject(false, GeneralName.otherName, new DERSequence(new ASN1Encodable[] { typeId, taggedValue })));
                    } catch (Exception e) {
                        Log.warn("Unable to parse certificate SAN 'otherName' value", e);
                    }
                    break;
                case 2:
                    // DNS
                    subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, (String) value));
                    break;
                case 6:
                    // URI
                    subjectAlternativeNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, (String) value));
                    break;
                default:
                    // Not applicable to XMPP, so silently ignore them
                    break;
            }
        }
    }
    final GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(subjectAlternativeNames));
    final ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    String signatureAlgorithm = "SHA256WITH" + cert.getPublicKey().getAlgorithm();
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey);
    PKCS10CertificationRequest csr = csrBuilder.build(signer);
    StringWriter string = new StringWriter();
    PemWriter pemWriter = new PemWriter(string);
    PemObjectGenerator objGen = new MiscPEMGenerator(csr);
    pemWriter.writeObject(objGen);
    pemWriter.close();
    return string.toString();
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PemWriter(org.bouncycastle.util.io.pem.PemWriter) ContentSigner(org.bouncycastle.operator.ContentSigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertException(org.bouncycastle.cert.CertException) CertificateParsingException(java.security.cert.CertificateParsingException) PKCSException(org.bouncycastle.pkcs.PKCSException) CertificateException(java.security.cert.CertificateException) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) BigInteger(java.math.BigInteger) JcaMiscPEMGenerator(org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 39 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project qpid-broker-j by apache.

the class SSLUtil method verifyHostname.

public static void verifyHostname(final String hostnameExpected, final X509Certificate cert) {
    try {
        SortedSet<String> names = getNamesFromCert(cert);
        if (names.isEmpty()) {
            throw new TransportException("SSL hostname verification failed. Certificate for did not contain CN or DNS subjectAlt");
        }
        boolean match = verifyHostname(hostnameExpected, names);
        if (!match) {
            throw new TransportException("SSL hostname verification failed." + " Expected : " + hostnameExpected + " Found in cert : " + names);
        }
    } catch (InvalidNameException e) {
        Principal p = cert.getSubjectDN();
        String dn = p.getName();
        throw new TransportException("SSL hostname verification failed. Could not parse name " + dn, e);
    } catch (CertificateParsingException e) {
        throw new TransportException("SSL hostname verification failed. Could not parse certificate:  " + e.getMessage(), e);
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) InvalidNameException(javax.naming.InvalidNameException) TransportException(org.apache.qpid.server.transport.TransportException) Principal(java.security.Principal)

Example 40 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project robovm by robovm.

the class X509V1CertificateGenerator method generateJcaObject.

private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) throws CertificateEncodingException {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tbsCert);
    v.add(sigAlgId);
    v.add(new DERBitString(signature));
    try {
        return new X509CertificateObject(Certificate.getInstance(new DERSequence(v)));
    } catch (CertificateParsingException e) {
        throw new ExtCertificateEncodingException("exception producing certificate object", e);
    }
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) CertificateParsingException(java.security.cert.CertificateParsingException) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DERBitString(org.bouncycastle.asn1.DERBitString)

Aggregations

CertificateParsingException (java.security.cert.CertificateParsingException)72 List (java.util.List)25 IOException (java.io.IOException)18 ArrayList (java.util.ArrayList)18 X509Certificate (java.security.cert.X509Certificate)15 CertificateException (java.security.cert.CertificateException)13 Collection (java.util.Collection)12 X500Principal (javax.security.auth.x500.X500Principal)11 BigInteger (java.math.BigInteger)8 InvalidKeyException (java.security.InvalidKeyException)7 HashMap (java.util.HashMap)7 DERIA5String (org.bouncycastle.asn1.DERIA5String)7 DEROctetString (org.bouncycastle.asn1.DEROctetString)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 NoSuchProviderException (java.security.NoSuchProviderException)6 SignatureException (java.security.SignatureException)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 CertificateExpiredException (java.security.cert.CertificateExpiredException)6 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)6 GeneralName (org.bouncycastle.asn1.x509.GeneralName)6