Example usage for org.bouncycastle.asn1.cms SignedData getCRLs

List of usage examples for org.bouncycastle.asn1.cms SignedData getCRLs

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms SignedData getCRLs.

Prototype

public ASN1Set getCRLs() 

Source Link

Usage

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
static protected SignedData includeCrls(byte[] assinatura, Collection crls) throws IOException, Exception,
        SecurityException, CRLException, NoSuchProviderException, NoSuchAlgorithmException {

    org.bouncycastle.asn1.pkcs.SignedData pkcs7 = pkcs7SignedData(assinatura);

    ContentInfo content = new ContentInfo(CMSObjectIdentifiers.data, null);

    SignedData signedCms = new SignedData(pkcs7.getDigestAlgorithms(), content, pkcs7.getCertificates(),
            pkcs7.getCRLs(), pkcs7.getSignerInfos());

    ASN1EncodableVector vec = new ASN1EncodableVector();

    for (X509CRLObject crl : (Collection<X509CRLObject>) crls)
        vec.add(ASN1Primitive.fromByteArray(crl.getEncoded()));

    DERSet set = new DERSet(vec);

    // for (X509CRLObject crl : (Collection<X509CRLObject>) crls)
    // set.addObject(ASN1Object.fromByteArray(crl.getEncoded()));

    SignedData signedCmsWithCrls = new SignedData(signedCms.getDigestAlgorithms(),
            signedCms.getEncapContentInfo(), signedCms.getCertificates(), set, signedCms.getSignerInfos());
    signedCmsWithCrls.getCertificates();
    signedCmsWithCrls.getCRLs();/*w  ww. jav a 2  s .  c  om*/
    return signedCmsWithCrls;
}

From source file:eu.europa.ec.markt.dss.signature.cades.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.
 *
 * @param cAdESSignature//from  w w  w  .  ja va 2s  .  com
 * @return
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getCRLsHashIndex(CAdESSignature cAdESSignature) 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);
}

From source file:eu.europa.ec.markt.dss.signature.cades.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.
 *
 * @param cAdESSignature/*  ww  w.  j a va2  s.  c  om*/
 * @return
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getVerifiedCRLsHashIndex(CAdESSignature cAdESSignature, TimestampToken timestampToken)
        throws DSSException {

    final ASN1Sequence crlHashes = getCRLHashIndex(timestampToken);
    final ArrayList<DEROctetString> crlHashesList = Collections.list(crlHashes.getObjects());

    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();
                handleRevocationEncoded(crlHashesList, DSSASN1Utils.getDEREncoded(asn1Encodable));
            }
        }
    }

    if (!crlHashesList.isEmpty()) {
        LOG.error("{} attribute hash in CRL Hashes have not been found in document attributes: {}",
                crlHashesList.size(), crlHashesList);
        // return a empty DERSequence to screw up the hash
        return new DERSequence();
    }

    return crlHashes;
}

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/* w w w  .j  a  v  a 2  s  . co  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

/**
 * This method handles the archive-timestamp-v2
 * <p/>/*from w  ww. j  a  va 2s .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.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//www .  j av  a2s  . 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);
}

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  .j a  v a2  s. c om
 * @throws eu.europa.esig.dss.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getVerifiedCRLsHashIndex(TimestampToken timestampToken) throws DSSException {

    final ASN1Sequence crlHashes = getCRLHashIndex(timestampToken);
    final List<DEROctetString> crlHashesList = new ArrayList<DEROctetString>();
    if (crlHashes != null) {
        crlHashesList.addAll(Collections.list(crlHashes.getObjects()));
    }

    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();
                handleRevocationEncoded(crlHashesList, DSSASN1Utils.getDEREncoded(asn1Encodable));
            }
        }
    }

    if (!crlHashesList.isEmpty()) {
        LOG.error("{} attribute hash in CRL Hashes have not been found in document attributes: {}",
                crlHashesList.size(), crlHashesList);
        // return a empty DERSequence to screw up the hash
        return new DERSequence();
    }

    return crlHashes;
}

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

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {//from   w  w w .ja va 2s. c  om

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

        ASN1InputStream asn1sInput = new ASN1InputStream(byteArray);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " "
                + encapContentInfo.getContent());

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            CertificateToken certificate = DSSASN1Utils.getCertificate(certificateHolder);
            X509Certificate x509Certificate = certificate.getCertificate();
            x509Certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(x509Certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

        SignerIdentifier sid = signedInfo.getSID();
        logger.info("SIGNER IDENTIFIER : " + sid.getId());

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = "";
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

        ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
        String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

        logger.info("SIGNATURE VALUE : " + signatureValue);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
        byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

        ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

        ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
        logger.info("Decrypted : " + seqDecrypt);

        DigestInfo digestInfo = new DigestInfo(seqDecrypt);
        assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

        String decryptedDigestEncodeBase64 = Utils.toBase64(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Utils.toBase64(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        Utils.closeQuietly(asn1sInput);
        Utils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

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

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/* www . j  a v  a2s.  co m*/

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

        ASN1InputStream asn1sInput = new ASN1InputStream(byteArray);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " "
                + encapContentInfo.getContent());

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            X509Certificate certificate = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);

            certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

        SignerIdentifier sid = signedInfo.getSID();
        logger.info("SIGNER IDENTIFIER : " + sid.getId());

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = StringUtils.EMPTY;
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

        ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
        String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

        logger.info("SIGNATURE VALUE : " + signatureValue);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
        byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

        ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

        ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
        logger.info("Decrypted : " + seqDecrypt);

        DigestInfo digestInfo = new DigestInfo(seqDecrypt);
        assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

        String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Base64.encodeBase64String(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        IOUtils.closeQuietly(asn1sInput);
        IOUtils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

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./*ww  w .  j a  va 2s. co  m*/
 * 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;
    }
}