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.text.pdf.PdfPublicKeySecurityHandler.java

License:Open Source License

private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
            algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    ASN1Primitive derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);/*  ww  w . j  a  v  a 2 s. co  m*/
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            algorithmidentifier, deroctetstring);
    ASN1Set set = null;
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();
}

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

License:Open Source License

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(
            new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure
            .getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(),
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());
    try {/*from   w w  w  .  j  a  va2 s .  c  o  m*/
        cipher.init(1, x509certificate);
    } catch (InvalidKeyException e) {
        cipher.init(1, x509certificate.getPublicKey());
    }
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}

From source file:com.itextpdf.text.pdf.security.CertificateInfo.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 ASN1Primitive//from  w  w  w. j a va 2  s  .co m
 */
public static ASN1Primitive getIssuer(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence) in.readObject();
        return (ASN1Primitive) seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 3 : 2);
    } catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.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  www.  j a v  a  2  s  .  co  m*/
 */
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 ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.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. j  av  a 2s  .  c o  m
 */
private static ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
    byte[] bytes = certificate.getExtensionValue(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.text.pdf.security.LtvVerification.java

License:Open Source License

private PdfName getSignatureHashKey(String signatureName) throws NoSuchAlgorithmException, IOException {
    PdfDictionary dic = acroFields.getSignatureDictionary(signatureName);
    PdfString contents = dic.getAsString(PdfName.CONTENTS);
    byte[] bc = contents.getOriginalBytes();
    byte[] bt = null;
    if (PdfName.ETSI_RFC3161.equals(PdfReader.getPdfObject(dic.get(PdfName.SUBFILTER)))) {
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(bc));
        ASN1Primitive pkcs = din.readObject();
        bc = pkcs.getEncoded();//from  w  w  w  .j a v a2s.c o  m
    }
    bt = hashBytesSha1(bc);
    return new PdfName(Utilities.convertToHex(bt));
}

From source file:com.itextpdf.text.pdf.security.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   w  ww. ja  v a2s . 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;
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(certsKey));
        certs = cr.engineReadAll();
        signCerts = certs;
        signCert = (X509Certificate) certs.iterator().next();
        crls = new ArrayList<CRL>();

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

        if (provider == null) {
            sig = Signature.getInstance("SHA1withRSA");
        } else {
            sig = Signature.getInstance("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 ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * Use this constructor if you want to verify a signature.
 * @param contentsKey the /Contents key/*from  w  ww . j  a va 2  s .co  m*/
 * @param filterSubtype the filtersubtype
 * @param provider the provider or <code>null</code> for the default provider
 */
@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(
                    MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object"));
        }
        if (!(pkcs instanceof ASN1Sequence)) {
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
        }
        ASN1Sequence signedData = (ASN1Sequence) pkcs;
        ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
        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<String>();
        Enumeration<ASN1Sequence> e = ((ASN1Set) content.getObjectAt(1)).getObjects();
        while (e.hasMoreElements()) {
            ASN1Sequence s = 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:
        */
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(contentsKey));
        certs = cr.engineReadAll();
        /*    
                    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(MessageLocalization.getComposedMessage(
                    "this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
        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 = new X509Principal(
                issuerAndSerialNumber.getObjectAt(0).toASN1Primitive().getEncoded());
        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 IllegalArgumentException(
                    MessageLocalization.getComposedMessage("can.t.find.signing.certificate.with.serial.1",
                            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 = new BouncyCastleDigest().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 = new BouncyCastleDigest()
                            .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(MessageLocalization
                        .getComposedMessage("authenticated.attribute.is.missing.the.digest"));
            ++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));
                ContentInfo contentInfo = new ContentInfo(tokenSequence);
                this.timeStampToken = new TimeStampToken(contentInfo);
            }
        }
        if (isTsp) {
            ContentInfo contentInfoTsp = new ContentInfo(signedData);
            this.timeStampToken = new TimeStampToken(contentInfoTsp);
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            String algOID = info.getMessageImprintAlgOID().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 ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.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./*  w w w  .  j  a va2 s  . co  m*/
 * @param secondDigest the digest in the authenticatedAttributes
 * @param signingTime the signing time in the authenticatedAttributes
 * @param tsaClient TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object
 * @since   2.1.6
 */
public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, TSAClient tsaClient, byte[] ocsp,
        Collection<byte[]> crlBytes, 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(new DERNull());
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        if (secondDigest != null && signingTime != null) {
            signerinfo.add(new DERTaggedObject(false, 0,
                    getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype)));
        }
        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid));
        v.add(new DERNull());
        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 ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * This method provides that encoding and the parameters must be
 * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}.
 * /* w ww. j  a v a 2s .c o m*/
 * @param secondDigest the content digest
 * @param signingTime the signing time
 * @return the byte array representation of the authenticatedAttributes ready to be signed
 */
private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp,
        Collection<byte[]> crlBytes, 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_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        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 == 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 = interfaceDigest.getMessageDigest(getHashAlgorithm());
            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));
        }

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