Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

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

Introduction

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

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:com.itextpdf.signatures.CertificateInfo.java

License:Open Source License

/**
 * Get the "subject" from the TBSCertificate bytes that are passed in.
 *
 * @param enc A TBSCertificate in a byte array
 * @return a ASN1Primitive//from w w w  .  j av a  2  s .c om
 */
public static ASN1Primitive getSubject(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence) in.readObject();
        return (ASN1Primitive) seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 5 : 4);
    } catch (IOException e) {
        throw new PdfException(e);
    }
}

From source file:com.itextpdf.signatures.CertificateUtil.java

License:Open Source License

/**
 * @param certificate   the certificate from which we need the ExtensionValue
 * @param oid the Object Identifier value for the extension.
 * @return   the extension value as an ASN1Primitive object
 * @throws IOException/*  w w w.ja v  a  2 s  .c om*/
 */
private static ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
    byte[] bytes = SignUtils.getExtensionValueByOid(certificate, oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    return aIn.readObject();
}

From source file:com.itextpdf.signatures.LtvVerification.java

License:Open Source License

private PdfName getSignatureHashKey(String signatureName) throws NoSuchAlgorithmException, IOException {
    PdfDictionary dic = sgnUtil.getSignatureDictionary(signatureName);
    PdfString contents = dic.getAsString(PdfName.Contents);
    byte[] bc = PdfEncodings.convertToBytes(contents.getValue(), null);
    byte[] bt = null;
    if (PdfName.ETSI_RFC3161.equals(dic.getAsName(PdfName.SubFilter))) {
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(bc));
        ASN1Primitive pkcs = din.readObject();
        bc = pkcs.getEncoded();/*w  w w  .j  a  v a 2 s. c o m*/
    }
    bt = hashBytesSha1(bc);
    return new PdfName(convertToHex(bt));
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Use this constructor if you want to verify a signature using the sub-filter adbe.x509.rsa_sha1.
 *
 * @param contentsKey the /Contents key//from ww  w .  ja  v a2  s .c o m
 * @param certsKey    the /Cert key
 * @param provider    the provider or <code>null</code> for the default provider
 */
@SuppressWarnings("unchecked")
public PdfPKCS7(byte[] contentsKey, byte[] certsKey, String provider) {
    try {
        this.provider = provider;
        certs = SignUtils.readAllCerts(certsKey);
        signCerts = certs;
        signCert = (X509Certificate) SignUtils.getFirstElement(certs);
        crls = new ArrayList<>();

        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey));
        digest = ((ASN1OctetString) in.readObject()).getOctets();

        sig = SignUtils.getSignatureHelper("SHA1withRSA", provider);
        sig.initVerify(signCert.getPublicKey());

        // setting the oid to SHA1withRSA
        digestAlgorithmOid = "1.2.840.10040.4.3";
        digestEncryptionAlgorithmOid = "1.3.36.3.3.1.2";
    } catch (Exception e) {
        throw new PdfException(e);
    }
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Use this constructor if you want to verify a signature.
 *
 * @param contentsKey   the /Contents key
 * @param filterSubtype the filtersubtype
 * @param provider      the provider or <code>null</code> for the default provider
 *//* w  w  w . j  ava 2  s. com*/
@SuppressWarnings({ "unchecked" })
public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype, String provider) {
    this.filterSubtype = filterSubtype;
    isTsp = PdfName.ETSI_RFC3161.equals(filterSubtype);
    isCades = PdfName.ETSI_CAdES_DETACHED.equals(filterSubtype);
    try {
        this.provider = provider;
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey));

        //
        // Basic checks to make sure it's a PKCS#7 SignedData Object
        //
        ASN1Primitive pkcs;

        try {
            pkcs = din.readObject();
        } catch (IOException e) {
            throw new IllegalArgumentException(PdfException.CannotDecodePkcs7SigneddataObject);
        }
        if (!(pkcs instanceof ASN1Sequence)) {
            throw new IllegalArgumentException(PdfException.NotAValidPkcs7ObjectNotASequence);
        }
        ASN1Sequence signedData = (ASN1Sequence) pkcs;
        ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
            throw new IllegalArgumentException(PdfException.NotAValidPkcs7ObjectNotSignedData);
        ASN1Sequence content = (ASN1Sequence) ((ASN1TaggedObject) signedData.getObjectAt(1)).getObject();
        // the positions that we care are:
        //     0 - version
        //     1 - digestAlgorithms
        //     2 - possible ID_PKCS7_DATA
        //     (the certificates and crls are taken out by other means)
        //     last - signerInfos

        // the version
        version = ((ASN1Integer) content.getObjectAt(0)).getValue().intValue();

        // the digestAlgorithms
        digestalgos = new HashSet<>();
        Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects();
        while (e.hasMoreElements()) {
            ASN1Sequence s = (ASN1Sequence) e.nextElement();
            ASN1ObjectIdentifier o = (ASN1ObjectIdentifier) s.getObjectAt(0);
            digestalgos.add(o.getId());
        }

        // the possible ID_PKCS7_DATA
        ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2);
        if (rsaData.size() > 1) {
            ASN1OctetString rsaDataContent = (ASN1OctetString) ((ASN1TaggedObject) rsaData.getObjectAt(1))
                    .getObject();
            RSAdata = rsaDataContent.getOctets();
        }

        int next = 3;
        while (content.getObjectAt(next) instanceof ASN1TaggedObject)
            ++next;

        // the certificates
        /*
                    This should work, but that's not always the case because of a bug in BouncyCastle:
        */
        certs = SignUtils.readAllCerts(contentsKey);
        /*
                    The following workaround was provided by Alfonso Massa, but it doesn't always work either.
                
                    ASN1Set certSet = null;
                    ASN1Set crlSet = null;
                    while (content.getObjectAt(next) instanceof ASN1TaggedObject) {
        ASN1TaggedObject tagged = (ASN1TaggedObject)content.getObjectAt(next);
                
        switch (tagged.getTagNo()) {
        case 0:
            certSet = ASN1Set.getInstance(tagged, false);
            break;
        case 1:
            crlSet = ASN1Set.getInstance(tagged, false);
            break;
        default:
            throw new IllegalArgumentException("unknown tag value " + tagged.getTagNo());
        }
        ++next;
                    }
                    certs = new ArrayList<Certificate>(certSet.size());
                
                    CertificateFactory certFact = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
                    for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) {
        ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive();
        if (obj instanceof ASN1Sequence) {
           ByteArrayInputStream stream = new ByteArrayInputStream(obj.getEncoded());
           X509Certificate x509Certificate = (X509Certificate)certFact.generateCertificate(stream);
           stream.close();
        certs.add(x509Certificate);
        }
                    }
        */
        // the signerInfos
        ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next);
        if (signerInfos.size() != 1)
            throw new IllegalArgumentException(
                    PdfException.ThisPkcs7ObjectHasMultipleSignerinfosOnlyOneIsSupportedAtThisTime);
        ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0);
        // the positions that we care are
        //     0 - version
        //     1 - the signing certificate issuer and serial number
        //     2 - the digest algorithm
        //     3 or 4 - digestEncryptionAlgorithm
        //     4 or 5 - encryptedDigest
        signerversion = ((ASN1Integer) signerInfo.getObjectAt(0)).getValue().intValue();
        // Get the signing certificate
        ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1);
        X509Principal issuer = SignUtils.getIssuerX509Name(issuerAndSerialNumber);
        BigInteger serialNumber = ((ASN1Integer) issuerAndSerialNumber.getObjectAt(1)).getValue();
        for (Object element : certs) {
            X509Certificate cert = (X509Certificate) element;
            if (cert.getIssuerDN().equals(issuer) && serialNumber.equals(cert.getSerialNumber())) {
                signCert = cert;
                break;
            }
        }
        if (signCert == null) {
            throw new PdfException(PdfException.CannotFindSigningCertificateWithSerial1)
                    .setMessageParams(issuer.getName() + " / " + serialNumber.toString(16));
        }
        signCertificateChain();
        digestAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0))
                .getId();
        next = 3;
        boolean foundCades = false;
        if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
            ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next);
            ASN1Set sseq = ASN1Set.getInstance(tagsig, false);
            sigAttr = sseq.getEncoded();
            // maybe not necessary, but we use the following line as fallback:
            sigAttrDer = sseq.getEncoded(ASN1Encoding.DER);

            for (int k = 0; k < sseq.size(); ++k) {
                ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k);
                String idSeq2 = ((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId();
                if (idSeq2.equals(SecurityIDs.ID_MESSAGE_DIGEST)) {
                    ASN1Set set = (ASN1Set) seq2.getObjectAt(1);
                    digestAttr = ((ASN1OctetString) set.getObjectAt(0)).getOctets();
                } else if (idSeq2.equals(SecurityIDs.ID_ADBE_REVOCATION)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    for (int j = 0; j < seqout.size(); ++j) {
                        ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j);
                        if (tg.getTagNo() == 0) {
                            ASN1Sequence seqin = (ASN1Sequence) tg.getObject();
                            findCRL(seqin);
                        }
                        if (tg.getTagNo() == 1) {
                            ASN1Sequence seqin = (ASN1Sequence) tg.getObject();
                            findOcsp(seqin);
                        }
                    }
                } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V1)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    SigningCertificate sv2 = SigningCertificate.getInstance(seqout);
                    ESSCertID[] cerv2m = sv2.getCerts();
                    ESSCertID cerv2 = cerv2m[0];
                    byte[] enc2 = signCert.getEncoded();
                    MessageDigest m2 = SignUtils.getMessageDigest("SHA-1");
                    byte[] signCertHash = m2.digest(enc2);
                    byte[] hs2 = cerv2.getCertHash();
                    if (!Arrays.equals(signCertHash, hs2))
                        throw new IllegalArgumentException(
                                "Signing certificate doesn't match the ESS information.");
                    foundCades = true;
                } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    SigningCertificateV2 sv2 = SigningCertificateV2.getInstance(seqout);
                    ESSCertIDv2[] cerv2m = sv2.getCerts();
                    ESSCertIDv2 cerv2 = cerv2m[0];
                    AlgorithmIdentifier ai2 = cerv2.getHashAlgorithm();
                    byte[] enc2 = signCert.getEncoded();
                    MessageDigest m2 = SignUtils
                            .getMessageDigest(DigestAlgorithms.getDigest(ai2.getAlgorithm().getId()));
                    byte[] signCertHash = m2.digest(enc2);
                    byte[] hs2 = cerv2.getCertHash();
                    if (!Arrays.equals(signCertHash, hs2))
                        throw new IllegalArgumentException(
                                "Signing certificate doesn't match the ESS information.");
                    foundCades = true;
                }
            }
            if (digestAttr == null)
                throw new IllegalArgumentException(PdfException.AuthenticatedAttributeIsMissingTheDigest);
            ++next;
        }
        if (isCades && !foundCades)
            throw new IllegalArgumentException("CAdES ESS information missing.");
        digestEncryptionAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++))
                .getObjectAt(0)).getId();
        digest = ((ASN1OctetString) signerInfo.getObjectAt(next++)).getOctets();
        if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
            ASN1TaggedObject taggedObject = (ASN1TaggedObject) signerInfo.getObjectAt(next);
            ASN1Set unat = ASN1Set.getInstance(taggedObject, false);
            AttributeTable attble = new AttributeTable(unat);
            Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
            if (ts != null && ts.getAttrValues().size() > 0) {
                ASN1Set attributeValues = ts.getAttrValues();
                ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0));
                org.bouncycastle.asn1.cms.ContentInfo contentInfo = org.bouncycastle.asn1.cms.ContentInfo
                        .getInstance(tokenSequence);
                this.timeStampToken = new TimeStampToken(contentInfo);
            }
        }
        if (isTsp) {
            org.bouncycastle.asn1.cms.ContentInfo contentInfoTsp = org.bouncycastle.asn1.cms.ContentInfo
                    .getInstance(signedData);
            this.timeStampToken = new TimeStampToken(contentInfoTsp);
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            String algOID = info.getHashAlgorithm().getAlgorithm().getId();
            messageDigest = DigestAlgorithms.getMessageDigestFromOid(algOID, null);
        } else {
            if (RSAdata != null || digestAttr != null) {
                if (PdfName.Adbe_pkcs7_sha1.equals(getFilterSubtype())) {
                    messageDigest = DigestAlgorithms.getMessageDigest("SHA1", provider);
                } else {
                    messageDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider);
                }
                encContDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider);
            }
            sig = initSignature(signCert.getPublicKey());
        }
    } catch (Exception e) {
        throw new PdfException(e);
    }
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
 * in the signerInfo can also be set, OR a time-stamp-authority client
 * may be provided./* ww w  . j  av a2  s . c  o m*/
 *
 * @param secondDigest the digest in the authenticatedAttributes
 * @param tsaClient    TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object
 */
public byte[] getEncodedPKCS7(byte[] secondDigest, ITSAClient tsaClient, byte[] ocsp,
        Collection<byte[]> crlBytes, PdfSigner.CryptoStandard sigtype) {
    try {
        if (externalDigest != null) {
            digest = externalDigest;
            if (RSAdata != null)
                RSAdata = externalRSAdata;
        } else if (externalRSAdata != null && RSAdata != null) {
            RSAdata = externalRSAdata;
            sig.update(RSAdata);
            digest = sig.sign();
        } else {
            if (RSAdata != null) {
                RSAdata = messageDigest.digest();
                sig.update(RSAdata);
            }
            digest = sig.sign();
        }

        // Create the set of Hash algorithms
        ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
        for (Object element : digestalgos) {
            ASN1EncodableVector algos = new ASN1EncodableVector();
            algos.add(new ASN1ObjectIdentifier((String) element));
            algos.add(DERNull.INSTANCE);
            digestAlgorithms.add(new DERSequence(algos));
        }

        // Create the contentInfo.
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
        if (RSAdata != null)
            v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
        DERSequence contentinfo = new DERSequence(v);

        // Get all the certificates
        //
        v = new ASN1EncodableVector();
        for (Object element : certs) {
            ASN1InputStream tempstream = new ASN1InputStream(
                    new ByteArrayInputStream(((X509Certificate) element).getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.
        //
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version
        //
        signerinfo.add(new ASN1Integer(signerversion));

        v = new ASN1EncodableVector();
        v.add(CertificateInfo.getIssuer(signCert.getTBSCertificate()));
        v.add(new ASN1Integer(signCert.getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestAlgorithmOid));
        v.add(DERNull.INSTANCE);
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        if (secondDigest != null) {
            signerinfo.add(new DERTaggedObject(false, 0,
                    getAuthenticatedAttributeSet(secondDigest, ocsp, crlBytes, sigtype)));
        }
        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid));
        v.add(DERNull.INSTANCE);
        signerinfo.add(new DERSequence(v));

        // Add the digest
        signerinfo.add(new DEROctetString(digest));

        // When requested, go get and add the timestamp. May throw an exception.
        // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
        // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
        if (tsaClient != null) {
            byte[] tsImprint = tsaClient.getMessageDigest().digest(digest);
            byte[] tsToken = tsaClient.getTimeStampToken(tsImprint);
            if (tsToken != null) {
                ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(tsToken);
                if (unauthAttributes != null) {
                    signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes)));
                }
            }
        }

        // Finally build the body out of all the components above
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new ASN1Integer(version));
        body.add(new DERSet(digestAlgorithms));
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        // Only allow one signerInfo
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        //
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DERSequence(whole));
        dout.close();

        return bOut.toByteArray();
    } catch (Exception e) {
        throw new PdfException(e);
    }
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Added by Aiken Sam, 2006-11-15, modifed by Martin Brunecky 07/12/2007
 * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2).
 * Token is the TSA response without response status, which is usually
 * handled by the (vendor supplied) TSA request/response interface).
 *
 * @param timeStampToken byte[] - time stamp token, DER encoded signedData
 * @return ASN1EncodableVector//from   w  ww.j av a2  s. c o  m
 * @throws IOException
 */
private ASN1EncodableVector buildUnauthenticatedAttributes(byte[] timeStampToken) throws IOException {
    if (timeStampToken == null)
        return null;

    // @todo: move this together with the rest of the defintions
    String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken

    ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(timeStampToken));
    ASN1EncodableVector unauthAttributes = new ASN1EncodableVector();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
    ASN1Sequence seq = (ASN1Sequence) tempstream.readObject();
    v.add(new DERSet(seq));

    unauthAttributes.add(new DERSequence(v));
    return unauthAttributes;
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * This method provides that encoding and the parameters must be
 * exactly the same as in {@link #getEncodedPKCS7(byte[])}.
 *
 * @param secondDigest the content digest
 * @return the byte array representation of the authenticatedAttributes ready to be signed
 *//*w w  w. jav  a2s .  c om*/
private DERSet getAuthenticatedAttributeSet(byte[] secondDigest, byte[] ocsp, Collection<byte[]> crlBytes,
        PdfSigner.CryptoStandard sigtype) {
    try {
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE));
        v.add(new DERSet(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        boolean haveCrl = false;
        if (crlBytes != null) {
            for (byte[] bCrl : crlBytes) {
                if (bCrl != null) {
                    haveCrl = true;
                    break;
                }
            }
        }
        if (ocsp != null || haveCrl) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION));

            ASN1EncodableVector revocationV = new ASN1EncodableVector();

            if (haveCrl) {
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                for (byte[] bCrl : crlBytes) {
                    if (bCrl == null)
                        continue;
                    ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(bCrl));
                    v2.add(t.readObject());
                }
                revocationV.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
            }

            if (ocsp != null) {
                DEROctetString doctet = new DEROctetString(ocsp);
                ASN1EncodableVector vo1 = new ASN1EncodableVector();
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
                v2.add(doctet);
                ASN1Enumerated den = new ASN1Enumerated(0);
                ASN1EncodableVector v3 = new ASN1EncodableVector();
                v3.add(den);
                v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
                vo1.add(new DERSequence(v3));
                revocationV.add(new DERTaggedObject(true, 1, new DERSequence(vo1)));
            }

            v.add(new DERSet(new DERSequence(revocationV)));
            attribute.add(new DERSequence(v));
        }
        if (sigtype == PdfSigner.CryptoStandard.CADES) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2));

            ASN1EncodableVector aaV2 = new ASN1EncodableVector();
            AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithmOid),
                    null);
            aaV2.add(algoId);
            MessageDigest md = SignUtils.getMessageDigest(getHashAlgorithm(), interfaceDigest);
            byte[] dig = md.digest(signCert.getEncoded());
            aaV2.add(new DEROctetString(dig));

            v.add(new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2)))));
            attribute.add(new DERSequence(v));
        }

        if (signaturePolicyIdentifier != null) {
            attribute.add(new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId,
                    new DERSet(signaturePolicyIdentifier)));
        }

        return new DERSet(attribute);
    } catch (Exception e) {
        throw new PdfException(e);
    }
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Helper method that creates the BasicOCSPResp object.
 *
 * @param seq//from w w w. j a  v  a  2  s .c o m
 * @throws IOException
 */
private void findOcsp(ASN1Sequence seq) throws IOException {
    basicResp = (BasicOCSPResp) null;
    boolean ret = false;
    while (true) {
        if (seq.getObjectAt(0) instanceof ASN1ObjectIdentifier && ((ASN1ObjectIdentifier) seq.getObjectAt(0))
                .getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
            break;
        }
        ret = true;
        for (int k = 0; k < seq.size(); ++k) {
            if (seq.getObjectAt(k) instanceof ASN1Sequence) {
                seq = (ASN1Sequence) seq.getObjectAt(0);
                ret = false;
                break;
            }
            if (seq.getObjectAt(k) instanceof ASN1TaggedObject) {
                ASN1TaggedObject tag = (ASN1TaggedObject) seq.getObjectAt(k);
                if (tag.getObject() instanceof ASN1Sequence) {
                    seq = (ASN1Sequence) tag.getObject();
                    ret = false;
                    break;
                } else
                    return;
            }
        }
        if (ret)
            return;
    }
    ASN1OctetString os = (ASN1OctetString) seq.getObjectAt(1);
    ASN1InputStream inp = new ASN1InputStream(os.getOctets());
    BasicOCSPResponse resp = BasicOCSPResponse.getInstance(inp.readObject());
    basicResp = new BasicOCSPResp(resp);
}

From source file:com.itextpdf.text.pdf.JPKIPdfPKCS7.java

License:Open Source License

/**
 * Get the "issuer" from the TBSCertificate bytes that are passed in
 * @param enc a TBSCertificate in a byte array
 * @return a DERObject/*from  www  . j  ava 2 s .  co m*/
 */
private static DERObject getIssuer(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence) in.readObject();
        return (DERObject) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3 : 2);
    } catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}