Example usage for org.bouncycastle.asn1.x509 AuthorityKeyIdentifier getKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 AuthorityKeyIdentifier getKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 AuthorityKeyIdentifier getKeyIdentifier.

Prototype

public byte[] getKeyIdentifier() 

Source Link

Usage

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

License:Open Source License

private byte[] getAuthorityKeyId(X509Certificate cert) throws IOException {
    byte[] extvalue = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
    if (extvalue == null) {
        return null;
    }/*  w  ww  .j  a v  a 2s. c  om*/
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue))
            .readObject());
    AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
    return keyId.getKeyIdentifier();
}

From source file:be.fedict.eid.dss.model.bean.TrustValidationServiceBean.java

License:Open Source License

private byte[] getAuthorityKeyId(X509Certificate cert) throws IOException {
    byte[] extvalue = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
    if (extvalue == null) {
        return null;
    }/*from  ww w. ja va 2 s  .c o  m*/
    DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue))
            .readObject());
    /*AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(
                                oct.getOctets())).readObject());*/
    AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier(oct.getOctets());

    return keyId.getKeyIdentifier();
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

License:Open Source License

private byte[] getAKId(final X509Certificate cert) throws IOException {
    final byte[] extValue = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
    if (extValue != null) {
        final DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extValue))
                .readObject());/*from w  ww .  ja  va  2 s. c om*/
        final AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
        return keyId.getKeyIdentifier();
    } else {
        return null;
    }
}

From source file:be.fedict.trust.linker.PublicKeyTrustLinker.java

License:Open Source License

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }/*from www.  j  a  v a2  s  .c  o m*/
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }

    algorithmPolicy.checkSignatureAlgorithm(childCertificate.getSigAlgOID(), validationDate);

    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA: " + certificate.getSubjectX500Principal());
        /*
         * http://www.valicert.com/ Root CA has no CA flag set. Actually
         * this is in violation with 4.2.1.10 Basic Constraints of RFC2459.
         */
        try {
            certificate.verify(certificate.getPublicKey());
            LOG.warn("allowing self-signed Root CA without CA flag set");
        } catch (Exception e) {
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "certificate not a CA");
        }
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(Extension.authorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData && null != subjectKeyIdentifierData) {
        LOG.error("child certificate is CA and MUST contain an Authority Key Identifier");
        // return new TrustLinkerResult(false,
        // TrustLinkerResultReason.INVALID_TRUST,
        // "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {
        AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdentifierData));
        SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdentifierData));
        if (!Arrays.equals(authorityKeyIdentifier.getKeyIdentifier(),
                subjectKeyIdentifier.getKeyIdentifier())) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    /*
     * Keep in mind that this trust linker can never return TRUSTED.
     */
    return TrustLinkerResult.UNDECIDED;
}

From source file:mitm.common.security.certificate.X509ExtensionInspectorTest.java

License:Open Source License

@Test
public void testAuthoritykeyIdentifier() throws Exception {
    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "mitm-test-ca.cer");

    AuthorityKeyIdentifier authorityKeyIdentifier = X509CertificateInspector
            .getAuthorityKeyIdentifier(certificate);

    assertNotNull(authorityKeyIdentifier);
    assertEquals(1, authorityKeyIdentifier.getAuthorityCertIssuer().getNames().length);

    GeneralName name = authorityKeyIdentifier.getAuthorityCertIssuer().getNames()[0];
    assertEquals(GeneralName.directoryName, name.getTagNo());
    assertEquals("C=NL,ST=NH,L=Amsterdam,CN=MITM Test Root,E=root@example.com",
            X500Name.getInstance(name.getName()).toString());
    assertEquals("115FCAC409FB2022B7D06920A00FE42",
            BigIntegerUtils.hexEncode(authorityKeyIdentifier.getAuthorityCertSerialNumber()));

    // another cert
    certificate = TestUtils.loadCertificate("test/resources/testdata/certificates/" + "ldap-crl.cer");

    authorityKeyIdentifier = X509CertificateInspector.getAuthorityKeyIdentifier(certificate);

    assertNotNull(authorityKeyIdentifier);
    assertEquals("37509F5DEF72162D12C7D46C408B1F65F550A8F9",
            HexUtils.hexEncode(authorityKeyIdentifier.getKeyIdentifier()));
}

From source file:net.sf.keystore_explorer.crypto.x509.X509Ext.java

License:Open Source License

private String getAuthorityKeyIdentifierStringValue(byte[] value) throws IOException {
    // @formatter:off

    /*//from   w ww.  j  av  a2s. c  o m
     * AuthorityKeyIdentifier ::= ASN1Sequence { keyIdentifier [0]
     * KeyIdentifier OPTIONAL, authorityCertIssuer [1] GeneralNames
     * OPTIONAL, authorityCertSerialNumber [2] CertificateSerialNumber
     * OPTIONAL }
     *
     * KeyIdentifier ::= OCTET STRING
     *
     * GeneralNames ::= ASN1Sequence SIZE (1..MAX) OF GeneralName
     *
     * CertificateSerialNumber ::= ASN1Integer
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(value);

    byte[] keyIdentifier = authorityKeyIdentifier.getKeyIdentifier();
    GeneralNames authorityCertIssuer = authorityKeyIdentifier.getAuthorityCertIssuer();
    BigInteger certificateSerialNumber = authorityKeyIdentifier.getAuthorityCertSerialNumber();

    if (keyIdentifier != null) { // Optional
        // Output as a hex string
        sb.append(MessageFormat.format(res.getString("AuthorityKeyIdentifier"),
                HexUtil.getHexString(keyIdentifier)));
        sb.append(NEWLINE);
    }

    if (authorityCertIssuer != null) { // Optional
        sb.append(res.getString("CertificateIssuer"));
        sb.append(NEWLINE);

        for (GeneralName generalName : authorityCertIssuer.getNames()) {
            sb.append(INDENT);
            sb.append(GeneralNameUtil.toString(generalName));
            sb.append(NEWLINE);
        }
    }

    if (certificateSerialNumber != null) { // Optional
        // Output as an integer
        sb.append(MessageFormat.format(res.getString("CertificateSerialNumber"),
                HexUtil.getHexString(certificateSerialNumber)));
        sb.append(NEWLINE);
    }

    return sb.toString();
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DAuthorityKeyIdentifier.java

License:Open Source License

private void prepopulateWithValue(byte[] value) throws IOException {
    AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(value);

    if (authorityKeyIdentifier.getKeyIdentifier() != null) {
        jkiKeyIdentifier.setKeyIdentifier(authorityKeyIdentifier.getKeyIdentifier());
    }/*from  w  w w .j a v a  2 s  . com*/

    GeneralNames authorityCertIssuer = authorityKeyIdentifier.getAuthorityCertIssuer();

    if (authorityCertIssuer != null) {
        jgnAuthorityCertIssuer.setGeneralNames(authorityCertIssuer);
    }

    BigInteger authorityCertSerialNumber = authorityKeyIdentifier.getAuthorityCertSerialNumber();

    if (authorityCertSerialNumber != null) {
        jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.longValue());
        jtfAuthorityCertSerialNumber.setCaretPosition(0);
    }
}

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get Authority Key Identifier (2.5.29.35) extension value as a string.
 * //from w w w .  j  a v  a  2  s.c  om
 * <pre>
 * AuthorityKeyIdentifier ::= SEQUENCE {
 *     keyIdentifier             [0] KeyIdentifier           OPTIONAL,
 *     authorityCertIssuer       [1] Names                   OPTIONAL,
 *     authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
 * KeyIdentifier ::= OCTET STRING
 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
 * CertificateSerialNumber  ::=  INTEGER
 * </pre>
 * 
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getAuthorityKeyIdentifierStringValue(byte[] bValue) throws IOException {
    AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(bValue);

    StringBuilder strBuff = new StringBuilder();

    byte[] keyIdentifier = aki.getKeyIdentifier();
    if (keyIdentifier != null) {
        strBuff.append(RB.getString("KeyIdentifier"));
        strBuff.append(": ");
        strBuff.append(convertToHexString(keyIdentifier));
        strBuff.append("<br>");
    }

    GeneralNames authorityCertIssuer;
    if ((authorityCertIssuer = aki.getAuthorityCertIssuer()) != null) {
        if (strBuff.length() != 0) {
            strBuff.append("<br>");
        }
        strBuff.append("<ul><li>");
        strBuff.append(RB.getString("CertificateIssuer"));
        strBuff.append(": ");
        strBuff.append(getGeneralNamesString(authorityCertIssuer, LinkClass.BROWSER));
        strBuff.append("</li></ul>");
    }

    BigInteger serialNo;
    if ((serialNo = aki.getAuthorityCertSerialNumber()) != null) {
        if (strBuff.length() != 0) {
            strBuff.append("<br>");
        }
        strBuff.append(MessageFormat.format(RB.getString("CertificateSerialNumber"), serialNo));
    }

    return strBuff.toString();
}

From source file:net.solarnetwork.node.setup.test.PKITestUtils.java

License:Open Source License

public static X509Certificate generateNewCACert(PublicKey publicKey, String subject, X509Certificate issuer,
        PrivateKey issuerKey, String caDN) throws Exception {
    final X500Name issuerDn = (issuer == null ? new X500Name(subject) : JcaX500NameUtil.getSubject(issuer));
    final X500Name subjectDn = new X500Name(subject);
    final BigInteger serial = getNextSerialNumber();
    final Date notBefore = new Date();
    final Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60L * 60L);
    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerDn, serial, notBefore, notAfter,
            subjectDn, publicKey);//  ww w.  jav a 2  s  . c om

    // add "CA" extension
    BasicConstraints basicConstraints;
    if (issuer == null) {
        basicConstraints = new BasicConstraints(true);
    } else {
        int issuerPathLength = issuer.getBasicConstraints();
        basicConstraints = new BasicConstraints(issuerPathLength - 1);
    }
    builder.addExtension(X509Extension.basicConstraints, true, basicConstraints);

    // add subjectKeyIdentifier
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    SubjectKeyIdentifier ski = utils.createSubjectKeyIdentifier(publicKey);
    builder.addExtension(X509Extension.subjectKeyIdentifier, false, ski);

    // add authorityKeyIdentifier
    GeneralNames issuerName = new GeneralNames(new GeneralName(GeneralName.directoryName, caDN));
    AuthorityKeyIdentifier aki = utils.createAuthorityKeyIdentifier(publicKey);
    aki = new AuthorityKeyIdentifier(aki.getKeyIdentifier(), issuerName, serial);
    builder.addExtension(X509Extension.authorityKeyIdentifier, false, aki);

    // add keyUsage
    X509KeyUsage keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.digitalSignature
            | X509KeyUsage.keyCertSign | X509KeyUsage.nonRepudiation);
    builder.addExtension(X509Extension.keyUsage, true, keyUsage);

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA");
    ContentSigner signer = signerBuilder.build(issuerKey);

    X509CertificateHolder holder = builder.build(signer);
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    return converter.getCertificate(holder);
}

From source file:org.cesecore.certificates.crl.CrlCreateSessionTest.java

License:Open Source License

private void checkCrlAkid(X509CA subca, final byte[] crl) throws Exception {
    assertNotNull(crl);//w  w  w .  j ava 2 s. c  o  m

    // First, check that it is signed by the correct public key
    final X509CRL xcrl = CertTools.getCRLfromByteArray(crl);
    final PublicKey pubK = subca.getCACertificate().getPublicKey();
    xcrl.verify(pubK);

    // Check that the correct AKID is used
    final byte[] akidExtBytes = xcrl.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    ASN1InputStream octAis = new ASN1InputStream(new ByteArrayInputStream(akidExtBytes));
    DEROctetString oct = (DEROctetString) (octAis.readObject());
    ASN1InputStream keyidAis = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
    AuthorityKeyIdentifier akid = AuthorityKeyIdentifier.getInstance((ASN1Sequence) keyidAis.readObject());
    keyidAis.close();
    octAis.close();
    assertArrayEquals("Incorrect Authority Key Id in CRL.", TEST_AKID, akid.getKeyIdentifier());
}