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

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

Introduction

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

Prototype

public static X509Name getInstance(Object obj) 

Source Link

Usage

From source file:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

License:Open Source License

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }/*  w w  w.  j  a va2s .  c  o m*/

    // create basic XML container structure
    Document document = signatureElement.getOwnerDocument();
    String xadesNamespacePrefix;
    if (null != qualifyingPropertiesElement.getPrefix()) {
        xadesNamespacePrefix = qualifyingPropertiesElement.getPrefix() + ":";
    } else {
        xadesNamespacePrefix = "";
    }
    Element unsignedPropertiesElement = (Element) findSingleNode(qualifyingPropertiesElement,
            "xades:UnsignedProperties");
    if (null == unsignedPropertiesElement) {
        unsignedPropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedProperties");
        qualifyingPropertiesElement.appendChild(unsignedPropertiesElement);
    }
    Element unsignedSignaturePropertiesElement = (Element) findSingleNode(unsignedPropertiesElement,
            "xades:UnsignedSignatureProperties");
    if (null == unsignedSignaturePropertiesElement) {
        unsignedSignaturePropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedSignatureProperties");
        unsignedPropertiesElement.appendChild(unsignedSignaturePropertiesElement);
    }

    // create the XAdES-T time-stamp
    Node signatureValueNode = findSingleNode(signatureElement, "ds:SignatureValue");
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.debug("creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(signatureValueNode),
            tsaRevocationDataXadesT, this.c14nAlgoId, this.timeStampService, this.objectFactory,
            this.xmldsigObjectFactory);

    // marshal the XAdES-T extension
    try {
        this.marshaller.marshal(this.objectFactory.createSignatureTimeStamp(signatureTimeStamp),
                unsignedSignaturePropertiesElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        try {
            this.marshaller.marshal(this.xades141ObjectFactory.createTimeStampValidationData(validationData),
                    unsignedSignaturePropertiesElement);
        } catch (JAXBException e) {
            throw new RuntimeException("JAXB error: " + e.getMessage(), e);
        }
    }

    if (null == this.revocationDataService) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = this.objectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = this.objectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();
    for (int certIdx = 1; certIdx < signingCertificateChain.size(); certIdx++) {
        /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
        X509Certificate certificate = signingCertificateChain.get(certIdx);
        CertIDType certId = XAdESSignatureFacet.getCertID(certificate, this.objectFactory,
                this.xmldsigObjectFactory, this.digestAlgorithm, false);
        certIds.add(certId);
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = this.objectFactory.createCompleteRevocationRefsType();
    RevocationData revocationData = this.revocationDataService.getRevocationData(signingCertificateChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = this.objectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        List<byte[]> crls = revocationData.getCRLs();
        for (byte[] encodedCrl : crls) {
            CRLRefType crlRef = this.objectFactory.createCRLRefType();
            crlRefList.add(crlRef);
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = this.objectFactory.createCRLIdentifierType();
            crlRef.setCRLIdentifier(crlIdentifier);
            String issuerName;
            try {
                issuerName = PrincipalUtil.getIssuerX509Principal(crl).getName().replace(",", ", ");
            } catch (CRLException e) {
                throw new RuntimeException("CRL encoding error: " + e.getMessage(), e);
            }
            crlIdentifier.setIssuer(issuerName);
            crlIdentifier.setIssueTime(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(crl.getThisUpdate()).toGregorianCalendar()));
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(encodedCrl,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            crlRef.setDigestAlgAndValue(digestAlgAndValue);
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = this.objectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();
        List<byte[]> ocsps = revocationData.getOCSPs();
        for (byte[] ocsp : ocsps) {
            OCSPRefType ocspRef = this.objectFactory.createOCSPRefType();
            ocspRefList.add(ocspRef);

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(ocsp,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            ocspRef.setDigestAlgAndValue(digestAlgAndValue);

            OCSPIdentifierType ocspIdentifier = this.objectFactory.createOCSPIdentifierType();
            ocspRef.setOCSPIdentifier(ocspIdentifier);
            OCSPResp ocspResp;
            try {
                ocspResp = new OCSPResp(ocsp);
            } catch (IOException e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
            Object ocspResponseObject;
            try {
                ocspResponseObject = ocspResp.getResponseObject();
            } catch (OCSPException e) {
                throw new RuntimeException("OCSP error: " + e.getMessage(), e);
            }
            BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResponseObject;
            Date producedAt = basicOcspResp.getProducedAt();
            ocspIdentifier.setProducedAt(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(producedAt).toGregorianCalendar()));

            ResponderIDType responderId = this.objectFactory.createResponderIDType();
            ocspIdentifier.setResponderID(responderId);
            RespID respId = basicOcspResp.getResponderId();
            ResponderID ocspResponderId = respId.toASN1Object();
            DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
            if (2 == derTaggedObject.getTagNo()) {
                ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                responderId.setByKey(keyHashOctetString.getOctets());
            } else {
                X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                responderId.setByName(name.toString());
            }
        }
    }

    // marshal XAdES-C
    NodeList unsignedSignaturePropertiesNodeList = ((Element) qualifyingPropertiesElement)
            .getElementsByTagNameNS(XADES_NAMESPACE, "UnsignedSignatureProperties");
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    try {
        this.marshaller.marshal(this.objectFactory.createCompleteCertificateRefs(completeCertificateRefs),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createCompleteRevocationRefs(completeRevocationRefs),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new LinkedList<Node>();
    timeStampNodesXadesX1.add(signatureValueNode);
    Node signatureTimeStampNode = findSingleNode(unsignedSignaturePropertiesNode, "xades:SignatureTimeStamp");
    timeStampNodesXadesX1.add(signatureTimeStampNode);
    Node completeCertificateRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteCertificateRefs");
    timeStampNodesXadesX1.add(completeCertificateRefsNode);
    Node completeRevocationRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteRevocationRefs");
    timeStampNodesXadesX1.add(completeRevocationRefsNode);

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.debug("creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1,
            this.c14nAlgoId, this.timeStampService, this.objectFactory, this.xmldsigObjectFactory);
    ValidationDataType timeStampXadesX1ValidationData;
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
    } else {
        timeStampXadesX1ValidationData = null;
    }

    // marshal XAdES-X
    try {
        this.marshaller.marshal(this.objectFactory.createSigAndRefsTimeStamp(timeStampXadesX1),
                unsignedSignaturePropertiesNode);
        if (null != timeStampXadesX1ValidationData) {
            this.marshaller.marshal(
                    this.xades141ObjectFactory.createTimeStampValidationData(timeStampXadesX1ValidationData),
                    unsignedSignaturePropertiesNode);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X-L
    CertificateValuesType certificateValues = this.objectFactory.createCertificateValuesType();
    List<Object> certificateValuesList = certificateValues.getEncapsulatedX509CertificateOrOtherCertificate();
    for (X509Certificate certificate : signingCertificateChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = this.objectFactory.createEncapsulatedPKIDataType();
        try {
            encapsulatedPKIDataType.setValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
        certificateValuesList.add(encapsulatedPKIDataType);
    }
    RevocationValuesType revocationValues = createRevocationValues(revocationData);

    // marshal XAdES-X-L
    try {
        this.marshaller.marshal(this.objectFactory.createCertificateValues(certificateValues),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createRevocationValues(revocationValues),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
}

From source file:de.rub.dez6a3.jpdfsigner.TimeStampToken.java

License:Open Source License

/**
 * Validate the time stamp token.//  www  . java 2  s. c o m
 * <p>
 * To be valid the token must be signed by the passed in certificate and
 * the certificate must be the one refered to by the SigningCertificate
 * attribute included in the hashed attributes of the token. The
 * certifcate must also have the ExtendedKeyUsageExtension with only
 * KeyPurposeId.id_kp_timeStamping and have been valid at the time the
 * timestamp was created.
 * </p>
 * <p>
 * A successful call to validate means all the above are true.
 * </p>
 */
public void validate(X509Certificate cert, String provider) throws TSPException, TSPValidationException,
        CertificateExpiredException, CertificateNotYetValidException, NoSuchProviderException {
    try {
        if (!MessageDigest.isEqual(certID.getCertHash(),
                MessageDigest.getInstance("SHA-1").digest(cert.getEncoded()))) {
            throw new TSPValidationException("certificate hash does not match certID hash.");
        }

        if (certID.getIssuerSerial() != null) {
            if (!certID.getIssuerSerial().getSerial().getValue().equals(cert.getSerialNumber())) {
                throw new TSPValidationException(
                        "certificate serial number does not match certID for signature.");
            }

            GeneralName[] names = certID.getIssuerSerial().getIssuer().getNames();
            X509Principal principal = PrincipalUtil.getIssuerX509Principal(cert);
            boolean found = false;

            for (int i = 0; i != names.length; i++) {
                if (names[i].getTagNo() == 4
                        && new X509Principal(X509Name.getInstance(names[i].getName())).equals(principal)) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                throw new TSPValidationException("certificate name does not match certID for signature. ");
            }
        }

        TSPUtil.validateCertificate(cert);

        cert.checkValidity(tstInfo.getGenTime());

        if (!tsaSignerInfo.verify(cert, provider)) {
            throw new TSPValidationException("signature not created by certificate.");
        }
    } catch (CMSException e) {
        if (e.getUnderlyingException() != null) {
            throw new TSPException(e.getMessage(), e.getUnderlyingException());
        } else {
            throw new TSPException("CMS exception: " + e, e);
        }
    } catch (NoSuchAlgorithmException e) {
        throw new TSPException("cannot find algorithm: " + e, e);
    } catch (CertificateEncodingException e) {
        throw new TSPException("problem processing certificate: " + e, e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java

License:Open Source License

private void incorporateOCSPRefs(CompleteRevocationRefsType completeRevocationRefs, ValidationContext ctx) {
    if (!ctx.getNeededOCSPResp().isEmpty()) {
        OCSPRefsType ocspRefs = this.xadesObjectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();

        for (BasicOCSPResp basicOcspResp : ctx.getNeededOCSPResp()) {
            try {
                OCSPRefType ocspRef = this.xadesObjectFactory.createOCSPRefType();

                DigestAlgAndValueType digestAlgAndValue = getDigestAlgAndValue(
                        OCSPUtils.fromBasicToResp(basicOcspResp).getEncoded(), DigestAlgorithm.SHA1);
                LOG.info("Add a reference for OCSP produced at " + basicOcspResp.getProducedAt() + " digest "
                        + Hex.encodeHexString(digestAlgAndValue.getDigestValue()));
                ocspRef.setDigestAlgAndValue(digestAlgAndValue);

                OCSPIdentifierType ocspIdentifier = xadesObjectFactory.createOCSPIdentifierType();
                ocspRef.setOCSPIdentifier(ocspIdentifier);

                Date producedAt = basicOcspResp.getProducedAt();

                GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
                cal.setTime(producedAt);

                ocspIdentifier.setProducedAt(this.datatypeFactory.newXMLGregorianCalendar(cal));

                ResponderIDType responderId = this.xadesObjectFactory.createResponderIDType();
                ocspIdentifier.setResponderID(responderId);
                RespID respId = basicOcspResp.getResponderId();
                ResponderID ocspResponderId = respId.toASN1Object();
                DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
                if (2 == derTaggedObject.getTagNo()) {
                    ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                    responderId.setByKey(keyHashOctetString.getOctets());
                } else {
                    X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                    responderId.setByName(name.toString());
                }//from   w w  w.j  av  a 2 s .  c om

                ocspRefList.add(ocspRef);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:org.globus.gsi.bc.BouncyCastleUtil.java

License:Apache License

/**
 * Returns certificate type of the given TBS certificate. <BR>
 * The certificate type is {@link GSIConstants#CA GSIConstants.CA}
 * <B>only</B> if the certificate contains a
 * BasicConstraints extension and it is marked as CA.<BR>
 * A certificate is a GSI-2 proxy when the subject DN of the certificate
 * ends with <I>"CN=proxy"</I> (certificate type {@link
 * GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY}) or
 * <I>"CN=limited proxy"</I> (certificate type {@link
 * GSIConstants#GSI_2_LIMITED_PROXY GSIConstants.LIMITED_PROXY}) component
 * and the issuer DN of the certificate matches the subject DN without
 * the last proxy <I>CN</I> component.<BR>
 * A certificate is a GSI-3 proxy when the subject DN of the certificate
 * ends with a <I>CN</I> component, the issuer DN of the certificate
 * matches the subject DN without the last <I>CN</I> component and
 * the certificate contains {@link ProxyCertInfo ProxyCertInfo} critical
 * extension./*from  w w  w.  ja  v a 2 s  .  com*/
 * The certificate type is {@link GSIConstants#GSI_3_IMPERSONATION_PROXY
 * GSIConstants.GSI_3_IMPERSONATION_PROXY} if the policy language of
 * the {@link ProxyCertInfo ProxyCertInfo} extension is set to
 * {@link ProxyPolicy#IMPERSONATION ProxyPolicy.IMPERSONATION} OID.
 * The certificate type is {@link GSIConstants#GSI_3_LIMITED_PROXY
 * GSIConstants.GSI_3_LIMITED_PROXY} if the policy language of
 * the {@link ProxyCertInfo ProxyCertInfo} extension is set to
 * {@link ProxyPolicy#LIMITED ProxyPolicy.LIMITED} OID.
 * The certificate type is {@link GSIConstants#GSI_3_INDEPENDENT_PROXY
 * GSIConstants.GSI_3_INDEPENDENT_PROXY} if the policy language of
 * the {@link ProxyCertInfo ProxyCertInfo} extension is set to
 * {@link ProxyPolicy#INDEPENDENT ProxyPolicy.INDEPENDENT} OID.
 * The certificate type is {@link GSIConstants#GSI_3_RESTRICTED_PROXY
 * GSIConstants.GSI_3_RESTRICTED_PROXY} if the policy language of
 * the {@link ProxyCertInfo ProxyCertInfo} extension is set to
 * any other OID then the above.<BR>
 * The certificate type is {@link GSIConstants#EEC GSIConstants.EEC}
 * if the certificate is not a CA certificate or a GSI-2 or GSI-3 proxy.
 *
 * @param crt the TBS certificate to get the type of.
 * @return the certificate type. The certificate type is determined
 *         by rules described above.
 * @exception IOException if something goes wrong.
 * @exception CertificateException for proxy certificates, if
 *            the issuer DN of the certificate does not match
 *            the subject DN of the certificate without the
 *            last <I>CN</I> component. Also, for GSI-3 proxies
 *            when the <code>ProxyCertInfo</code> extension is
 *            not marked as critical.
 */
private static GSIConstants.CertificateType getCertificateType(TBSCertificateStructure crt)
        throws CertificateException, IOException {
    X509Extensions extensions = crt.getExtensions();
    X509Extension ext = null;

    if (extensions != null) {
        ext = extensions.getExtension(X509Extension.basicConstraints);
        if (ext != null) {
            BasicConstraints basicExt = BasicConstraints.getInstance(ext);
            if (basicExt.isCA()) {
                return GSIConstants.CertificateType.CA;
            }
        }
    }

    GSIConstants.CertificateType type = GSIConstants.CertificateType.EEC;

    // does not handle multiple AVAs
    X500Name subject = crt.getSubject();

    ASN1Set entry = X509NameHelper.getLastNameEntry(subject);
    ASN1Sequence ava = (ASN1Sequence) entry.getObjectAt(0);
    if (BCStyle.CN.equals(ava.getObjectAt(0))) {
        String value = ((ASN1String) ava.getObjectAt(1)).getString();
        if (value.equalsIgnoreCase("proxy")) {
            type = GSIConstants.CertificateType.GSI_2_PROXY;
        } else if (value.equalsIgnoreCase("limited proxy")) {
            type = GSIConstants.CertificateType.GSI_2_LIMITED_PROXY;
        } else if (extensions != null) {
            boolean gsi4 = true;
            // GSI_4
            ext = extensions.getExtension(ProxyCertInfo.OID);
            if (ext == null) {
                // GSI_3
                ext = extensions.getExtension(ProxyCertInfo.OLD_OID);
                gsi4 = false;
            }
            if (ext != null) {
                if (ext.isCritical()) {
                    ProxyCertInfo proxyCertExt = getProxyCertInfo(ext);
                    ProxyPolicy proxyPolicy = proxyCertExt.getProxyPolicy();
                    ASN1ObjectIdentifier oid = proxyPolicy.getPolicyLanguage();
                    if (ProxyPolicy.IMPERSONATION.equals(oid)) {
                        if (gsi4) {
                            type = GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY;
                        } else {
                            type = GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY;
                        }
                    } else if (ProxyPolicy.INDEPENDENT.equals(oid)) {
                        if (gsi4) {
                            type = GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY;
                        } else {
                            type = GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY;
                        }
                    } else if (ProxyPolicy.LIMITED.equals(oid)) {
                        if (gsi4) {
                            type = GSIConstants.CertificateType.GSI_4_LIMITED_PROXY;
                        } else {
                            type = GSIConstants.CertificateType.GSI_3_LIMITED_PROXY;
                        }
                    } else {
                        if (gsi4) {
                            type = GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY;
                        } else {
                            type = GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY;
                        }
                    }

                } else {
                    String err = i18n.getMessage("proxyCertCritical");
                    throw new CertificateException(err);
                }
            }
        }

        if (ProxyCertificateUtil.isProxy(type)) {
            X509NameHelper iss = new X509NameHelper(crt.getIssuer());
            iss.add((ASN1Set) BouncyCastleUtil.duplicate(entry));
            X509Name issuer = iss.getAsName();
            if (!issuer.equals(X509Name.getInstance(subject))) {
                String err = i18n.getMessage("proxyDNErr");
                throw new CertificateException(err);
            }
        }
    }

    return type;
}

From source file:org.opensc.pkcs15.asn1.attr.CommonPrivateKeyAttributes.java

License:Apache License

/**
 * @param obj The ASN.1 object to decode.
 * @return An instance of CommonPrivateKeyAttributes.
 *//*from ww  w  .jav a2 s  . c  o  m*/
public static CommonPrivateKeyAttributes getInstance(Object obj) {
    if (obj instanceof CommonPrivateKeyAttributes)
        return (CommonPrivateKeyAttributes) obj;

    if (obj instanceof ASN1Sequence) {
        ASN1Sequence seq = (ASN1Sequence) obj;

        Enumeration<Object> objs = seq.getObjects();

        CommonPrivateKeyAttributes ret = new CommonPrivateKeyAttributes();

        while (objs.hasMoreElements()) {

            Object o = objs.nextElement();

            if (o instanceof ASN1Sequence) {
                ret.setSubjectName(X509Name.getInstance(o));
            } else if (o instanceof ASN1TaggedObject) {

                ASN1TaggedObject to = (ASN1TaggedObject) o;

                if (to.getTagNo() != 0)
                    throw new IllegalArgumentException("Invalid member tag [" + to.getTagNo()
                            + "] in member of CommonPrivateKeyAttributes ASN.1 SEQUENCE.");

                ret.setKeyIdentifiers(KeyIdentifiers.getInstance(to.getObject()));

            } else
                throw new IllegalArgumentException(
                        "Invalid member [" + o + "] in CommonPrivateKeyAttributes ASN.1 SEQUENCE.");
        }

        return ret;
    }

    throw new IllegalArgumentException("CommonPrivateKeyAttributes must be encoded as an ASN.1 SEQUENCE.");
}

From source file:org.opensc.pkcs15.asn1.attr.CommonPublicKeyAttributes.java

License:Apache License

/**
 * @param obj The ASN.1 object to decode.
 * @return An instance of CommonPublicKeyAttributes.
 *//* w w w  .  j  ava 2s .com*/
public static CommonPublicKeyAttributes getInstance(Object obj) {
    if (obj instanceof CommonPublicKeyAttributes)
        return (CommonPublicKeyAttributes) obj;

    if (obj instanceof ASN1Sequence) {
        ASN1Sequence seq = (ASN1Sequence) obj;

        Enumeration<Object> objs = seq.getObjects();

        CommonPublicKeyAttributes ret = new CommonPublicKeyAttributes();

        while (objs.hasMoreElements()) {

            Object o = objs.nextElement();

            if (o instanceof ASN1Sequence) {
                ret.setSubjectName(X509Name.getInstance(o));
            } else if (o instanceof ASN1TaggedObject) {

                ASN1TaggedObject to = (ASN1TaggedObject) o;

                if (to.getTagNo() != 0)
                    throw new IllegalArgumentException("Invalid member tag [" + to.getTagNo()
                            + "] in member of CommonPublicKeyAttributes ASN.1 SEQUENCE.");

                ret.setTrustedUsage(Usage.getInstance(to.getObject()));

            } else
                throw new IllegalArgumentException(
                        "Invalid member [" + o + "] in CommonPublicKeyAttributes ASN.1 SEQUENCE.");
        }

        return ret;
    }

    throw new IllegalArgumentException("CommonPublicKeyAttributes must be encoded as an ASN.1 SEQUENCE.");
}

From source file:org.opensc.pkcs15.asn1.attr.X509CertificateAttributes.java

License:Apache License

/**
 * @param obj The ASN.1 object to decode.
 * @param directory The directory used to resolve path references.
 * @return An instance of CommonPublicKeyAttributes.
 *//*from  w ww . j a  va 2 s. c o m*/
public static X509CertificateAttributes getInstance(Object obj,
        Directory<Path, X509CertificateObject> directory) {
    if (obj instanceof X509CertificateAttributes)
        return (X509CertificateAttributes) obj;

    if (obj instanceof ASN1Sequence) {
        ASN1Sequence seq = (ASN1Sequence) obj;

        Enumeration<Object> objs = seq.getObjects();

        X509CertificateAttributes ret = new X509CertificateAttributes();

        ret.setValue(X509CertificateObjectFactory.getInstance(objs.nextElement(), directory));

        if (!objs.hasMoreElements())
            return ret;

        Object o = objs.nextElement();

        if (o instanceof ASN1Sequence) {
            ret.setSubject(X509Name.getInstance(o));

            if (!objs.hasMoreElements())
                return ret;
            o = objs.nextElement();
        }

        if (o instanceof ASN1TaggedObject) {

            ASN1TaggedObject to = (ASN1TaggedObject) o;

            if (to.getTagNo() != 0)
                throw new IllegalArgumentException("Invalid member tag [" + to.getTagNo()
                        + "] in member of X509CertificateAttributes ASN.1 SEQUENCE.");

            ret.setIssuer(X509Name.getInstance(to.getObject()));

            if (!objs.hasMoreElements())
                return ret;
            o = objs.nextElement();
        }

        if (o instanceof DERInteger) {
            ret.setSerialNumber(DERInteger.getInstance(o).getValue());
            return ret;
        }

        throw new IllegalArgumentException(
                "Invalid member [" + o + "] in X509CertificateAttributes ASN.1 SEQUENCE.");
    }

    throw new IllegalArgumentException("X509CertificateAttributes must be encoded as an ASN.1 SEQUENCE.");
}