Java Code Examples for java.security.cert.X509Certificate#getExtensionValue()

The following examples show how to use java.security.cert.X509Certificate#getExtensionValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TPMAttestationStatementValidator.java    From webauthn4j with Apache License 2.0 7 votes vote down vote up
private void validateX5c(TPMAttestationStatement attestationStatement, TPMSAttest certInfo, AuthenticatorData<RegistrationExtensionAuthenticatorOutput<?>> authenticatorData) {
    X509Certificate aikCert = attestationStatement.getX5c().getEndEntityAttestationCertificate().getCertificate();

    /// Verify the sig is a valid signature over certInfo using the attestation public key in aikCert with the algorithm specified in alg.
    String jcaName = getJcaName(attestationStatement.getAlg());
    Signature certInfoSignature = SignatureUtil.createSignature(jcaName);
    try {
        certInfoSignature.initVerify(aikCert.getPublicKey());
        certInfoSignature.update(certInfo.getBytes());
        if (!certInfoSignature.verify(attestationStatement.getSig())) {
            throw new BadAttestationStatementException("hash of certInfo doesn't match with sig.");
        }
    } catch (SignatureException | InvalidKeyException e) {
        throw new BadAttestationStatementException("Failed to validate the signature.", e);
    }

    /// Verify that aikCert meets the requirements in ยง8.3.1 TPM Attestation Statement Certificate Requirements.
    validateAikCert(aikCert);

    /// If aikCert contains an extension with OID 1 3 6 1 4 1 45724 1 1 4 (id-fido-gen-ce-aaguid) verify that the value of this extension matches the aaguid in authenticatorData.
    byte[] aaguidBytes = aikCert.getExtensionValue(ID_FIDO_GEN_CE_AAGUID);
    if (aaguidBytes != null && !Objects.equals(new AAGUID(aaguidBytes), authenticatorData.getAttestedCredentialData().getAaguid())) {
        throw new BadAttestationStatementException("AAGUID in aikCert doesn't match with that in authenticatorData");
    }
}
 
Example 2
Source File: StatusResponseManager.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtain the URI use by the {@code StatusResponseManager} during
 * lookups.
 *
 * This method takes into account not only the AIA extension from a
 * certificate to be checked, but also any default URI and possible
 * override settings for the response manager.
 *
 * @param cert the subject to get the responder URI from
 *
 * @return a {@code URI} containing the address to the OCSP responder,
 *      or {@code null} if no AIA extension exists in the certificate
 *      and no default responder has been configured.
 *
 * @throws NullPointerException if {@code cert} is {@code null}.
 */
URI getURI(X509Certificate cert) {
    Objects.requireNonNull(cert);

    if (cert.getExtensionValue(
            PKIXExtensions.OCSPNoCheck_Id.toString()) != null) {
        if (SSLLogger.isOn && SSLLogger.isOn("respmgr")) {
            SSLLogger.fine(
                "OCSP NoCheck extension found.  OCSP will be skipped");
        }
        return null;
    } else if (defaultResponder != null && respOverride) {
        if (SSLLogger.isOn && SSLLogger.isOn("respmgr")) {
          SSLLogger.fine(
                "Responder override: URI is " + defaultResponder);
        }
        return defaultResponder;
    } else {
        URI certURI = OCSP.getResponderURI(cert);
        return (certURI != null ? certURI : defaultResponder);
    }
}
 
Example 3
Source File: ValidateNC.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {

        X509Certificate anchorCert = getCertFromFile(certs[0]);
        byte [] nameConstraints = anchorCert.getExtensionValue("2.5.29.30");
        if (nameConstraints != null) {
            DerInputStream in = new DerInputStream(nameConstraints);
            nameConstraints = in.getOctetString();
        }
        TrustAnchor anchor = new TrustAnchor(anchorCert, nameConstraints);
        List list = new ArrayList();
        for (int i = 1; i < certs.length; i++) {
            list.add(0, getCertFromFile(certs[i]));
        }
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        path = cf.generateCertPath(list);

        anchors = Collections.singleton(anchor);
        params = new PKIXParameters(anchors);
        params.setRevocationEnabled(false);
    }
 
Example 4
Source File: SignedCertificateGeneratorTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void getSignedByIssuer_setsExtendedKeyUsage_ifPresent() throws Exception {
  X509Certificate generatedCertificate = subject
    .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters,
      certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate());

  assertThat(generatedCertificate.getExtensionValue(Extension.keyUsage.getId()), nullValue());

  certificateGenerationParameters = parametersContainsExtensions();

  generatedCertificate = subject
    .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters,
      certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate());
  final byte[] actualKeyUsage = generatedCertificate.getExtensionValue(Extension.extendedKeyUsage.getId());

  assertThat(Arrays.copyOfRange(actualKeyUsage, 2, actualKeyUsage.length),
    equalTo(certificateGenerationParameters.getExtendedKeyUsage().getEncoded()));
}
 
Example 5
Source File: ValidateNC.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {

        X509Certificate anchorCert = getCertFromFile(certs[0]);
        byte [] nameConstraints = anchorCert.getExtensionValue("2.5.29.30");
        if (nameConstraints != null) {
            DerInputStream in = new DerInputStream(nameConstraints);
            nameConstraints = in.getOctetString();
        }
        TrustAnchor anchor = new TrustAnchor(anchorCert, nameConstraints);
        List list = new ArrayList();
        for (int i = 1; i < certs.length; i++) {
            list.add(0, getCertFromFile(certs[i]));
        }
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        path = cf.generateCertPath(list);

        anchors = Collections.singleton(anchor);
        params = new PKIXParameters(anchors);
        params.setRevocationEnabled(false);
    }
 
Example 6
Source File: AdaptableX509CertSelector.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean matchSubjectKeyID(X509Certificate xcert) {
    if (ski == null) {
        return true;
    }
    try {
        byte[] extVal = xcert.getExtensionValue("2.5.29.14");
        if (extVal == null) {
            if (debug != null) {
                debug.println("AdaptableX509CertSelector.match: "
                    + "no subject key ID extension. Subject: "
                    + xcert.getSubjectX500Principal());
            }
            return true;
        }
        DerInputStream in = new DerInputStream(extVal);
        byte[] certSubjectKeyID = in.getOctetString();
        if (certSubjectKeyID == null ||
                !Arrays.equals(ski, certSubjectKeyID)) {
            if (debug != null) {
                debug.println("AdaptableX509CertSelector.match: "
                    + "subject key IDs don't match. "
                    + "Expected: " + Arrays.toString(ski) + " "
                    + "Cert's: " + Arrays.toString(certSubjectKeyID));
            }
            return false;
        }
    } catch (IOException ex) {
        if (debug != null) {
            debug.println("AdaptableX509CertSelector.match: "
                + "exception in subject key ID check");
        }
        return false;
    }
    return true;
}
 
Example 7
Source File: Parse.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void CRLDistributionPointsExtensionTest(String certStr)
        throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream is = new ByteArrayInputStream(certStr.getBytes());
    X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

    // oid for CRL Distribution Points = 2.5.29.31
    byte[] CDPExtBytes = cert.getExtensionValue("2.5.29.31");
    DerValue val = new DerValue(CDPExtBytes);
    byte[] data = val.getOctetString();
    CRLDistributionPointsExtension CDPExt
            = new CRLDistributionPointsExtension(false, data);
}
 
Example 8
Source File: XMLX509SKI.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @param cert
 * @return ski bytes from the given certificate
 *
 * @throws XMLSecurityException
 * @see java.security.cert.X509Extension#getExtensionValue(java.lang.String)
 */
public static byte[] getSKIBytesFromCert(X509Certificate cert)
    throws XMLSecurityException {

    if (cert.getVersion() < 3) {
        Object exArgs[] = { Integer.valueOf(cert.getVersion()) };
        throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
    }

    /*
     * Gets the DER-encoded OCTET string for the extension value
     * (extnValue) identified by the passed-in oid String. The oid
     * string is represented by a set of positive whole numbers
     * separated by periods.
     */
    byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID);
    if (extensionValue == null) {
        throw new XMLSecurityException("certificate.noSki.null");
    }

    /**
     * Strip away first four bytes from the extensionValue
     * The first two bytes are the tag and length of the extensionValue
     * OCTET STRING, and the next two bytes are the tag and length of
     * the ski OCTET STRING.
     */
    byte skidValue[] = new byte[extensionValue.length - 4];

    System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example 9
Source File: TimestampedSigner.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Examine the certificate for a Subject Information Access extension
 * (<a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280</a>).
 * The extension's <tt>accessMethod</tt> field should contain the object
 * identifier defined for timestamping: 1.3.6.1.5.5.7.48.3 and its
 * <tt>accessLocation</tt> field should contain an HTTP or HTTPS URL.
 *
 * @param tsaCertificate An X.509 certificate for the TSA.
 * @return An HTTP or HTTPS URI or null if none was found.
 */
public static URI getTimestampingURI(X509Certificate tsaCertificate) {

    if (tsaCertificate == null) {
        return null;
    }
    // Parse the extensions
    try {
        byte[] extensionValue =
            tsaCertificate.getExtensionValue(SUBJECT_INFO_ACCESS_OID);
        if (extensionValue == null) {
            return null;
        }
        DerInputStream der = new DerInputStream(extensionValue);
        der = new DerInputStream(der.getOctetString());
        DerValue[] derValue = der.getSequence(5);
        AccessDescription description;
        GeneralName location;
        URIName uri;
        for (int i = 0; i < derValue.length; i++) {
            description = new AccessDescription(derValue[i]);
            if (description.getAccessMethod()
                    .equals((Object)AD_TIMESTAMPING_Id)) {
                location = description.getAccessLocation();
                if (location.getType() == GeneralNameInterface.NAME_URI) {
                    uri = (URIName) location.getName();
                    if (uri.getScheme().equalsIgnoreCase("http") ||
                            uri.getScheme().equalsIgnoreCase("https")) {
                        return uri.getURI();
                    }
                }
            }
        }
    } catch (IOException ioe) {
        // ignore
    }
    return null;
}
 
Example 10
Source File: XMLX509SKI.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @param cert
 * @return ski bytes from the given certificate
 *
 * @throws XMLSecurityException
 * @see java.security.cert.X509Extension#getExtensionValue(java.lang.String)
 */
public static byte[] getSKIBytesFromCert(X509Certificate cert)
    throws XMLSecurityException {

    if (cert.getVersion() < 3) {
        Object exArgs[] = { Integer.valueOf(cert.getVersion()) };
        throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
    }

    /*
     * Gets the DER-encoded OCTET string for the extension value
     * (extnValue) identified by the passed-in oid String. The oid
     * string is represented by a set of positive whole numbers
     * separated by periods.
     */
    byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID);
    if (extensionValue == null) {
        throw new XMLSecurityException("certificate.noSki.null");
    }

    /**
     * Strip away first four bytes from the extensionValue
     * The first two bytes are the tag and length of the extensionValue
     * OCTET STRING, and the next two bytes are the tag and length of
     * the ski OCTET STRING.
     */
    byte skidValue[] = new byte[extensionValue.length - 4];

    System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example 11
Source File: X509Utils.java    From tigase-extension with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] getPublicKeyBlock(X509Certificate certificate) throws IOException {
    byte[] publicKeyExtData = certificate.getExtensionValue(SubjectPGPPublicKeyInfo.OID.getId());

    if (publicKeyExtData != null) {
        SubjectPGPPublicKeyInfo keyInfo = SubjectPGPPublicKeyInfo.getInstance(publicKeyExtData);

        return keyInfo.getPublicKeyData().getBytes();
    }

    return null;
}
 
Example 12
Source File: SubjectAlternativeNameImpl.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
public SubjectAlternativeNameImpl(X509Certificate cert) throws IOException {
	DNSNames = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.subjectAlternativeName.getId());
	if (extVal == null)
		return;
	GeneralNames gn = GeneralNames.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	GeneralName[] names = gn.getNames();
	for (GeneralName name : names) {
		if (name.getTagNo() == GeneralName.dNSName) {
			String dns = name.getName().toString();
			DNSNames.add(dns);
		}
	}
}
 
Example 13
Source File: AdaptableX509CertSelector.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private boolean matchSubjectKeyID(X509Certificate xcert) {
    if (ski == null) {
        return true;
    }
    try {
        byte[] extVal = xcert.getExtensionValue("2.5.29.14");
        if (extVal == null) {
            if (debug != null) {
                debug.println("AdaptableX509CertSelector.match: "
                    + "no subject key ID extension. Subject: "
                    + xcert.getSubjectX500Principal());
            }
            return true;
        }
        DerInputStream in = new DerInputStream(extVal);
        byte[] certSubjectKeyID = in.getOctetString();
        if (certSubjectKeyID == null ||
                !Arrays.equals(ski, certSubjectKeyID)) {
            if (debug != null) {
                debug.println("AdaptableX509CertSelector.match: "
                    + "subject key IDs don't match. "
                    + "Expected: " + Arrays.toString(ski) + " "
                    + "Cert's: " + Arrays.toString(certSubjectKeyID));
            }
            return false;
        }
    } catch (IOException ex) {
        if (debug != null) {
            debug.println("AdaptableX509CertSelector.match: "
                + "exception in subject key ID check");
        }
        return false;
    }
    return true;
}
 
Example 14
Source File: Parse.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void CRLDistributionPointsExtensionTest(String certStr)
        throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream is = new ByteArrayInputStream(certStr.getBytes());
    X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

    // oid for CRL Distribution Points = 2.5.29.31
    byte[] CDPExtBytes = cert.getExtensionValue("2.5.29.31");
    DerValue val = new DerValue(CDPExtBytes);
    byte[] data = val.getOctetString();
    CRLDistributionPointsExtension CDPExt
            = new CRLDistributionPointsExtension(false, data);
}
 
Example 15
Source File: Attestation.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
private ASN1Sequence getAttestationSequence(X509Certificate x509Cert)
        throws CertificateParsingException {
    byte[] attestationExtensionBytes = x509Cert.getExtensionValue(KEY_DESCRIPTION_OID);
    if (attestationExtensionBytes == null || attestationExtensionBytes.length == 0) {
        throw new CertificateParsingException(
                "Did not find extension with OID " + KEY_DESCRIPTION_OID);
    }
    return Asn1Utils.getAsn1SequenceFromBytes(attestationExtensionBytes);
}
 
Example 16
Source File: Parse.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void CRLDistributionPointsExtensionTest(String certStr)
        throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream is = new ByteArrayInputStream(certStr.getBytes());
    X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

    // oid for CRL Distribution Points = 2.5.29.31
    byte[] CDPExtBytes = cert.getExtensionValue("2.5.29.31");
    DerValue val = new DerValue(CDPExtBytes);
    byte[] data = val.getOctetString();
    CRLDistributionPointsExtension CDPExt
            = new CRLDistributionPointsExtension(false, data);
}
 
Example 17
Source File: Parse.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void CRLDistributionPointsExtensionTest(String certStr)
        throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream is = new ByteArrayInputStream(certStr.getBytes());
    X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

    // oid for CRL Distribution Points = 2.5.29.31
    byte[] CDPExtBytes = cert.getExtensionValue("2.5.29.31");
    DerValue val = new DerValue(CDPExtBytes);
    byte[] data = val.getOctetString();
    CRLDistributionPointsExtension CDPExt
            = new CRLDistributionPointsExtension(false, data);
}
 
Example 18
Source File: PackedAttestationStatementValidator.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
AAGUID extractAAGUIDFromAttestationCertificate(X509Certificate certificate) {
    byte[] extensionValue = certificate.getExtensionValue(ID_FIDO_GEN_CE_AAGUID);
    if (extensionValue == null) {
        return AAGUID.NULL;
    }
    try {
        Asn1OctetString envelope = new Asn1OctetString();
        envelope.decode(extensionValue);
        Asn1OctetString innerEnvelope = new Asn1OctetString();
        innerEnvelope.decode(envelope.getValue());
        return new AAGUID(UUIDUtil.fromBytes(innerEnvelope.getValue()));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 19
Source File: TimestampedSigner.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Examine the certificate for a Subject Information Access extension
 * (<a href="http://tools.ietf.org/html/rfc5280">RFC 5280</a>).
 * The extension's {@code accessMethod} field should contain the object
 * identifier defined for timestamping: 1.3.6.1.5.5.7.48.3 and its
 * {@code accessLocation} field should contain an HTTP or HTTPS URL.
 *
 * @param tsaCertificate An X.509 certificate for the TSA.
 * @return An HTTP or HTTPS URI or null if none was found.
 */
public static URI getTimestampingURI(X509Certificate tsaCertificate) {

    if (tsaCertificate == null) {
        return null;
    }
    // Parse the extensions
    try {
        byte[] extensionValue =
            tsaCertificate.getExtensionValue(SUBJECT_INFO_ACCESS_OID);
        if (extensionValue == null) {
            return null;
        }
        DerInputStream der = new DerInputStream(extensionValue);
        der = new DerInputStream(der.getOctetString());
        DerValue[] derValue = der.getSequence(5);
        AccessDescription description;
        GeneralName location;
        URIName uri;
        for (int i = 0; i < derValue.length; i++) {
            description = new AccessDescription(derValue[i]);
            if (description.getAccessMethod()
                    .equals((Object)AD_TIMESTAMPING_Id)) {
                location = description.getAccessLocation();
                if (location.getType() == GeneralNameInterface.NAME_URI) {
                    uri = (URIName) location.getName();
                    if (uri.getScheme().equalsIgnoreCase("http") ||
                            uri.getScheme().equalsIgnoreCase("https")) {
                        return uri.getURI();
                    }
                }
            }
        }
    } catch (IOException ioe) {
        // ignore
    }
    return null;
}
 
Example 20
Source File: TimestampedSigner.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Examine the certificate for a Subject Information Access extension
 * (<a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280</a>).
 * The extension's <tt>accessMethod</tt> field should contain the object
 * identifier defined for timestamping: 1.3.6.1.5.5.7.48.3 and its
 * <tt>accessLocation</tt> field should contain an HTTP or HTTPS URL.
 *
 * @param tsaCertificate An X.509 certificate for the TSA.
 * @return An HTTP or HTTPS URI or null if none was found.
 */
public static URI getTimestampingURI(X509Certificate tsaCertificate) {

    if (tsaCertificate == null) {
        return null;
    }
    // Parse the extensions
    try {
        byte[] extensionValue =
            tsaCertificate.getExtensionValue(SUBJECT_INFO_ACCESS_OID);
        if (extensionValue == null) {
            return null;
        }
        DerInputStream der = new DerInputStream(extensionValue);
        der = new DerInputStream(der.getOctetString());
        DerValue[] derValue = der.getSequence(5);
        AccessDescription description;
        GeneralName location;
        URIName uri;
        for (int i = 0; i < derValue.length; i++) {
            description = new AccessDescription(derValue[i]);
            if (description.getAccessMethod()
                    .equals((Object)AD_TIMESTAMPING_Id)) {
                location = description.getAccessLocation();
                if (location.getType() == GeneralNameInterface.NAME_URI) {
                    uri = (URIName) location.getName();
                    if (uri.getScheme().equalsIgnoreCase("http") ||
                            uri.getScheme().equalsIgnoreCase("https")) {
                        return uri.getURI();
                    }
                }
            }
        }
    } catch (IOException ioe) {
        // ignore
    }
    return null;
}