Example usage for org.bouncycastle.asn1.cms AttributeTable getAll

List of usage examples for org.bouncycastle.asn1.cms AttributeTable getAll

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms AttributeTable getAll.

Prototype

public ASN1EncodableVector getAll(ASN1ObjectIdentifier oid) 

Source Link

Document

Return all the attributes matching the OBJECT IDENTIFIER oid.

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  ww. j ava2  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.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   w  w  w.j  ava 2  s.co m
                }
            }
        }
    }
    return timestampTokenList;
}

From source file:org.signserver.module.tsa.TimeStampSignerTest.java

License:Open Source License

private int testWithHash(final ASN1ObjectIdentifier hashAlgo) throws Exception {
    int reqid = random.nextInt();
    TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(hashAlgo,
            new byte[getHashLength(hashAlgo)], BigInteger.valueOf(100));

    byte[] requestBytes = timeStampRequest.getEncoded();

    GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);

    final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER1, signRequest,
            new RequestContext());

    final CertificateFactory factory = CertificateFactory.getInstance("X.509");
    final X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new ByteArrayInputStream(Base64.decode(CERTSTRING.getBytes())));

    TimeStampResponse timeStampResponse = null;
    try {/*from   w w w . j a  va 2  s  .c o m*/
        // check response
        timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
        timeStampResponse.validate(timeStampRequest);

        if (timeStampResponse.getStatus() != PKIStatus.GRANTED) {
            // return early and don't attempt to get a token
            return timeStampResponse.getStatus();
        }

        // check the hash value from the response
        TimeStampToken token = timeStampResponse.getTimeStampToken();
        AlgorithmIdentifier algo = token.getTimeStampInfo().getHashAlgorithm();
        assertEquals("Timestamp response is using incorrect hash algorithm", hashAlgo, algo.getAlgorithm());

        Collection signerInfos = token.toCMSSignedData().getSignerInfos().getSigners();

        // there should be one SignerInfo
        assertEquals("There should only be one signer in the timestamp response", 1, signerInfos.size());

        for (Object o : signerInfos) {
            SignerInformation si = (SignerInformation) o;

            // test the response signature algorithm
            assertEquals("Timestamp used unexpected signature algorithm", TSPAlgorithms.SHA1.toString(),
                    si.getDigestAlgOID());
            assertEquals("Timestamp is signed with unexpected signature encryption algorithm",
                    "1.2.840.113549.1.1.1", si.getEncryptionAlgOID());

            final AttributeTable attrs = si.getSignedAttributes();
            final ASN1EncodableVector scAttrs = attrs.getAll(PKCSObjectIdentifiers.id_aa_signingCertificate);

            assertEquals("Should contain a signingCertificate signed attribute", 1, scAttrs.size());

            TestUtils.checkSigningCertificateAttribute(ASN1Sequence.getInstance(scAttrs.get(0)), cert);
        }

    } catch (TSPException e) {
        fail("Failed to verify response");
    } catch (IOException e) {
        fail("Failed to verify response");
    }

    final TimeStampToken token = timeStampResponse.getTimeStampToken();

    try {

        token.validate(cert, "BC");

    } catch (TSPException e) {
        fail("Failed to validate response token");
    }

    return timeStampResponse.getStatus();
}

From source file:org.votingsystem.callable.MessageTimeStamper.java

License:Open Source License

public byte[] getDigestToken() {
    if (timeStampToken == null)
        return null;
    CMSSignedData tokenCMSSignedData = timeStampToken.toCMSSignedData();
    Collection signers = tokenCMSSignedData.getSignerInfos().getSigners();
    SignerInformation tsaSignerInfo = (SignerInformation) signers.iterator().next();
    AttributeTable signedAttrTable = tsaSignerInfo.getSignedAttributes();
    ASN1EncodableVector v = signedAttrTable.getAll(CMSAttributes.messageDigest);
    Attribute t = (Attribute) v.get(0);
    ASN1Set attrValues = t.getAttrValues();
    DERObject validMessageDigest = attrValues.getObjectAt(0).getDERObject();
    ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
    byte[] digestToken = signedMessageDigest.getOctets();
    //String digestTokenStr = new String(Base64.encode(digestToken));
    //log.info(" digestTokenStr: " + digestTokenStr);
    return digestToken;
}

From source file:org.votingsystem.signature.util.CMSUtils.java

License:Open Source License

public static DERObject getSingleValuedSignedAttribute(AttributeTable signedAttrTable,
        DERObjectIdentifier attrOID, String printableName) throws CMSException {
    if (signedAttrTable == null)
        return null;
    ASN1EncodableVector vector = signedAttrTable.getAll(attrOID);
    switch (vector.size()) {
    case 0:/*from w w  w  .  j a  v  a 2s  .c o  m*/
        return null;
    case 1:
        Attribute t = (Attribute) vector.get(0);
        ASN1Set attrValues = t.getAttrValues();
        if (attrValues.size() != 1)
            throw new CMSException("A " + printableName + " attribute MUST have a single attribute value");
        return attrValues.getObjectAt(0).getDERObject();
    default:
        throw new CMSException(
                "The SignedAttributes in a signerInfo MUST NOT include multiple instances of the "
                        + printableName + " attribute");
    }
}

From source file:org.votingsystem.signature.util.CMSUtils.java

License:Open Source License

public static byte[] getDigestToken(TimeStampToken timeStampToken) {
    if (timeStampToken == null)
        return null;
    CMSSignedData tokenCMSSignedData = timeStampToken.toCMSSignedData();
    Collection signers = tokenCMSSignedData.getSignerInfos().getSigners();
    SignerInformation tsaSignerInfo = (SignerInformation) signers.iterator().next();

    AttributeTable signedAttrTable = tsaSignerInfo.getSignedAttributes();
    ASN1EncodableVector v = signedAttrTable.getAll(CMSAttributes.messageDigest);
    Attribute t = (Attribute) v.get(0);
    ASN1Set attrValues = t.getAttrValues();
    DERObject validMessageDigest = attrValues.getObjectAt(0).getDERObject();

    ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
    byte[] digestToken = signedMessageDigest.getOctets();
    //String digestTokenStr = new String(Base64.encode(digestToken));
    return digestToken;
}

From source file:se.tillvaxtverket.ttsigvalws.ttwssigvalidation.pdf.PdfSignatureVerifier.java

License:Open Source License

private static void checkTimestamps(CMSSignedDataParser sp, CMSSigVerifyResult sigResult) throws CMSException {
    List<TimeStampResult> timeStampResultList = sigResult.getTimStampResultList();
    sigResult.setTimStampResultList(timeStampResultList);
    SignerInformationStore signers = sp.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();/*w w  w . j  av  a 2s.com*/
    if (!it.hasNext()) {
        return;
    }
    SignerInformation signer = (SignerInformation) it.next();

    //Collect and check time stamps
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
    if (unsignedAttributes == null) {
        return;
    }
    ASN1EncodableVector timeStamps = unsignedAttributes
            .getAll(new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.2.14"));
    if (timeStamps.size() == 0) {
        return;
    }
    for (int i = 0; i < timeStamps.size(); i++) {
        try {
            Attribute timestampAttr = Attribute.getInstance(timeStamps.get(i));
            byte[] timeStampBytes = timestampAttr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
            TimeStampResult tsResult = new TimeStampResult();
            tsResult.setTimestamp(timeStampBytes);
            timeStampResultList.add(tsResult);

            InputStream tsis = new ByteArrayInputStream(timeStampBytes);
            CMSSignedDataParser tsSp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), tsis);

            byte[] tsInfoBytes = IOUtils.toByteArray(tsSp.getSignedContent().getContentStream());
            TimeStampData timeStampData = PdfBoxSigUtil.getTimeStampData(tsInfoBytes);
            tsResult.setTsData(timeStampData);

            //Compare TimeStamp data hash with signature hash
            byte[] sigHash = getDigest(timeStampData.getImprintHashAlgo(), signer.getSignature());
            tsResult.setTimestampMatch(Arrays.equals(sigHash, timeStampData.getImprintDigest()));

            CMSSigVerifyResult tsSigResult = new CMSSigVerifyResult();
            tsSigResult.setSignedData(timeStampBytes);
            tsResult.setSignatureVerification(tsSigResult);

            verifyCMSSignature(tsSp, tsSigResult);
        } catch (Exception e) {
        }

    }
    sigResult.setTimStampResultList(timeStampResultList);
}