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.validation102853.cades.CAdESSignature.java

License:Open Source License

/**
 * This method handles the archive-timestamp-v2
 * <p/>//  w  w w .  j a  va  2 s. c om
 * The value of the messageImprint field within TimeStampToken shall be a hash of the concatenation of:
 *  the encapContentInfo element of the SignedData sequence;
 *  any external content being protected by the signature, if the eContent element of the encapContentInfo is omitted;
 *  the Certificates and crls elements of the SignedData sequence, when present; and
 *  all data elements in the SignerInfo sequence including all signed and unsigned attributes.
 * <p/>
 * NOTE 1: An alternative archiveTimestamp attribute, identified by an object identifier { iso(1) member-body(2)
 * us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-aa(2) 27, is defined in prior versions of
 * TS 101 733. The archiveTimestamp attribute, defined in versions of TS 101 733 prior to 1.5.1, is not
 * compatible with the attribute defined in the present document. The archiveTimestamp attribute, defined in
 * versions 1.5.1 to 1.6.3 of TS 101 733, is compatible with the present document if the content is internal to
 * encapContentInfo. Unless the version of TS 101 733 employed by the signing party is known by all
 * recipients, use of the archiveTimestamp attribute defined in prior versions of TS 101 733 is deprecated.
 * NOTE 2: Counter signatures held as countersignature attributes do not require independent archive time-stamps as
 * they are protected by the archive time-stamp against the containing SignedData structure.
 * NOTE 3: Unless DER is used throughout, it is recommended that the binary encoding of the ASN.1 structures
 * being time-stamped be preserved when being archived to ensure that the recalculation of the data hash is
 * consistent.
 * NOTE 4: The hash is calculated over the concatenated data elements as received /stored including the Type and
 * Length encoding.
 * NOTE 5: Whilst it is recommended that unsigned attributes be DER encoded, it cannot generally be so guaranteed
 * except by prior arrangement.
 *
 * @param timestampToken
 * @return
 * @throws DSSException
 */
private byte[] getArchiveTimestampDataV2(TimestampToken timestampToken) throws DSSException {

    try {

        final ByteArrayOutputStream data = new ByteArrayOutputStream();

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

        ContentInfo content = signedData.getEncapContentInfo();
        if (content == null || content.getContent() == null) {
            /* Detached signatures have either no encapContentInfo in signedData, or it exists but has no eContent */
            if (getOriginalDocumentBytes() != null) {
                data.write(content.toASN1Primitive().getEncoded());
                data.write(getOriginalDocumentBytes());
            } else {
                throw new DSSException("Signature is detached and no original data provided.");
            }
        } else {

            ASN1OctetString octet = (ASN1OctetString) content.getContent();

            ContentInfo info2 = new ContentInfo(PKCSObjectIdentifiers.data, octet);
            final byte[] contentInfoBytes = info2.getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Content Info: {}", DSSUtils.toHex(contentInfoBytes));
            }
            data.write(contentInfoBytes);
        }
        final ASN1Set certificates = signedData.getCertificates();
        if (certificates != null) {

            final byte[] certificatesBytes = new DERTaggedObject(false, 0,
                    new DERSequence(certificates.toArray())).getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Certificates: {}", DSSUtils.toHex(certificatesBytes));
            }
            data.write(certificatesBytes);
        }
        if (signedData.getCRLs() != null) {

            final byte[] crlBytes = signedData.getCRLs().getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("CRLs: {}", DSSUtils.toHex(crlBytes));
            }
            data.write(crlBytes);
        }
        final SignerInfo signerInfo = signerInformation.toASN1Structure();
        final ByteArrayOutputStream signerByteArrayOutputStream = new ByteArrayOutputStream();
        final ASN1Set unauthenticatedAttributes = signerInfo.getUnauthenticatedAttributes();
        final ASN1Sequence filteredUnauthenticatedAttributes = filterUnauthenticatedAttributes(
                unauthenticatedAttributes, timestampToken);
        final ASN1Sequence asn1Object = getSignerInfoEncoded(signerInfo, filteredUnauthenticatedAttributes);
        for (int ii = 0; ii < asn1Object.size(); ii++) {

            final byte[] signerInfoBytes = DSSASN1Utils
                    .getDEREncoded(asn1Object.getObjectAt(ii).toASN1Primitive());
            signerByteArrayOutputStream.write(signerInfoBytes);
        }
        final byte[] signerInfoBytes = signerByteArrayOutputStream.toByteArray();
        if (LOG.isTraceEnabled()) {
            LOG.trace("SignerInfoBytes: {}", DSSUtils.toHex(signerInfoBytes));
        }
        data.write(signerInfoBytes);

        final byte[] result = data.toByteArray();
        return result;

    } catch (IOException e) {
        throw new DSSException(e);
    } catch (Exception e) {
        // When error in computing or in format the algorithm just continues.
        LOG.warn("When error in computing or in format the algorithm just continue...", e);
        return DSSUtils.EMPTY_BYTE_ARRAY;
    }
}

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 .java  2 s .c o m*/
 * @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 .  ja  v  a2s  .co 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.ec.markt.dss.validation102853.crl.CRLToken.java

License:Open Source License

/**
 * @return the a copy of x509crl as a X509CRLHolder
 *//*ww w .  ja v a  2s .c o m*/
public X509CRLHolder getX509CrlHolder() {

    try {
        final X509CRL x509crl = getX509crl();
        final TBSCertList tbsCertList = TBSCertList.getInstance(x509crl.getTBSCertList());
        final AlgorithmIdentifier sigAlgOID = new AlgorithmIdentifier(
                new ASN1ObjectIdentifier(x509crl.getSigAlgOID()));
        final byte[] signature = x509crl.getSignature();
        final X509CRLHolder x509crlHolder = new X509CRLHolder(new CertificateList(
                new DERSequence(new ASN1Encodable[] { tbsCertList, sigAlgOID, new DERBitString(signature) })));
        return x509crlHolder;
    } catch (CRLException e) {
        throw new DSSException(e);
    }
}

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   w  ww. j a  v  a 2 s  .c  o  m*/
 * 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.CAdESLevelBaselineB.java

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)//w  w w . j av  a2  s. c om
 *
 * 5.11.1 commitment-type-indication Attribute
 * There may be situations where a signer wants to explicitly indicate to a verifier that by signing the data, it
 * illustrates a
 * type of commitment on behalf of the signer. The commitment-type-indication attribute conveys such
 * information.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addCommitmentType(final CAdESSignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    // TODO (19/08/2014): commitmentTypeQualifier is not implemented
    final BLevelParameters bLevelParameters = parameters.bLevel();

    final List<String> commitmentTypeIndications = bLevelParameters.getCommitmentTypeIndications();
    if (CollectionUtils.isNotEmpty(commitmentTypeIndications)) {

        final int size = commitmentTypeIndications.size();
        ASN1Encodable[] asn1Encodables = new ASN1Encodable[size];
        for (int ii = 0; ii < size; ii++) {

            final String commitmentTypeId = commitmentTypeIndications.get(ii);
            final ASN1ObjectIdentifier objectIdentifier = new ASN1ObjectIdentifier(commitmentTypeId);
            // final CommitmentTypeIndication commitmentTypeIndication = new
            // CommitmentTypeIndication(objectIdentifier);
            // final ASN1Primitive asn1Primitive = commitmentTypeIndication.toASN1Primitive();
            asn1Encodables[ii] = new DERSequence(objectIdentifier);
        }
        final DERSet attrValues = new DERSet(asn1Encodables);
        final Attribute attribute = new Attribute(id_aa_ets_commitmentType, attrValues);
        signedAttributes.add(attribute);
    }
}

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

License:Open Source License

/**
 * @return the a copy of x509crl as a X509CRLHolder
 *//*  w  w  w . jav a 2 s . c o  m*/
private X509CRLHolder getX509CrlHolder(CRLToken crlToken) {
    try {
        final X509CRL x509crl = crlToken.getX509crl();
        final TBSCertList tbsCertList = TBSCertList.getInstance(x509crl.getTBSCertList());
        final AlgorithmIdentifier sigAlgOID = new AlgorithmIdentifier(
                new ASN1ObjectIdentifier(x509crl.getSigAlgOID()));
        final byte[] signature = x509crl.getSignature();
        final DERSequence seq = new DERSequence(
                new ASN1Encodable[] { tbsCertList, sigAlgOID, new DERBitString(signature) });
        final CertificateList x509CRL = new CertificateList(seq);
        // final CertificateList x509CRL = new
        // CertificateList.getInstance((Object)seq);
        final X509CRLHolder x509crlHolder = new X509CRLHolder(x509CRL);
        return x509crlHolder;
    } catch (CRLException e) {
        throw new DSSException(e);
    }
}

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 .  com*/
    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   w  w w . j  a v a  2  s  .c om*/
 * @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//w  w w .  ja v  a 2s.  c  o  m
 * @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);
}