Search in sources :

Example 81 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project Spark by igniterealtime.

the class SparkTrustManager method checkBasicConstraints.

/**
 * Checks the validity of the BasicConstraints extension of each certificate in the chain.
 *
 * Each certificate is assumed to have a BasicConstraints extension, with the exception of the leaf (end-entity)
 * certificate, which _can_ have a certificate.
 *
 * All non-leaf certificates must have the cA field set to 'true'.
 *
 * The pathLen is valid: it defines the maximum amount of intermediate certificates between the CA and the leaf
 * certificate. The leaf certificate itself is not included in the count (eg: a value of 'one' would allow for a
 * chain length of three: the leaf, one intermediate, and the root (where the value of 'one' is defined).
 *
 * This method assumes that the provided chain is in order, where the first chain is the end-entity / leaf certificate.
 *
 * The trust anchor / root CA should not be part of the certPath chain.
 *
 * @param chain The certificate chain, possibly incomplete.
 * @param trustAnchor the root CA certificate.
 * @throws CertificateException When the BasicConstraint verification fails.
 */
private void checkBasicConstraints(CertPath chain, X509Certificate trustAnchor) throws CertificateException {
    // Intentionally skipping over the first certificate, which is the end-entity certificate.
    for (int i = 1; i < chain.getCertificates().size(); i++) {
        final X509Certificate cert = (X509Certificate) chain.getCertificates().get(i);
        // The amount of certificates between the current certificate and the end-entity certificate cannot
        // exceed the value of pathLenConstraint (if the CA flag is not set, -1 will be returned)
        final int pathLenConstraint = cert.getBasicConstraints();
        final int certsSeparatingThisCertFromEndEntity = i - 1;
        if (certsSeparatingThisCertFromEndEntity > pathLenConstraint) {
            throw new CertificateException("Certificate number " + i + " in the chain failed the BasicConstraints check: " + (pathLenConstraint == -1 ? "CA flag not set" : "pathLenConstraint to small (was: " + pathLenConstraint + " needed:" + certsSeparatingThisCertFromEndEntity + ")"));
        }
    }
    // Explicitly check the trustAnchor (as it should not be in the chain)
    final int pathLenConstraint = trustAnchor.getBasicConstraints();
    final int certsSeparatingThisCertFromEndEntity = chain.getCertificates().size() - 1;
    if (certsSeparatingThisCertFromEndEntity > pathLenConstraint) {
        throw new CertificateException("Trust anchor of the chain failed the BasicConstraints check: " + (pathLenConstraint == -1 ? "CA flag not set" : "pathLenConstraint to small (was: " + pathLenConstraint + " needed:" + certsSeparatingThisCertFromEndEntity + ")"));
    }
}
Also used : DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 82 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project pdfbox by apache.

the class CRLVerifier method getCrlDistributionPoints.

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution
 * Point" extension in a X.509 certificate. If CRL distribution point
 * extension is unavailable, returns an empty list.
 * @param cert
 * @return List of CRL distribution point URLs.
 * @throws java.io.IOException
 */
public static List<String> getCrlDistributionPoints(X509Certificate cert) throws IOException {
    byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<>();
    }
    ASN1Primitive derObjCrlDP;
    try (ASN1InputStream oAsnInStream = new ASN1InputStream(crldpExt)) {
        derObjCrlDP = oAsnInStream.readObject();
    }
    if (!(derObjCrlDP instanceof ASN1OctetString)) {
        LOG.warn("CRL distribution points for certificate subject " + cert.getSubjectX500Principal().getName() + " should be an octet string, but is " + derObjCrlDP);
        return new ArrayList<>();
    }
    ASN1OctetString dosCrlDP = (ASN1OctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1Primitive derObj2;
    try (ASN1InputStream oAsnInStream2 = new ASN1InputStream(crldpExtOctets)) {
        derObj2 = oAsnInStream2.readObject();
    }
    CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
    List<String> crlUrls = new ArrayList<>();
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            // Look for an URI
            for (GeneralName genName : GeneralNames.getInstance(dpn.getName()).getNames()) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = ASN1IA5String.getInstance(genName.getName()).getString();
                    crlUrls.add(url);
                }
            }
        }
    }
    return crlUrls;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ArrayList(java.util.ArrayList) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1IA5String(org.bouncycastle.asn1.ASN1IA5String) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 83 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project keystore-explorer by kaikramer.

the class X509Ext method getDeltaCrlIndicatorStringValue.

private static String getDeltaCrlIndicatorStringValue(byte[] value) throws IOException {
    // @formatter:off
    /*
		 * deltaCRLIndicator EXTENSION ::= { SYNTAX BaseCRLNumber IDENTIFIED BY
		 * id-ce-deltaCRLIndicator }
		 *
		 * BaseCRLNumber ::= CRLNumber
		 *
		 * CRLNumber ::= ASN1Integer (0..MAX)
		 */
    // @formatter:on
    CRLNumber crlNumber = CRLNumber.getInstance(value);
    BigInteger crlNum = crlNumber.getCRLNumber();
    return HexUtil.getHexString(crlNum) + NEWLINE;
}
Also used : CRLNumber(org.bouncycastle.asn1.x509.CRLNumber) BigInteger(java.math.BigInteger)

Example 84 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project keystore-explorer by kaikramer.

the class X509Ext method getMsCaVersionStringValue.

private static String getMsCaVersionStringValue(byte[] octets) {
    /*
            "The extension data is a DWORD value (encoded as X509_INTEGER in the extension);
            the low 16 bits are the certificate index, and the high 16 bits are the key index."
		 */
    ASN1Integer asn1Integer = ASN1Integer.getInstance(octets);
    int version = asn1Integer.getValue().intValue();
    String certIndex = String.valueOf(version & 0xffff);
    String keyIndex = String.valueOf(version >> 16);
    StringBuilder sb = new StringBuilder();
    sb.append(MessageFormat.format(res.getString("MSCaVersion.CertIndex"), certIndex));
    sb.append(NEWLINE);
    sb.append(MessageFormat.format(res.getString("MSCaVersion.KeyIndex"), keyIndex));
    sb.append(NEWLINE);
    return sb.toString();
}
Also used : ASN1Integer(org.bouncycastle.asn1.ASN1Integer) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERGeneralString(org.bouncycastle.asn1.DERGeneralString) ASN1IA5String(org.bouncycastle.asn1.ASN1IA5String) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) ASN1BitString(org.bouncycastle.asn1.ASN1BitString) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1BMPString(org.bouncycastle.asn1.ASN1BMPString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1PrintableString(org.bouncycastle.asn1.ASN1PrintableString) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint)

Example 85 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project ddf by codice.

the class CertificateSigningRequestTest method testNewCertificateBuilderWithSan.

@Test
public void testNewCertificateBuilderWithSan() throws Exception {
    final DateTime start = DateTime.now().minusDays(1);
    final DateTime end = start.plusYears(100);
    final KeyPair kp = makeKeyPair();
    csr.setSerialNumber(1);
    csr.setNotBefore(start);
    csr.setNotAfter(end);
    csr.setCommonName("A");
    csr.setSubjectKeyPair(kp);
    csr.addSubjectAlternativeNames("IP:1.2.3.4", "DNS:A");
    final X509Certificate issuerCert = mock(X509Certificate.class);
    doReturn(new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US")).when(issuerCert).getSubjectX500Principal();
    final JcaX509v3CertificateBuilder builder = csr.newCertificateBuilder(issuerCert);
    final X509CertificateHolder holder = builder.build(new DemoCertificateAuthority().getContentSigner());
    assertThat(holder.getSerialNumber(), equalTo(BigInteger.ONE));
    assertThat(holder.getNotBefore(), equalTo(new Time(start.toDate()).getDate()));
    assertThat(holder.getNotAfter(), equalTo(new Time(end.toDate()).getDate()));
    assertThat(holder.getSubject().toString(), equalTo("cn=A"));
    assertThat("Unable to validate public key", holder.getSubjectPublicKeyInfo(), equalTo(SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded())));
    final org.bouncycastle.asn1.x509.Extension csn = holder.getExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName);
    assertThat(csn.getParsedValue().toASN1Primitive().getEncoded(ASN1Encoding.DER), equalTo(new GeneralNamesBuilder().addName(new GeneralName(GeneralName.iPAddress, "1.2.3.4")).addName(new GeneralName(GeneralName.dNSName, "A")).build().getEncoded(ASN1Encoding.DER)));
}
Also used : KeyPair(java.security.KeyPair) Time(org.bouncycastle.asn1.x509.Time) DateTime(org.joda.time.DateTime) DateTime(org.joda.time.DateTime) X509Certificate(java.security.cert.X509Certificate) GeneralNamesBuilder(org.bouncycastle.asn1.x509.GeneralNamesBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Test(org.junit.Test)

Aggregations

IOException (java.io.IOException)133 Extension (org.bouncycastle.asn1.x509.Extension)131 X509Certificate (java.security.cert.X509Certificate)80 ArrayList (java.util.ArrayList)78 Enumeration (java.util.Enumeration)75 Extensions (org.bouncycastle.asn1.x509.Extensions)70 BigInteger (java.math.BigInteger)62 CertPathValidatorException (java.security.cert.CertPathValidatorException)60 DEROctetString (org.bouncycastle.asn1.DEROctetString)59 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)58 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)57 GeneralSecurityException (java.security.GeneralSecurityException)55 List (java.util.List)55 HashSet (java.util.HashSet)54 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)51 CertificateExpiredException (java.security.cert.CertificateExpiredException)47 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)47 CertPathBuilderException (java.security.cert.CertPathBuilderException)45 Set (java.util.Set)45 GeneralName (org.bouncycastle.asn1.x509.GeneralName)44