Example usage for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector

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

Introduction

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

Prototype

public ASN1EncodableVector() 

Source Link

Usage

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//w ww . j a  v a2s.  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.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 .j  a v  a2s .  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   ww w .j a v  a 2 s  .  c  o  m*/
    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();
}

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

License:Open Source License

/**
 * Copied from org.bouncycastle.asn1.cms.SignerInfo#toASN1Object() and adapted to be able to use the custom unauthenticatedAttributes
 *
 * @param signerInfo/*from w w w .  jav a2  s.c  om*/
 * @param unauthenticatedAttributes
 * @return
 */
private ASN1Sequence getSignerInfoEncoded(SignerInfo signerInfo, ASN1Encodable unauthenticatedAttributes) {

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(signerInfo.getVersion());
    v.add(signerInfo.getSID());
    v.add(signerInfo.getDigestAlgorithm());

    if (signerInfo.getAuthenticatedAttributes() != null) {
        v.add(new DERTaggedObject(false, 0, signerInfo.getAuthenticatedAttributes()));
    }

    v.add(signerInfo.getDigestEncryptionAlgorithm());
    v.add(signerInfo.getEncryptedDigest());

    if (unauthenticatedAttributes != null) {
        v.add(new DERTaggedObject(false, 1, unauthenticatedAttributes));
    }

    return new DERSequence(v);
}

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

License:Open Source License

/**
 * Remove any archive-timestamp-v2/3 attribute added after the timestampToken
 *//*from  w w w.  j  a v  a2  s .c  o  m*/
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes,
        TimestampToken timestampToken) {

    ASN1EncodableVector result = new ASN1EncodableVector();
    for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

        final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
        final ASN1ObjectIdentifier attrType = attribute.getAttrType();
        if (OID.id_aa_ets_archiveTimestampV2.equals(attrType)
                || OID.id_aa_ets_archiveTimestampV3.equals(attrType)) {
            try {

                TimeStampToken token = new TimeStampToken(new CMSSignedData(DSSASN1Utils
                        .getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive())));
                if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
                    continue;
                }
            } catch (Exception e) {
                throw new DSSException(e);
            }
        }
        result.add(unauthenticatedAttributes.getObjectAt(ii));
    }
    return new DERSequence(result);
}

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

License:Open Source License

public AttributeTable getSignedAttributes(final CAdESSignatureParameters parameters) {

    ASN1EncodableVector signedAttributes = new ASN1EncodableVector();

    addSigningCertificateAttribute(parameters, signedAttributes);
    addSigningTimeAttribute(parameters, signedAttributes);
    addSignerAttribute(parameters, signedAttributes);
    addSignaturePolicyId(parameters, signedAttributes);
    addContentHints(parameters, signedAttributes);
    addContentIdentifier(parameters, signedAttributes);
    addCommitmentType(parameters, signedAttributes);
    addSignerLocation(parameters, signedAttributes);
    addContentTimestamps(parameters, signedAttributes);

    // mime-type attribute breaks parallel signatures by adding PKCS7 as a mime-type for subsequent signers.
    // This attribute is not mandatory, so it has been disabled.

    final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
    return signedAttributesTable;
}

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

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)//from ww w.j  a v  a  2s  .com
 * 5.11.2 signer-location Attribute
 * The signer-location attribute specifies a mnemonic for an address associated with the signer at a particular
 * geographical (e.g. city) location. The mnemonic is registered in the country in which the signer is located and
 * is used in
 * the provision of the Public Telegram Service (according to Recommendation ITU-T F.1 [11]).
 * The signer-location attribute shall be a signed attribute.
 *
 * @param parameters
 * @param signedAttributes
 * @return
 */
private void addSignerLocation(final CAdESSignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    if (!padesUsage) {
        /*
         * In PAdES, the role is in the signature dictionary
         */
        final eu.europa.esig.dss.SignerLocation signerLocationParameter = parameters.bLevel()
                .getSignerLocation();
        if (signerLocationParameter != null) {

            final DERUTF8String country = signerLocationParameter.getCountry() == null ? null
                    : new DERUTF8String(signerLocationParameter.getCountry());
            final DERUTF8String locality = signerLocationParameter.getLocality() == null ? null
                    : new DERUTF8String(signerLocationParameter.getLocality());
            final ASN1EncodableVector postalAddress = new ASN1EncodableVector();
            final List<String> postalAddressParameter = signerLocationParameter.getPostalAddress();
            if (postalAddressParameter != null) {
                for (final String addressLine : postalAddressParameter) {
                    postalAddress.add(new DERUTF8String(addressLine));
                }
            }
            final DERSequence derSequencePostalAddress = new DERSequence(postalAddress);
            final SignerLocation signerLocation = new SignerLocation(country, locality,
                    derSequencePostalAddress);
            final DERSet attrValues = new DERSet(signerLocation);
            final Attribute attribute = new Attribute(id_aa_ets_signerLocation, attrValues);
            signedAttributes.add(attribute);
        }
    }
}

From source file:eu.europa.esig.dss.cades.signature.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);
    }/*w  w  w. ja v a  2  s  .  c  om*/
    vector.add(certificatesHashIndex);
    vector.add(crLsHashIndex);
    vector.add(unsignedAttributesHashIndex);
    final ASN1Sequence derSequence = new DERSequence(vector);
    return new Attribute(id_aa_ATSHashIndex, new DERSet(derSequence));
}

From source file:eu.europa.esig.dss.cades.signature.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.
 *
 * @return//from  ww  w  .j  a v a 2s.c o  m
 * @throws eu.europa.esig.dss.DSSException
 */
private ASN1Sequence getCertificatesHashIndex() throws DSSException {

    final ASN1EncodableVector certificatesHashIndexVector = new ASN1EncodableVector();

    final List<CertificateToken> certificateTokens = cadesSignature.getCertificates();
    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(), Hex.encodeHexString(digest));
        }
        final DEROctetString derOctetStringDigest = new DEROctetString(digest);
        certificatesHashIndexVector.add(derOctetStringDigest);
    }
    return new DERSequence(certificatesHashIndexVector);
}

From source file:eu.europa.esig.dss.cades.signature.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.
 *
 * @return/*from   w  w w.java2s .  c  om*/
 * @throws eu.europa.esig.dss.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getCRLsHashIndex() 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);
}