Example usage for java.security.cert X509Certificate getExtensionValue

List of usage examples for java.security.cert X509Certificate getExtensionValue

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getExtensionValue.

Prototype

public byte[] getExtensionValue(String oid);

Source Link

Document

Gets the DER-encoded OCTET string for the extension value (extnValue) identified by the passed-in oid String.

Usage

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

protected void generateCrmf() throws Exception {

    // Edit our favorite test user
    UserDataVOWS user1 = new UserDataVOWS();
    user1.setUsername(CA1_WSTESTUSER1);/*from ww  w.j  a  v  a 2s.com*/
    user1.setPassword(PASSWORD);
    user1.setClearPwd(true);
    user1.setSubjectDN(getDN(CA1_WSTESTUSER1));
    user1.setCaName(CA1);
    user1.setStatus(UserDataVOWS.STATUS_NEW);
    user1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED);
    user1.setEndEntityProfileName(WS_EEPROF_EI);
    user1.setCertificateProfileName(WS_CERTPROF_EI);
    ejbcaraws.editUser(user1);

    final AuthenticationToken admin = new TestAlwaysAllowLocalAuthenticationToken(
            new UsernamePrincipal("SYSTEMTEST"));
    KeyPair keys = KeyTools.genKeys("512", "RSA");
    CAInfo info = caSession.getCAInfo(admin, CA1);
    CertReqMsg req = createCrmfRequest(info.getSubjectDN(), getDN(CA1_WSTESTUSER1), keys, "1.2.3.4");
    CertReqMessages msgs = new CertReqMessages(req);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msgs);
    byte[] ba = bao.toByteArray();
    String reqstr = new String(Base64.encode(ba));
    //CertificateResponse certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, CRMF, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
    CertificateResponse certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, reqstr, null,
            CertificateHelper.RESPONSETYPE_CERTIFICATE);
    assertNotNull(certenv);
    X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData());
    assertNotNull(cert);
    log.info(cert.getSubjectDN().toString());
    assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString());
    byte[] ext = cert.getExtensionValue("1.2.3.4");
    // Certificate profile did not allow extension override
    assertNull("no extension should exist", ext);
    // Allow extension override
    CertificateProfile profile = certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI);
    profile.setAllowExtensionOverride(true);
    certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile);
    // Now our extension should be possible to get in there
    try {
        ejbcaraws.editUser(user1);
        keys = KeyTools.genKeys("512", "RSA");
        info = caSession.getCAInfo(admin, CA1);
        req = createCrmfRequest(info.getSubjectDN(), getDN(CA1_WSTESTUSER1), keys, "1.2.3.4");
        msgs = new CertReqMessages(req);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(msgs);
        ba = bao.toByteArray();
        reqstr = new String(Base64.encode(ba));
        certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, reqstr, null,
                CertificateHelper.RESPONSETYPE_CERTIFICATE);
        assertNotNull(certenv);
        cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData());
        assertNotNull(cert);
        assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString());
        ext = cert.getExtensionValue("1.2.3.4");
        assertNotNull("there should be an extension", ext);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(ext));
        try {
            DEROctetString oct = (DEROctetString) (asn1InputStream.readObject());
            assertEquals("Extension did not have the correct value", "foo123",
                    (new String(oct.getOctets()).trim()));
        } finally {
            asn1InputStream.close();
        }
    } finally {
        // restore
        profile.setAllowExtensionOverride(false);
        certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile);
    }
}

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

@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   w  w w. j  a v  a  2s .  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:org.codice.ddf.security.filter.login.LoginFilter.java

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;//  w  w w .  jav  a 2 s.com
        }
    }

    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.");
        }
    }
}

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

public void addOtherTSLPointer(String location, String mimeType, String tslType, String schemeTerritory,
        String schemeOperatorName, String schemeTypeCommunityRuleUri, Locale schemeTypeCommunityRuleUriLocale,
        X509Certificate digitalIdentityCertificate) {
    TSLSchemeInformationType schemeInformation = getSchemeInformation();
    OtherTSLPointersType otherTSLPointers = schemeInformation.getPointersToOtherTSL();
    if (null == otherTSLPointers) {
        otherTSLPointers = this.objectFactory.createOtherTSLPointersType();
        schemeInformation.setPointersToOtherTSL(otherTSLPointers);
    }/*from w  w  w. j  av  a 2 s .c o m*/
    List<OtherTSLPointerType> pointerList = otherTSLPointers.getOtherTSLPointer();
    OtherTSLPointerType otherTSLPointer = this.objectFactory.createOtherTSLPointerType();
    pointerList.add(otherTSLPointer);

    otherTSLPointer.setTSLLocation(location);
    AdditionalInformationType additionalInformation = this.objectFactory.createAdditionalInformationType();
    otherTSLPointer.setAdditionalInformation(additionalInformation);

    List<Object> objects = additionalInformation.getTextualInformationOrOtherInformation();
    {
        JAXBElement<String> mimeTypeElement = this.tslxObjectFactory.createMimeType(mimeType);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(mimeTypeElement);
        objects.add(anyType);
    }
    {
        JAXBElement<String> tslTypeElement = this.objectFactory.createTSLType(tslType);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(tslTypeElement);
        objects.add(anyType);
    }
    {
        JAXBElement<String> schemeTerritoryElement = this.objectFactory.createSchemeTerritory(schemeTerritory);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(schemeTerritoryElement);
        objects.add(anyType);
    }
    {
        InternationalNamesType i18nNames = this.objectFactory.createInternationalNamesType();
        MultiLangNormStringType i18nName = this.objectFactory.createMultiLangNormStringType();
        i18nName.setLang("en");
        i18nName.setValue(schemeOperatorName);
        i18nNames.getName().add(i18nName);
        JAXBElement<InternationalNamesType> schemeOperatorNameElement = this.objectFactory
                .createSchemeOperatorName(i18nNames);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(schemeOperatorNameElement);
        objects.add(anyType);
    }
    {
        NonEmptyMultiLangURIListType uriList = this.objectFactory.createNonEmptyMultiLangURIListType();
        NonEmptyMultiLangURIType uri = this.objectFactory.createNonEmptyMultiLangURIType();
        uri.setLang(schemeTypeCommunityRuleUriLocale.getLanguage());
        uri.setValue(schemeTypeCommunityRuleUri);
        uriList.getURI().add(uri);
        JAXBElement<NonEmptyMultiLangURIListType> schemeTypeCommunityRulesElement = this.objectFactory
                .createSchemeTypeCommunityRules(uriList);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(schemeTypeCommunityRulesElement);
        objects.add(anyType);
    }
    if (null != digitalIdentityCertificate) {
        ServiceDigitalIdentityListType serviceDigitalIdentityList = this.objectFactory
                .createServiceDigitalIdentityListType();
        DigitalIdentityListType digitalIdentityList = this.objectFactory.createDigitalIdentityListType();
        List<DigitalIdentityType> digitalIdentities = digitalIdentityList.getDigitalId();
        DigitalIdentityType digitalIdentity = this.objectFactory.createDigitalIdentityType();

        try {
            digitalIdentity.setX509Certificate(digitalIdentityCertificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("X509 encoding error: " + e.getMessage(), e);
        }
        digitalIdentities.add(digitalIdentity);

        digitalIdentity = this.objectFactory.createDigitalIdentityType();
        digitalIdentity.setX509SubjectName(digitalIdentityCertificate.getSubjectX500Principal().getName());
        digitalIdentities.add(digitalIdentity);

        byte[] skiValue = digitalIdentityCertificate
                .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
        if (null != skiValue) {
            digitalIdentity = this.objectFactory.createDigitalIdentityType();
            SubjectKeyIdentifierStructure subjectKeyIdentifierStructure;
            try {
                subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(skiValue);
            } catch (IOException e) {
                throw new RuntimeException("X509 SKI decoding error: " + e.getMessage(), e);
            }
            digitalIdentity.setX509SKI(subjectKeyIdentifierStructure.getKeyIdentifier());
            digitalIdentities.add(digitalIdentity);
        }

        List<DigitalIdentityListType> digitalIdentityListList = serviceDigitalIdentityList
                .getServiceDigitalIdentity();
        digitalIdentityListList.add(digitalIdentityList);

        otherTSLPointer.setServiceDigitalIdentities(serviceDigitalIdentityList);
    }
}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

private static String getOcspUrl(X509Certificate certificate) throws Exception {
    byte[] octetBytes = certificate.getExtensionValue(X509Extension.authorityInfoAccess.getId());
    DLSequence dlSequence = null;//from w  w  w. j ava  2s.  c o m
    ASN1Encodable asn1Encodable = null;
    try {
        ASN1Primitive fromExtensionValue = X509ExtensionUtil.fromExtensionValue(octetBytes);
        if (!(fromExtensionValue instanceof DLSequence)) {
            return null;
        }
        dlSequence = (DLSequence) fromExtensionValue;
        for (int i = 0; i < dlSequence.size(); i++) {
            asn1Encodable = dlSequence.getObjectAt(i);
            if (!(asn1Encodable instanceof DLSequence)) {
                break;
            }
        }
        if (!(asn1Encodable instanceof DLSequence)) {
            return null;
        }
        dlSequence = (DLSequence) asn1Encodable;
        for (int i = 0; i < dlSequence.size(); i++) {
            asn1Encodable = dlSequence.getObjectAt(i);
            if (asn1Encodable instanceof DERTaggedObject) {
                break;
            }
        }
        if (!(asn1Encodable instanceof DERTaggedObject)) {
            return null;
        }
        DERTaggedObject derTaggedObject = (DERTaggedObject) asn1Encodable;
        byte[] encoded = derTaggedObject.getEncoded();
        if (derTaggedObject.getTagNo() == 6) {
            int len = encoded[1];
            return new String(encoded, 2, len);
        }
    } catch (IOException ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
    }
    return null;
}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

private static List<String> getAIALocations(X509Certificate cert) throws Exception {

    //Gets the DER-encoded OCTET string for the extension value for Authority information access Points
    byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());
    if (aiaExtensionValue == null) {
        throw new Exception("Certificate doesn't have authority " + "information access points");
    }/*  ww  w  .j a v  a 2  s  .c om*/
    //might have to pass an ByteArrayInputStream(aiaExtensionValue)
    ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue);
    AuthorityInformationAccess authorityInformationAccess;

    try {
        DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject());
        ASN1InputStream asn1InOctets = new ASN1InputStream(aiaDEROctetString.getOctets());
        ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1InOctets.readObject();
        authorityInformationAccess = AuthorityInformationAccess.getInstance(aiaASN1Sequence);
    } catch (IOException ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        throw new Exception("Cannot read certificate to get OCSP URLs", ex);
    }

    List<String> ocspUrlList = new ArrayList<String>();
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {

        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
            DERIA5String str = DERIA5String.getInstance(gn.getName());
            String accessLocation = str.getString();
            ocspUrlList.add(accessLocation);
        }
    }
    if (ocspUrlList.isEmpty()) {
        throw new Exception("Cant get OCSP urls from certificate");
    }

    return ocspUrlList;
}