Example usage for org.bouncycastle.asn1 ASN1Set toArray

List of usage examples for org.bouncycastle.asn1 ASN1Set toArray

Introduction

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

Prototype

public ASN1Encodable[] toArray() 

Source Link

Usage

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

License:Open Source License

private List<TimestampToken> getTimestampList(final ASN1ObjectIdentifier attrType,
        final TimestampType timestampType, final ArchiveTimestampType archiveTimestampType) {

    final List<TimestampToken> list = new ArrayList<TimestampToken>();

    final AttributeTable attributes;
    if (attrType.equals(PKCSObjectIdentifiers.id_aa_ets_contentTimestamp)) {

        attributes = signerInformation.getSignedAttributes();
    } else {//from w w w .j a  v a  2  s .co m

        attributes = signerInformation.getUnsignedAttributes();
    }
    if (attributes == null) {
        return list;
    }
    final ASN1EncodableVector archiveList = attributes.getAll(attrType);
    for (int i = 0; i < archiveList.size(); i++) {
        final Attribute attribute = (Attribute) archiveList.get(i);

        final ASN1Set attrValues = attribute.getAttrValues();
        for (final ASN1Encodable value : attrValues.toArray()) {
            try {
                TimeStampToken token = new TimeStampToken(
                        new CMSSignedData(value.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
                final TimestampToken timestampToken = new TimestampToken(token, timestampType, certPool);
                timestampToken.setArchiveTimestampType(archiveTimestampType);
                list.add(timestampToken);
            } catch (Exception e) {
                throw new RuntimeException("Parsing error", e);
            }
        }
    }
    return list;
}

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

License:Open Source License

/**
 * This method handles the archive-timestamp-v2
 * <p/>/*from  w  ww. j a v  a  2  s.c o m*/
 * 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.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

private List<TimestampToken> createTimestamps(final ASN1ObjectIdentifier attrType,
        final TimestampType timestampType, final ArchiveTimestampType archiveTimestampType) {

    final List<TimestampToken> timestampTokenList = new ArrayList<TimestampToken>();
    final AttributeTable attributes = attrType.equals(id_aa_ets_contentTimestamp)
            ? signerInformation.getSignedAttributes()
            : signerInformation.getUnsignedAttributes();
    if (attributes != null) {

        final ASN1EncodableVector allAttributes = attributes.getAll(attrType);
        for (int ii = 0; ii < allAttributes.size(); ii++) {
            final Attribute attribute = (Attribute) allAttributes.get(ii);
            final ASN1Set attrValues = attribute.getAttrValues();
            for (final ASN1Encodable value : attrValues.toArray()) {
                if (value instanceof DEROctetString) {
                    LOG.warn("Illegal content for timestamp (OID : " + attrType
                            + ") : OCTET STRING is not allowed !");
                } else {
                    try {
                        byte[] encoded = value.toASN1Primitive().getEncoded();
                        final CMSSignedData signedData = new CMSSignedData(encoded);
                        final TimeStampToken token = new TimeStampToken(signedData);
                        final TimestampToken timestampToken = new TimestampToken(token, timestampType,
                                certPool);

                        timestampToken.setArchiveTimestampType(archiveTimestampType);
                        timestampTokenList.add(timestampToken);
                    } catch (Exception e) {
                        throw new DSSException(e);
                    }//from  www  . j ava  2 s. co m
                }
            }
        }
    }
    return timestampTokenList;
}

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

License:Open Source License

/**
 * This method handles the archive-timestamp-v2
 * 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.//w  w  w. j  a  va 2 s . c  om
 * 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 (getOriginalDocumentStream() != null) {
                data.write(content.toASN1Primitive().getEncoded());
                IOUtils.copy(getOriginalDocumentStream(), data);
            } 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:net.sf.keystore_explorer.crypto.x509.X509Ext.java

License:Open Source License

private String getVeriSignNonVerified(byte[] octets) throws IOException {

    /*//from w  w  w.  j  a v a2 s  .c  om
        NonVerified ::= SET OF ATTRIBUTE
     */

    StringBuilder sb = new StringBuilder();

    ASN1Set asn1Set = ASN1Set.getInstance(octets);
    for (ASN1Encodable attribute : asn1Set.toArray()) {

        ASN1ObjectIdentifier attributeId = ((Attribute) attribute).getAttrType();
        ASN1Set attributeValues = ((Attribute) attribute).getAttrValues();

        for (ASN1Encodable attributeValue : attributeValues.toArray()) {

            String attributeValueStr = getAttributeValueString(attributeId, attributeValue);

            sb.append(MessageFormat.format("{0}={1}", attributeId.getId(), attributeValueStr));
            sb.append(NEWLINE);
        }
    }

    return sb.toString();
}

From source file:org.broad.igv.feature.AminoAcidManager.java

License:LGPL

/**
 * Load codon tables from the specified path. If any exceptions occur
 * while loading, no changes are made to this instance.
 * <p/>/*  w w w.  j a  v a2s.  c  o  m*/
 * Note that the new codon tables are ADDED to the existing tables
 * <p/>
 * The currentCodonTable is set to be the codonTable with id = defaultid if present
 * If not, the first one in the array is set as default
 *
 * @param codonTablesPath
 * @return
 */
synchronized void loadCodonTables(String codonTablesPath) throws IOException, JsonParseException {
    LinkedHashMap<CodonTableKey, CodonTable> newCodonTables = new LinkedHashMap<CodonTableKey, CodonTable>(20);
    CodonTable defaultCodonTable = null;

    InputStream is = AminoAcidManager.class.getResourceAsStream(codonTablesPath);
    if (is == null) {
        is = ParsingUtils.openInputStream(codonTablesPath);
    }

    if (codonTablesPath.endsWith(".json")) {
        JsonObject allData = readJSONFromStream(is);
        int defaultId = -1;
        defaultId = allData.get("defaultid").getAsInt();
        JsonArray codonArray = allData.get("Genetic-code-table").getAsJsonArray();
        if (codonArray.size() == 0) {
            throw new JsonParseException("JSON File has empty array for Genetic-code-table");
        }
        for (int ca = 0; ca < codonArray.size(); ca++) {
            CodonTable curTable = CodonTable.createFromJSON(codonTablesPath,
                    codonArray.get(ca).getAsJsonObject());
            newCodonTables.put(curTable.getKey(), curTable);
            if (defaultCodonTable == null || curTable.getId() == defaultId) {
                defaultCodonTable = curTable;
            }
        }
    } else if (codonTablesPath.endsWith(".asn1") || codonTablesPath.endsWith(".val")) {
        ASN1InputStream ASNis = new ASN1InputStream(is);
        ASN1Primitive obj = ASNis.readObject();
        ASN1Set set = (ASN1Set) obj;
        //Array of different genetic code tables
        ASN1Encodable[] codonArray = set.toArray();
        if (codonArray.length == 0) {
            throw new RuntimeException("ASN1 File has empty array for Genetic-code-table");
        }
        for (ASN1Encodable aCodonArray : codonArray) {
            CodonTable curTable = CodonTable.createFromASN1(codonTablesPath, aCodonArray);
            newCodonTables.put(curTable.getKey(), curTable);
            if (defaultCodonTable == null) {
                defaultCodonTable = curTable;
            }
        }
    } else {
        throw new IllegalArgumentException("Unknown file type, must be .json or .asn1");
    }

    allCodonTables.putAll(newCodonTables);
    currentCodonTable = defaultCodonTable;
}