Example usage for org.bouncycastle.asn1.x509 SubjectKeyIdentifier getInstance

List of usage examples for org.bouncycastle.asn1.x509 SubjectKeyIdentifier getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 SubjectKeyIdentifier getInstance.

Prototype

public static SubjectKeyIdentifier getInstance(Object obj) 

Source Link

Usage

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

License:Open Source License

private byte[] getSubjectKeyId(X509Certificate cert) throws IOException {
    byte[] extvalue = cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    if (extvalue == null) {
        return null;
    }/*www.  ja v a2s  .com*/
    ASN1OctetString str = ASN1OctetString
            .getInstance(new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());
    SubjectKeyIdentifier keyId = SubjectKeyIdentifier
            .getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());
    return keyId.getKeyIdentifier();
}

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

License:Open Source License

private byte[] getSKId(final X509Certificate cert) throws IOException {
    final byte[] extValue = cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    if (extValue != null) {
        final ASN1OctetString str = ASN1OctetString
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(extValue)).readObject());
        final SubjectKeyIdentifier keyId = SubjectKeyIdentifier
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());
        return keyId.getKeyIdentifier();
    } else {/* w ww .  ja v  a2s . c  om*/
        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 ww w . j  ava 2  s  .co 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:eu.europa.esig.dss.DSSASN1Utils.java

License:Open Source License

/**
 * This method returns SKI bytes from certificate.
 *
 * @param certificateToken//from   w  ww  . j  av  a2  s .  c o  m
 *            {@code CertificateToken}
 * @return ski bytes from the given certificate
 * @throws DSSException
 */
public static byte[] getSki(final CertificateToken certificateToken) throws DSSException {
    try {
        byte[] sKI = certificateToken.getCertificate()
                .getExtensionValue(Extension.subjectKeyIdentifier.getId());
        ASN1Primitive extension = X509ExtensionUtil.fromExtensionValue(sKI);
        SubjectKeyIdentifier skiBC = SubjectKeyIdentifier.getInstance(extension);
        return skiBC.getKeyIdentifier();
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil.java

License:BSD License

public static byte[] getSubjectKeyIdentifier(X509Extension certificate) {
    try {/*  ww  w.  j  ava2  s.c o m*/
        byte[] extensionValue = certificate
                .getExtensionValue(org.bouncycastle.asn1.x509.X509Extension.subjectKeyIdentifier.getId());
        if (extensionValue == null) {
            return null;
        }
        return SubjectKeyIdentifier.getInstance(X509ExtensionUtil.fromExtensionValue(extensionValue))
                .getKeyIdentifier();
    } catch (IOException e) {
        throw new X509CertificateOperationException("Cannot get SubjectKeyIdentifier for certificate", e);
    }
}

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

License:Open Source License

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

    /*/* w  ww  . j a  v a2 s  .  com*/
     * SubjectKeyIdentifier ::= KeyIdentifier
     *
     * KeyIdentifier ::= OCTET STRING
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier.getInstance(value);

    // Get key identifier from octet string
    byte[] keyIdentifierBytes = subjectKeyIdentifier.getKeyIdentifier();

    sb.append(MessageFormat.format(res.getString("SubjectKeyIdentifier"),
            HexUtil.getHexString(keyIdentifierBytes)));
    sb.append(NEWLINE);

    return sb.toString();
}

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

License:Open Source License

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

    jkiKeyIdentifier.setKeyIdentifier(subjectKeyIdentifier.getKeyIdentifier());
}

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

License:Open Source License

/**
 * Get Subject Key Identifier (2.5.29.14) extension value as a string.
 * /*from   w  ww .j  ava  2s.  c o  m*/
 * <pre>
 * SubjectKeyIdentifier ::= KeyIdentifier
 * KeyIdentifier ::= OCTET STRING
 * </pre>
 * 
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getSubjectKeyIdentifierStringValue(byte[] bValue) throws IOException {
    SubjectKeyIdentifier ski = SubjectKeyIdentifier.getInstance(bValue);
    byte[] bKeyIdent = ski.getKeyIdentifier();

    // Output as a hex string
    return convertToHexString(bKeyIdent);
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Get the subject key identifier from a certificate extensions
 * // w w  w.j a  v a2  s .  co  m
 * @param cert certificate containing the extension
 * @return byte[] containing the subject key identifier, or null if it does not exist
 */
public static byte[] getSubjectKeyId(Certificate cert) {
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        byte[] extvalue = x509cert.getExtensionValue("2.5.29.14");
        if (extvalue == null) {
            return null;
        }
        ASN1InputStream extvalueAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extvalue));
        try {
            try {
                ASN1OctetString str = ASN1OctetString.getInstance(extvalueAsn1InputStream.readObject());
                ASN1InputStream strAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(str.getOctets()));
                try {
                    SubjectKeyIdentifier keyId = SubjectKeyIdentifier
                            .getInstance(strAsn1InputStream.readObject());
                    return keyId.getKeyIdentifier();
                } finally {
                    strAsn1InputStream.close();
                }
            } finally {
                extvalueAsn1InputStream.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Could not parse subject key ID from certificate.", e);
        }
    }
    return null;
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

License:Open Source License

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs)
        throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;//from   w w  w  .j a va 2s. c o m
        }
    }

    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject()
                    .getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();

                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf
                                    .generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();

                            //HoK spec section 2.5:
                            //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession.
                            //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte.
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException
                                | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with certificate.");
                        }

                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //HoK spec section 2.5:
                        //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate.
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject DN.");
                        }

                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException(
                                "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(assertionOs.getOctets());
                            //HoK spec section 2.5:
                            //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate.
                            //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension,
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(),
                                    assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException(
                                        "Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}