Example usage for org.bouncycastle.asn1 DERSequence DERSequence

List of usage examples for org.bouncycastle.asn1 DERSequence DERSequence

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DERSequence DERSequence.

Prototype

public DERSequence(ASN1Encodable[] elements) 

Source Link

Document

Create a sequence containing an array of objects.

Usage

From source file:eu.europa.ec.markt.dss.signature.cades.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

private Attribute getComposedAtsHashIndex(AlgorithmIdentifier algorithmIdentifiers,
        ASN1Sequence certificatesHashIndex, ASN1Sequence crLsHashIndex,
        ASN1Sequence unsignedAttributesHashIndex) {
    final ASN1EncodableVector vector = new ASN1EncodableVector();
    if (algorithmIdentifiers != null) {
        vector.add(algorithmIdentifiers);
    }/*from   w w  w  .j  a  v  a  2s . co m*/
    vector.add(certificatesHashIndex);
    vector.add(crLsHashIndex);
    vector.add(unsignedAttributesHashIndex);
    final ASN1Sequence derSequence = new DERSequence(vector);
    return new Attribute(OID.id_aa_ATSHashIndex, new DERSet(derSequence));
}

From source file:eu.europa.ec.markt.dss.signature.cades.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

/**
 * The field certificatesHashIndex is a sequence of octet strings. Each one contains the hash value of one
 * instance of CertificateChoices within certificates field of the root SignedData. A hash value for
 * every instance of CertificateChoices, as present at the time when the corresponding archive time-stamp is
 * requested, shall be included in certificatesHashIndex. No other hash value shall be included in this field.
 *
 * @param cAdESSignature//from  w  w w .  j a v  a  2  s  .co m
 * @return
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
private ASN1Sequence getCertificatesHashIndex(CAdESSignature cAdESSignature) throws DSSException {

    final ASN1EncodableVector certificatesHashIndexVector = new ASN1EncodableVector();

    final List<CertificateToken> certificateTokens = cAdESSignature
            .getCertificatesWithinSignatureAndTimestamps();
    for (final CertificateToken certificateToken : certificateTokens) {
        final byte[] encodedCertificate = certificateToken.getEncoded();
        final byte[] digest = DSSUtils.digest(hashIndexDigestAlgorithm, encodedCertificate);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding to CertificatesHashIndex DSS-Identifier: {} with hash {}",
                    certificateToken.getDSSId(), DSSUtils.encodeHexString(digest));
        }
        final DEROctetString derOctetStringDigest = new DEROctetString(digest);
        certificatesHashIndexVector.add(derOctetStringDigest);
    }
    return new DERSequence(certificatesHashIndexVector);
}

From source file:eu.europa.ec.markt.dss.signature.cades.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

/**
 * The field crlsHashIndex is a sequence of octet strings. Each one contains the hash value of one instance of
 * RevocationInfoChoice within crls field of the root SignedData. A hash value for every instance of
 * RevocationInfoChoice, as present at the time when the corresponding archive time-stamp is requested, shall be
 * included in crlsHashIndex. No other hash values shall be included in this field.
 *
 * @param cAdESSignature//from ww  w.  j  a  v  a 2s .c o  m
 * @return
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getCRLsHashIndex(CAdESSignature cAdESSignature) throws DSSException {

    final ASN1EncodableVector crlsHashIndex = new ASN1EncodableVector();

    final SignedData signedData = SignedData
            .getInstance(cAdESSignature.getCmsSignedData().toASN1Structure().getContent());
    final ASN1Set signedDataCRLs = signedData.getCRLs();
    if (signedDataCRLs != null) {
        final Enumeration<ASN1Encodable> crLs = signedDataCRLs.getObjects();
        if (crLs != null) {
            while (crLs.hasMoreElements()) {
                final ASN1Encodable asn1Encodable = crLs.nextElement();
                digestAndAddToList(crlsHashIndex, DSSASN1Utils.getDEREncoded(asn1Encodable));
            }
        }
    }

    return new DERSequence(crlsHashIndex);
}

From source file:eu.europa.ec.markt.dss.signature.cades.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

/**
 * The field unsignedAttrsHashIndex is a sequence of octet strings. Each one contains the hash value of one
 * instance of Attribute within unsignedAttrs field of the SignerInfo. A hash value for every instance of
 * Attribute, as present at the time when the corresponding archive time-stamp is requested, shall be included in
 * unsignedAttrsHashIndex. No other hash values shall be included in this field.
 *
 * @param signerInformation//from   ww  w.j a  v  a 2s .  com
 * @return
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getUnsignedAttributesHashIndex(SignerInformation signerInformation) throws DSSException {

    final ASN1EncodableVector unsignedAttributesHashIndex = new ASN1EncodableVector();
    AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
    final ASN1EncodableVector asn1EncodableVector = unsignedAttributes.toASN1EncodableVector();
    for (int i = 0; i < asn1EncodableVector.size(); i++) {
        final Attribute attribute = (Attribute) asn1EncodableVector.get(i);
        if (!excludedAttributesFromAtsHashIndex.contains(attribute.getAttrType())) {
            final DEROctetString derOctetStringDigest = getAttributeDerOctetStringHash(attribute);
            unsignedAttributesHashIndex.add(derOctetStringDigest);
        }
    }
    return new DERSequence(unsignedAttributesHashIndex);
}

From source file:eu.europa.ec.markt.dss.signature.cades.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

/**
 * 3) Fields version, sid, digestAlgorithm, signedAttrs, signatureAlgorithm, and
 * signature within the SignedData.signerInfoss item corresponding to the signature being archive
 * time-stamped, in their order of appearance.
 *
 * @param signerInformation// w w w.j  av a2s .com
 * @return
 */
private byte[] geSignedFields(SignerInformation signerInformation) {
    final SignerInfo signerInfo = signerInformation.toASN1Structure();
    final ASN1Integer version = signerInfo.getVersion();
    final SignerIdentifier sid = signerInfo.getSID();
    final AlgorithmIdentifier digestAlgorithm = signerInfo.getDigestAlgorithm();
    final ASN1TaggedObject signedAttributes = new DERTaggedObject(false, 0,
            new DERSequence(signerInfo.getAuthenticatedAttributes().toArray()));
    final AlgorithmIdentifier digestEncryptionAlgorithm = signerInfo.getDigestEncryptionAlgorithm();
    final ASN1OctetString encryptedDigest = signerInfo.getEncryptedDigest();

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        final byte[] derEncodedVersion = DSSASN1Utils.getDEREncoded(version);
        final byte[] derEncodedSid = DSSASN1Utils.getDEREncoded(sid);
        final byte[] derEncodedDigestAlgo = DSSASN1Utils.getDEREncoded(digestAlgorithm);
        final byte[] derEncodedSignedAttributes = DSSASN1Utils.getDEREncoded(signedAttributes);
        final byte[] derEncodedDigestEncryptionAlgo = DSSASN1Utils.getDEREncoded(digestEncryptionAlgorithm);
        final byte[] derEncodedEncryptedDigest = DSSASN1Utils.getDEREncoded(encryptedDigest);
        if (LOG.isDebugEnabled()) {
            LOG.debug("getSignedFields Version={}", DSSUtils.encodeHexString(derEncodedVersion));
            LOG.debug("getSignedFields Sid={}", DSSUtils.encodeHexString(derEncodedSid));
            LOG.debug("getSignedFields DigestAlgo={}", DSSUtils.encodeHexString(derEncodedDigestAlgo));
            LOG.debug("getSignedFields SignedAttributes={}",
                    DSSUtils.encodeHexString(derEncodedSignedAttributes)); // bad
            LOG.debug("getSignedFields DigestEncryptionAlgo={}",
                    DSSUtils.encodeHexString(derEncodedDigestEncryptionAlgo));
            LOG.debug("getSignedFields EncryptedDigest={}",
                    DSSUtils.encodeHexString(derEncodedEncryptedDigest));
        }
        byteArrayOutputStream.write(derEncodedVersion);
        byteArrayOutputStream.write(derEncodedSid);
        byteArrayOutputStream.write(derEncodedDigestAlgo);
        byteArrayOutputStream.write(derEncodedSignedAttributes);
        byteArrayOutputStream.write(derEncodedDigestEncryptionAlgo);
        byteArrayOutputStream.write(derEncodedEncryptedDigest);
        return byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileBES.java

License:Open Source License

private Attribute makeSignerAttrAttribute(SignatureParameters parameters) {
    DEROctetString[] roles = new DEROctetString[1];
    roles[0] = new DEROctetString(parameters.getClaimedSignerRole().getBytes());
    return new Attribute(PKCSObjectIdentifiers.id_aa_ets_signerAttr,
            new DERSet(new SignerAttribute(new DERSequence(roles))));

}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java

License:Open Source License

/**
 * Create a reference to a X509Certificate
 * //from  www  . j  a va 2 s  .  com
 * @param cert
 * @return
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
private OtherCertID makeOtherCertID(X509Certificate cert)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(),
            new BouncyCastleProvider());
    byte[] d = sha1digest.digest(cert.getEncoded());
    LOG.info(new DEROctetString(d).getDERObject().toString());
    OtherHash hash = new OtherHash(sha1digest.digest(cert.getEncoded()));
    OtherCertID othercertid = new OtherCertID(new DERSequence(hash.getDERObject()));
    return othercertid;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java

License:Open Source License

private Hashtable<ASN1ObjectIdentifier, ASN1Encodable> extendUnsignedAttributes(
        Hashtable<ASN1ObjectIdentifier, ASN1Encodable> unsignedAttrs, X509Certificate signingCertificate,
        SignatureParameters parameters, Date signingTime, CertificateSource optionalCertificateSource)
        throws IOException {

    ValidationContext validationContext = certificateVerifier.validateCertificate(signingCertificate,
            signingTime,/*w w  w . j  a  v a2s.com*/
            new CompositeCertificateSource(new ListCertificateSource(parameters.getCertificateChain()),
                    optionalCertificateSource),
            null, null);

    try {

        ArrayList<OtherCertID> completeCertificateRefs = new ArrayList<OtherCertID>();
        ArrayList<CrlOcspRef> completeRevocationRefs = new ArrayList<CrlOcspRef>();

        /*
         * The ETSI TS 101 733 stipulates (6.2.1): "It references the full set of CA certificates that have been
         * used to validate an ES with Complete validation data up to (but not including) the signer's certificate.
         * [...] NOTE 1: The signer's certificate is referenced in the signing certificate attribute (see clause
         * 5.7.3)." (6.2.1)
         * 
         * "The second and subsequent CrlOcspRef fields shall be in the same order as the OtherCertID to which they
         * relate." (6.2.2)
         * 
         * Also, no mention of the way to order those second and subsequent fields, so we add the certificates as
         * provided by the context.
         */

        /* The SignedCertificate is in validationContext.getCertificate() */

        for (CertificateAndContext c : validationContext.getNeededCertificates()) {

            /*
             * Add every certificate except the signing certificate
             */
            if (!c.equals(signingCertificate)) {
                completeCertificateRefs.add(makeOtherCertID(c.getCertificate()));
                // certificateValues.add(new X509CertificateStructure((ASN1Sequence) ASN1Object.fromByteArray(c
                // .getCertificate().getEncoded())));
            }

            ArrayList<CrlValidatedID> crlListIdValues = new ArrayList<CrlValidatedID>();
            ArrayList<OcspResponsesID> ocspListIDValues = new ArrayList<OcspResponsesID>();

            /*
             * Record each CRL and OCSP with a reference to the corresponding certificate
             */
            for (CRL relatedcrl : validationContext.getRelatedCRLs(c)) {
                crlListIdValues.add(makeCrlValidatedID((X509CRL) relatedcrl));
            }

            for (BasicOCSPResp relatedocspresp : validationContext.getRelatedOCSPResp(c)) {
                ocspListIDValues.add(makeOcspResponsesID(relatedocspresp));
            }

            CrlValidatedID[] crlListIdArray = new CrlValidatedID[crlListIdValues.size()];
            OcspResponsesID[] ocspListIDArray = new OcspResponsesID[ocspListIDValues.size()];

            completeRevocationRefs.add(new CrlOcspRef(new CrlListID(crlListIdValues.toArray(crlListIdArray)),
                    new OcspListID(ocspListIDValues.toArray(ocspListIDArray)), null));
        }

        OtherCertID[] otherCertIDArray = new OtherCertID[completeCertificateRefs.size()];
        CrlOcspRef[] crlOcspRefArray = new CrlOcspRef[completeRevocationRefs.size()];

        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_certificateRefs,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_certificateRefs,
                        new DERSet(new DERSequence(completeCertificateRefs.toArray(otherCertIDArray)))));
        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_revocationRefs,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_revocationRefs,
                        new DERSet(new DERSequence(completeRevocationRefs.toArray(crlOcspRefArray)))));

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e);
    } catch (OCSPException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return unsignedAttrs;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileXL.java

License:Open Source License

private Hashtable<ASN1ObjectIdentifier, ASN1Encodable> extendUnsignedAttributes(
        Hashtable<ASN1ObjectIdentifier, ASN1Encodable> unsignedAttrs, X509Certificate signingCertificate,
        Date signingDate, CertificateSource optionalCertificateSource) throws IOException {

    ValidationContext validationContext = certificateVerifier.validateCertificate(signingCertificate,
            signingDate, optionalCertificateSource, null, null);

    try {//from w w  w . j a v a  2s  .com
        List<X509CertificateStructure> certificateValues = new ArrayList<X509CertificateStructure>();
        ArrayList<CertificateList> crlValues = new ArrayList<CertificateList>();
        ArrayList<BasicOCSPResponse> ocspValues = new ArrayList<BasicOCSPResponse>();

        /*
         * The ETSI TS 101 733 stipulates (6.2.1): "It references the full set of CA certificates that have been
         * used to validate an ES with Complete validation data up to (but not including) the signer's certificate.
         * [...] NOTE 1: The signer's certificate is referenced in the signing certificate attribute (see clause
         * 5.7.3)." (6.2.1)
         * 
         * "The second and subsequent CrlOcspRef fields shall be in the same order as the OtherCertID to which they
         * relate." (6.2.2)
         * 
         * Also, no mention of the way to order those second and subsequent fields, so we add the certificates as
         * provided by the context.
         */

        /* The SignedCertificate is in validationContext.getCertificate() */

        for (CertificateAndContext c : validationContext.getNeededCertificates()) {

            /*
             * Add every certificate except the signing certificate
             */
            if (!c.equals(signingCertificate)) {
                certificateValues.add(new X509CertificateStructure(
                        (ASN1Sequence) ASN1Object.fromByteArray(c.getCertificate().getEncoded())));
            }

        }

        /*
         * Record each CRL and OCSP with a reference to the corresponding certificate
         */
        for (CRL relatedcrl : validationContext.getNeededCRL()) {
            crlValues.add(new CertificateList(
                    (ASN1Sequence) ASN1Object.fromByteArray(((X509CRL) relatedcrl).getEncoded())));
        }

        for (BasicOCSPResp relatedocspresp : validationContext.getNeededOCSPResp()) {
            ocspValues.add((new BasicOCSPResponse(
                    (ASN1Sequence) ASN1Object.fromByteArray(relatedocspresp.getEncoded()))));
        }

        CertificateList[] crlValuesArray = new CertificateList[crlValues.size()];
        BasicOCSPResponse[] ocspValuesArray = new BasicOCSPResponse[ocspValues.size()];
        RevocationValues revocationValues = new RevocationValues(crlValues.toArray(crlValuesArray),
                ocspValues.toArray(ocspValuesArray), null);
        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_revocationValues,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_revocationValues, new DERSet(revocationValues)));

        X509CertificateStructure[] certValuesArray = new X509CertificateStructure[certificateValues.size()];
        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_certValues,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_certValues,
                        new DERSet(new DERSequence(certificateValues.toArray(certValuesArray)))));

    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return unsignedAttrs;

}

From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileEPES.java

License:Open Source License

CMSSignedDataGenerator createCMSSignedDataGenerator(ContentSigner contentSigner,
        DigestCalculatorProvider digestCalculatorProvider, final SignatureParameters parameters,
        final byte[] messageDigest) throws IOException {
    try {/* w w  w .jav  a 2 s  .c o  m*/

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        X509Certificate signerCertificate = parameters.getSigningCertificate();

        X509CertificateHolder certHolder = new X509CertificateHolder(signerCertificate.getEncoded());

        SignerInfoGeneratorBuilder sigenb = new SignerInfoGeneratorBuilder(digestCalculatorProvider);

        final CAdESProfileEPES profile = new CAdESProfileEPES(true);

        sigenb = sigenb.setSignedAttributeGenerator(new CMSAttributeTableGenerator() {
            @Override
            public AttributeTable getAttributes(Map params) throws CMSAttributeTableGenerationException {
                Hashtable clone = (Hashtable) profile.getSignedAttributes(parameters).clone();

                if (!clone.containsKey(CMSAttributes.contentType)) {
                    DERObjectIdentifier contentType = (DERObjectIdentifier) params
                            .get(CMSAttributeTableGenerator.CONTENT_TYPE);

                    // contentType will be null if we're trying to generate a counter signature.
                    if (contentType != null) {
                        Attribute attr = new Attribute(CMSAttributes.contentType, new DERSet(contentType));
                        clone.put(attr.getAttrType(), attr);
                    }
                }

                if (!clone.containsKey(CMSAttributes.messageDigest)) {
                    System.out.println("Digest propos : "
                            + org.apache.commons.codec.binary.Hex.encodeHexString(messageDigest));
                    // byte[] messageDigest = (byte[]) params.get(CMSAttributeTableGenerator.DIGEST);
                    Attribute attr = new Attribute(CMSAttributes.messageDigest,
                            new DERSet(new DEROctetString(messageDigest)));
                    clone.put(attr.getAttrType(), attr);
                }

                if (parameters.getCommitmentTypeIndication() != null
                        && !parameters.getCommitmentTypeIndication().isEmpty()) {
                    ASN1EncodableVector vector = new ASN1EncodableVector();
                    for (String id : parameters.getCommitmentTypeIndication()) {
                        vector.add(new DERObjectIdentifier(id));
                    }
                    DERSet set = new DERSet(new DERSequence(vector));
                    Attribute attr = new Attribute(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.16"), set);
                    clone.put(attr.getAttrType(), attr);
                }

                return new AttributeTable(clone);
            }
        });

        // sigenb.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(new AttributeTable(
        // new Hashtable<ASN1ObjectIdentifier, ASN1Encodable>())));

        /*
         * We don't include a unsigned attribute table if not needed : a unsignedAttrs of signerInfo includes no
         * Attribute, UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute(defined in RFC3852).
         */
        SignerInfoGenerator sigen = sigenb.build(contentSigner, certHolder);

        generator.addSignerInfoGenerator(sigen);

        Collection<X509Certificate> certs = new ArrayList<X509Certificate>();
        if (parameters.getCertificateChain() == null
                || !parameters.getCertificateChain().contains(parameters.getSigningCertificate())) {
            certs.add(parameters.getSigningCertificate());
        }
        certs.addAll(parameters.getCertificateChain());
        JcaCertStore certStore = new JcaCertStore(certs);
        generator.addCertificates(certStore);

        System.out.println("Gnrator cr");
        return generator;

    } catch (CertificateException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    }

}