Example usage for org.bouncycastle.asn1 ASN1EncodableVector add

List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector add

Introduction

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

Prototype

public void add(ASN1Encodable element) 

Source Link

Usage

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

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)/*from w  w w.  ja v  a2 s.co m*/
 * <p/>
 * 5.10.3 content-hints Attribute
 * The content-hints attribute provides information on the innermost signed content of a multi-layer message where
 * one content is encapsulated in another.
 * The syntax of the content-hints attribute type of the ES is as defined in ESS (RFC 2634 [5]).
 * When used to indicate the precise format of the data to be presented to the user, the following rules apply:
 *  the contentType indicates the type of the associated content. It is an object identifier (i.e. a unique string of
 * integers) assigned by an authority that defines the content type; and
 *  when the contentType is id-data the contentDescription shall define the presentation format; the
 * format may be defined by MIME types.
 * When the format of the content is defined by MIME types, the following rules apply:
 *  the contentType shall be id-data as defined in CMS (RFC 3852 [4]);
 *  the contentDescription shall be used to indicate the encoding of the data, in accordance with the rules
 * defined RFC 2045 [6]; see annex F for an example of structured contents and MIME.
 * NOTE 1: id-data OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) 1 }.
 * NOTE 2: contentDescription is optional in ESS (RFC 2634 [5]). It may be used to complement
 * contentTypes defined elsewhere; such definitions are outside the scope of the present document.
 *
 * @param parameters
 * @param signedAttributes
 * @return
 */
private void addContentHints(final SignatureParameters parameters, final ASN1EncodableVector signedAttributes) {

    final BLevelParameters bLevelParameters = parameters.bLevel();
    if (DSSUtils.isNotBlank(bLevelParameters.getContentHintsType())) {

        final ASN1ObjectIdentifier contentHintsType = new ASN1ObjectIdentifier(
                bLevelParameters.getContentHintsType());
        final String contentHintsDescriptionString = bLevelParameters.getContentHintsDescription();
        final DERUTF8String contentHintsDescription = DSSUtils.isBlank(contentHintsDescriptionString) ? null
                : new DERUTF8String(contentHintsDescriptionString);
        //      "text/plain";
        //      "1.2.840.113549.1.7.1";

        final ContentHints contentHints = new ContentHints(contentHintsType, contentHintsDescription);
        final DERSet attrValues = new DERSet(contentHints);
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_contentHint, attrValues);
        signedAttributes.add(attribute);
    }
}

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

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)/* ww  w. java 2 s .  c  o m*/
 * <p/>
 * 5.10.2 content-identifier Attribute
 * The content-identifier attribute provides an identifier for the signed content, for use when a reference may be
 * later required to that content; for example, in the content-reference attribute in other signed data sent later. The
 * content-identifier shall be a signed attribute. content-identifier attribute type values for the ES have an ASN.1 type ContentIdentifier, as defined in
 * ESS (RFC 2634 [5]).
 * <p/>
 * The minimal content-identifier attribute should contain a concatenation of user-specific identification
 * information (such as a user name or public keying material identification information), a GeneralizedTime string,
 * and a random number.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addContentIdentifier(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    /* this attribute is prohibited in PAdES B */
    if (!padesUsage) {

        final BLevelParameters bLevelParameters = parameters.bLevel();
        final String contentIdentifierPrefix = bLevelParameters.getContentIdentifierPrefix();
        if (DSSUtils.isNotBlank(contentIdentifierPrefix)) {

            final String contentIdentifierSuffix;
            if (DSSUtils.isBlank(bLevelParameters.getContentIdentifierSuffix())) {

                final Date now = new Date();
                final String asn1GeneralizedTimeString = new ASN1GeneralizedTime(now).getTimeString();
                final long randomNumber = new Random(now.getTime()).nextLong();
                contentIdentifierSuffix = asn1GeneralizedTimeString + randomNumber;
                bLevelParameters.setContentIdentifierSuffix(contentIdentifierSuffix);
            } else {
                contentIdentifierSuffix = bLevelParameters.getContentIdentifierSuffix();
            }
            final String contentIdentifierString = contentIdentifierPrefix + contentIdentifierSuffix;
            final ContentIdentifier contentIdentifier = new ContentIdentifier(
                    contentIdentifierString.getBytes());
            final DERSet attrValues = new DERSet(contentIdentifier);
            final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_contentIdentifier,
                    attrValues);
            signedAttributes.add(attribute);
        }
    }
}

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

License:Open Source License

private void addSignaturePolicyId(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    Policy policy = parameters.bLevel().getSignaturePolicy();
    if (policy != null && policy.getId() != null) {

        final String policyId = policy.getId();
        SignaturePolicyIdentifier sigPolicy = null;
        if (!"".equals(policyId)) { // explicit

            final ASN1ObjectIdentifier derOIPolicyId = new ASN1ObjectIdentifier(policyId);
            final ASN1ObjectIdentifier oid = policy.getDigestAlgorithm().getOid();
            final AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(oid);
            OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(algorithmIdentifier,
                    new DEROctetString(policy.getDigestValue()));
            sigPolicy = new SignaturePolicyIdentifier(
                    new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue));
        } else {// implicit
            sigPolicy = new SignaturePolicyIdentifier();
        }//  www  .  ja v  a2  s . c  om
        final DERSet attrValues = new DERSet(sigPolicy);
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId, attrValues);
        signedAttributes.add(attribute);
    }
}

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

License:Open Source License

private void addSigningCertificateAttribute(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) throws DSSException {

    final DigestAlgorithm digestAlgorithm = parameters.getDigestAlgorithm();
    final X509Certificate signingCertificate = parameters.getSigningCertificate();
    final byte[] encoded = DSSUtils.getEncoded(signingCertificate);
    final byte[] certHash = DSSUtils.digest(digestAlgorithm, encoded);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding Certificate Hash {} with algorithm {}", DSSUtils.encodeHexString(certHash),
                digestAlgorithm.getName());
    }//  w w w. j  a  v  a 2s .c  om
    final IssuerSerial issuerSerial = DSSUtils.getIssuerSerial(signingCertificate);
    if (digestAlgorithm == DigestAlgorithm.SHA1) {

        final ESSCertID essCertId = new ESSCertID(certHash, issuerSerial);
        final SigningCertificate cadesSigningCertificate = new SigningCertificate(essCertId);
        final DERSet attrValues = new DERSet(cadesSigningCertificate);
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, attrValues);
        signedAttributes.add(attribute);
    } else {

        final ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(digestAlgorithm.getAlgorithmIdentifier(), certHash,
                issuerSerial);
        final ESSCertIDv2[] essCertIDv2Array = new ESSCertIDv2[] { essCertIDv2 };
        final SigningCertificateV2 cadesSigningCertificateV2 = new SigningCertificateV2(essCertIDv2Array);
        final DERSet attrValues = new DERSet(cadesSigningCertificateV2);
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, attrValues);
        signedAttributes.add(attribute);
    }
}

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  . ja v  a2s. c  o  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 ava 2s .c om*/
 * @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

private void digestAndAddToList(ASN1EncodableVector crlsHashIndex, byte[] encoded) {
    final byte[] digest = DSSUtils.digest(hashIndexDigestAlgorithm, encoded);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding to crlsHashIndex with hash {}", DSSUtils.encodeHexString(digest));
    }/*from  ww w  .j  av  a  2s.c  o  m*/
    final DEROctetString derOctetStringDigest = new DEROctetString(digest);
    crlsHashIndex.add(derOctetStringDigest);
}

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  www. j a  va 2 s .  c  o m*/
 * @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.pades.PAdESProfileEPES.java

License:Open Source License

CMSSignedDataGenerator createCMSSignedDataGenerator(ContentSigner contentSigner,
        DigestCalculatorProvider digestCalculatorProvider, final SignatureParameters parameters,
        final byte[] messageDigest) throws IOException {
    try {/*from  ww  w. j  a v  a2 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);
    }

}

From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java

License:Open Source License

@Override
public byte[] getArchiveTimestampData(int index, Document originalDocument) throws IOException {

    ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

    ContentInfo contentInfo = cmsSignedData.getContentInfo();
    SignedData signedData = SignedData.getInstance(contentInfo.getContent());

    /* The encapContentInfo should always be present according to the standard, but sometimes it's omitted */
    // 5.4.1/*from   w w w .  java 2 s  . c  om*/
    if (signedData.getEncapContentInfo() == null || signedData.getEncapContentInfo().getContent() == null) {
        /* Detached signatures have either no encapContentInfo in signedData, or it exists but has no eContent */
        if (originalDocument != null) {
            toTimestamp.write(originalDocument.openStream());
        } else {
            throw new RuntimeException("Signature is detached and no original data provided.");
        }
    } else {

        ContentInfo content = signedData.getEncapContentInfo();
        DEROctetString octet = (DEROctetString) content.getContent();

        ContentInfo info2 = new ContentInfo(new ASN1ObjectIdentifier("1.2.840.113549.1.7.1"),
                new BERConstructedOctetString(octet.getOctets()));
        toTimestamp.write(info2.getEncoded());
    }

    if (signedData.getCertificates() != null) {
        DEROutputStream output = new DEROutputStream(toTimestamp);
        output.writeObject(signedData.getCertificates());
        output.close();
    }

    if (signedData.getCRLs() != null) {
        toTimestamp.write(signedData.getCRLs().getEncoded());
    }

    if (signerInformation.getUnsignedAttributes() != null) {
        ASN1EncodableVector original = signerInformation.getUnsignedAttributes().toASN1EncodableVector();
        List<Attribute> timeStampToRemove = getTimeStampToRemove(index);
        ASN1EncodableVector filtered = new ASN1EncodableVector();
        for (int i = 0; i < original.size(); i++) {
            DEREncodable enc = original.get(i);
            if (!timeStampToRemove.contains(enc)) {
                filtered.add(original.get(i));
            }
        }
        SignerInformation filteredInfo = SignerInformation.replaceUnsignedAttributes(signerInformation,
                new AttributeTable(filtered));

        toTimestamp.write(filteredInfo.toASN1Structure().getEncoded());
    }

    return toTimestamp.toByteArray();
}