Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/pkcs/PKCS7.java
38830 views
/*1* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.pkcs;2627import java.io.*;28import java.math.BigInteger;29import java.net.URI;30import java.util.*;31import java.security.cert.X509Certificate;32import java.security.cert.CertificateException;33import java.security.cert.X509CRL;34import java.security.cert.CRLException;35import java.security.cert.CertificateFactory;36import java.security.*;3738import sun.security.timestamp.*;39import sun.security.util.*;40import sun.security.x509.AlgorithmId;41import sun.security.x509.X509CertImpl;42import sun.security.x509.X509CertInfo;43import sun.security.x509.X509CRLImpl;44import sun.security.x509.X500Name;4546/**47* PKCS7 as defined in RSA Laboratories PKCS7 Technical Note. Profile48* Supports only {@code SignedData} ContentInfo49* type, where to the type of data signed is plain Data.50* For signedData, {@code crls}, {@code attributes} and51* PKCS#6 Extended Certificates are not supported.52*53* @author Benjamin Renaud54*/55public class PKCS7 {5657private ObjectIdentifier contentType;5859// the ASN.1 members for a signedData (and other) contentTypes60private BigInteger version = null;61private AlgorithmId[] digestAlgorithmIds = null;62private ContentInfo contentInfo = null;63private X509Certificate[] certificates = null;64private X509CRL[] crls = null;65private SignerInfo[] signerInfos = null;6667private boolean oldStyle = false; // Is this JDK1.1.x-style?6869private Principal[] certIssuerNames;7071/*72* Random number generator for creating nonce values73* (Lazy initialization)74*/75private static class SecureRandomHolder {76static final SecureRandom RANDOM;77static {78SecureRandom tmp = null;79try {80tmp = SecureRandom.getInstance("SHA1PRNG");81} catch (NoSuchAlgorithmException e) {82// should not happen83}84RANDOM = tmp;85}86}8788/*89* Object identifier for the timestamping key purpose.90*/91private static final String KP_TIMESTAMPING_OID = "1.3.6.1.5.5.7.3.8";9293/*94* Object identifier for extendedKeyUsage extension95*/96private static final String EXTENDED_KEY_USAGE_OID = "2.5.29.37";9798/**99* Unmarshals a PKCS7 block from its encoded form, parsing the100* encoded bytes from the InputStream.101*102* @param in an input stream holding at least one PKCS7 block.103* @exception ParsingException on parsing errors.104* @exception IOException on other errors.105*/106public PKCS7(InputStream in) throws ParsingException, IOException {107DataInputStream dis = new DataInputStream(in);108byte[] data = new byte[dis.available()];109dis.readFully(data);110111parse(new DerInputStream(data));112}113114/**115* Unmarshals a PKCS7 block from its encoded form, parsing the116* encoded bytes from the DerInputStream.117*118* @param derin a DerInputStream holding at least one PKCS7 block.119* @exception ParsingException on parsing errors.120*/121public PKCS7(DerInputStream derin) throws ParsingException {122parse(derin);123}124125/**126* Unmarshals a PKCS7 block from its encoded form, parsing the127* encoded bytes.128*129* @param bytes the encoded bytes.130* @exception ParsingException on parsing errors.131*/132public PKCS7(byte[] bytes) throws ParsingException {133try {134DerInputStream derin = new DerInputStream(bytes);135parse(derin);136} catch (IOException ioe1) {137ParsingException pe = new ParsingException(138"Unable to parse the encoded bytes");139pe.initCause(ioe1);140throw pe;141}142}143144/*145* Parses a PKCS#7 block.146*/147private void parse(DerInputStream derin)148throws ParsingException149{150try {151derin.mark(derin.available());152// try new (i.e., JDK1.2) style153parse(derin, false);154} catch (IOException ioe) {155try {156derin.reset();157// try old (i.e., JDK1.1.x) style158parse(derin, true);159oldStyle = true;160} catch (IOException ioe1) {161ParsingException pe = new ParsingException(162ioe1.getMessage());163pe.initCause(ioe);164pe.addSuppressed(ioe1);165throw pe;166}167}168}169170/**171* Parses a PKCS#7 block.172*173* @param derin the ASN.1 encoding of the PKCS#7 block.174* @param oldStyle flag indicating whether or not the given PKCS#7 block175* is encoded according to JDK1.1.x.176*/177private void parse(DerInputStream derin, boolean oldStyle)178throws IOException179{180contentInfo = new ContentInfo(derin, oldStyle);181contentType = contentInfo.contentType;182DerValue content = contentInfo.getContent();183184if (contentType.equals((Object)ContentInfo.SIGNED_DATA_OID)) {185parseSignedData(content);186} else if (contentType.equals((Object)ContentInfo.OLD_SIGNED_DATA_OID)) {187// This is for backwards compatibility with JDK 1.1.x188parseOldSignedData(content);189} else if (contentType.equals((Object)190ContentInfo.NETSCAPE_CERT_SEQUENCE_OID)){191parseNetscapeCertChain(content);192} else {193throw new ParsingException("content type " + contentType +194" not supported.");195}196}197198/**199* Construct an initialized PKCS7 block.200*201* @param digestAlgorithmIds the message digest algorithm identifiers.202* @param contentInfo the content information.203* @param certificates an array of X.509 certificates.204* @param crls an array of CRLs205* @param signerInfos an array of signer information.206*/207public PKCS7(AlgorithmId[] digestAlgorithmIds,208ContentInfo contentInfo,209X509Certificate[] certificates,210X509CRL[] crls,211SignerInfo[] signerInfos) {212213version = BigInteger.ONE;214this.digestAlgorithmIds = digestAlgorithmIds;215this.contentInfo = contentInfo;216this.certificates = certificates;217this.crls = crls;218this.signerInfos = signerInfos;219}220221public PKCS7(AlgorithmId[] digestAlgorithmIds,222ContentInfo contentInfo,223X509Certificate[] certificates,224SignerInfo[] signerInfos) {225this(digestAlgorithmIds, contentInfo, certificates, null, signerInfos);226}227228private void parseNetscapeCertChain(DerValue val)229throws ParsingException, IOException {230DerInputStream dis = new DerInputStream(val.toByteArray());231DerValue[] contents = dis.getSequence(2);232certificates = new X509Certificate[contents.length];233234CertificateFactory certfac = null;235try {236certfac = CertificateFactory.getInstance("X.509");237} catch (CertificateException ce) {238// do nothing239}240241for (int i=0; i < contents.length; i++) {242ByteArrayInputStream bais = null;243try {244if (certfac == null)245certificates[i] = new X509CertImpl(contents[i]);246else {247byte[] encoded = contents[i].toByteArray();248bais = new ByteArrayInputStream(encoded);249certificates[i] =250(X509Certificate)certfac.generateCertificate(bais);251bais.close();252bais = null;253}254} catch (CertificateException ce) {255ParsingException pe = new ParsingException(ce.getMessage());256pe.initCause(ce);257throw pe;258} catch (IOException ioe) {259ParsingException pe = new ParsingException(ioe.getMessage());260pe.initCause(ioe);261throw pe;262} finally {263if (bais != null)264bais.close();265}266}267}268269private void parseSignedData(DerValue val)270throws ParsingException, IOException {271272DerInputStream dis = val.toDerInputStream();273274// Version275version = dis.getBigInteger();276277// digestAlgorithmIds278DerValue[] digestAlgorithmIdVals = dis.getSet(1);279int len = digestAlgorithmIdVals.length;280digestAlgorithmIds = new AlgorithmId[len];281try {282for (int i = 0; i < len; i++) {283DerValue oid = digestAlgorithmIdVals[i];284digestAlgorithmIds[i] = AlgorithmId.parse(oid);285}286287} catch (IOException e) {288ParsingException pe =289new ParsingException("Error parsing digest AlgorithmId IDs: " +290e.getMessage());291pe.initCause(e);292throw pe;293}294// contentInfo295contentInfo = new ContentInfo(dis);296297CertificateFactory certfac = null;298try {299certfac = CertificateFactory.getInstance("X.509");300} catch (CertificateException ce) {301// do nothing302}303304/*305* check if certificates (implicit tag) are provided306* (certificates are OPTIONAL)307*/308if ((byte)(dis.peekByte()) == (byte)0xA0) {309DerValue[] certVals = dis.getSet(2, true);310311len = certVals.length;312certificates = new X509Certificate[len];313int count = 0;314315for (int i = 0; i < len; i++) {316ByteArrayInputStream bais = null;317try {318byte tag = certVals[i].getTag();319// We only parse the normal certificate. Other types of320// CertificateChoices ignored.321if (tag == DerValue.tag_Sequence) {322if (certfac == null) {323certificates[count] = new X509CertImpl(certVals[i]);324} else {325byte[] encoded = certVals[i].toByteArray();326bais = new ByteArrayInputStream(encoded);327certificates[count] =328(X509Certificate)certfac.generateCertificate(bais);329bais.close();330bais = null;331}332count++;333}334} catch (CertificateException ce) {335ParsingException pe = new ParsingException(ce.getMessage());336pe.initCause(ce);337throw pe;338} catch (IOException ioe) {339ParsingException pe = new ParsingException(ioe.getMessage());340pe.initCause(ioe);341throw pe;342} finally {343if (bais != null)344bais.close();345}346}347if (count != len) {348certificates = Arrays.copyOf(certificates, count);349}350}351352// check if crls (implicit tag) are provided (crls are OPTIONAL)353if ((byte)(dis.peekByte()) == (byte)0xA1) {354DerValue[] crlVals = dis.getSet(1, true);355356len = crlVals.length;357crls = new X509CRL[len];358359for (int i = 0; i < len; i++) {360ByteArrayInputStream bais = null;361try {362if (certfac == null)363crls[i] = new X509CRLImpl(crlVals[i]);364else {365byte[] encoded = crlVals[i].toByteArray();366bais = new ByteArrayInputStream(encoded);367crls[i] = (X509CRL) certfac.generateCRL(bais);368bais.close();369bais = null;370}371} catch (CRLException e) {372ParsingException pe =373new ParsingException(e.getMessage());374pe.initCause(e);375throw pe;376} finally {377if (bais != null)378bais.close();379}380}381}382383// signerInfos384DerValue[] signerInfoVals = dis.getSet(1);385386len = signerInfoVals.length;387signerInfos = new SignerInfo[len];388389for (int i = 0; i < len; i++) {390DerInputStream in = signerInfoVals[i].toDerInputStream();391signerInfos[i] = new SignerInfo(in);392}393}394395/*396* Parses an old-style SignedData encoding (for backwards397* compatibility with JDK1.1.x).398*/399private void parseOldSignedData(DerValue val)400throws ParsingException, IOException401{402DerInputStream dis = val.toDerInputStream();403404// Version405version = dis.getBigInteger();406407// digestAlgorithmIds408DerValue[] digestAlgorithmIdVals = dis.getSet(1);409int len = digestAlgorithmIdVals.length;410411digestAlgorithmIds = new AlgorithmId[len];412try {413for (int i = 0; i < len; i++) {414DerValue oid = digestAlgorithmIdVals[i];415digestAlgorithmIds[i] = AlgorithmId.parse(oid);416}417} catch (IOException e) {418throw new ParsingException("Error parsing digest AlgorithmId IDs");419}420421// contentInfo422contentInfo = new ContentInfo(dis, true);423424// certificates425CertificateFactory certfac = null;426try {427certfac = CertificateFactory.getInstance("X.509");428} catch (CertificateException ce) {429// do nothing430}431DerValue[] certVals = dis.getSet(2);432len = certVals.length;433certificates = new X509Certificate[len];434435for (int i = 0; i < len; i++) {436ByteArrayInputStream bais = null;437try {438if (certfac == null)439certificates[i] = new X509CertImpl(certVals[i]);440else {441byte[] encoded = certVals[i].toByteArray();442bais = new ByteArrayInputStream(encoded);443certificates[i] =444(X509Certificate)certfac.generateCertificate(bais);445bais.close();446bais = null;447}448} catch (CertificateException ce) {449ParsingException pe = new ParsingException(ce.getMessage());450pe.initCause(ce);451throw pe;452} catch (IOException ioe) {453ParsingException pe = new ParsingException(ioe.getMessage());454pe.initCause(ioe);455throw pe;456} finally {457if (bais != null)458bais.close();459}460}461462// crls are ignored.463dis.getSet(0);464465// signerInfos466DerValue[] signerInfoVals = dis.getSet(1);467len = signerInfoVals.length;468signerInfos = new SignerInfo[len];469for (int i = 0; i < len; i++) {470DerInputStream in = signerInfoVals[i].toDerInputStream();471signerInfos[i] = new SignerInfo(in, true);472}473}474475/**476* Encodes the signed data to an output stream.477*478* @param out the output stream to write the encoded data to.479* @exception IOException on encoding errors.480*/481public void encodeSignedData(OutputStream out) throws IOException {482DerOutputStream derout = new DerOutputStream();483encodeSignedData(derout);484out.write(derout.toByteArray());485}486487/**488* Encodes the signed data to a DerOutputStream.489*490* @param out the DerOutputStream to write the encoded data to.491* @exception IOException on encoding errors.492*/493public void encodeSignedData(DerOutputStream out)494throws IOException495{496DerOutputStream signedData = new DerOutputStream();497498// version499signedData.putInteger(version);500501// digestAlgorithmIds502signedData.putOrderedSetOf(DerValue.tag_Set, digestAlgorithmIds);503504// contentInfo505contentInfo.encode(signedData);506507// certificates (optional)508if (certificates != null && certificates.length != 0) {509// cast to X509CertImpl[] since X509CertImpl implements DerEncoder510X509CertImpl implCerts[] = new X509CertImpl[certificates.length];511for (int i = 0; i < certificates.length; i++) {512if (certificates[i] instanceof X509CertImpl)513implCerts[i] = (X509CertImpl) certificates[i];514else {515try {516byte[] encoded = certificates[i].getEncoded();517implCerts[i] = new X509CertImpl(encoded);518} catch (CertificateException ce) {519throw new IOException(ce);520}521}522}523524// Add the certificate set (tagged with [0] IMPLICIT)525// to the signed data526signedData.putOrderedSetOf((byte)0xA0, implCerts);527}528529// CRLs (optional)530if (crls != null && crls.length != 0) {531// cast to X509CRLImpl[] since X509CRLImpl implements DerEncoder532Set<X509CRLImpl> implCRLs = new HashSet<X509CRLImpl>(crls.length);533for (X509CRL crl: crls) {534if (crl instanceof X509CRLImpl)535implCRLs.add((X509CRLImpl) crl);536else {537try {538byte[] encoded = crl.getEncoded();539implCRLs.add(new X509CRLImpl(encoded));540} catch (CRLException ce) {541throw new IOException(ce);542}543}544}545546// Add the CRL set (tagged with [1] IMPLICIT)547// to the signed data548signedData.putOrderedSetOf((byte)0xA1,549implCRLs.toArray(new X509CRLImpl[implCRLs.size()]));550}551552// signerInfos553signedData.putOrderedSetOf(DerValue.tag_Set, signerInfos);554555// making it a signed data block556DerValue signedDataSeq = new DerValue(DerValue.tag_Sequence,557signedData.toByteArray());558559// making it a content info sequence560ContentInfo block = new ContentInfo(ContentInfo.SIGNED_DATA_OID,561signedDataSeq);562563// writing out the contentInfo sequence564block.encode(out);565}566567/**568* This verifies a given SignerInfo.569*570* @param info the signer information.571* @param bytes the DER encoded content information.572*573* @exception NoSuchAlgorithmException on unrecognized algorithms.574* @exception SignatureException on signature handling errors.575*/576public SignerInfo verify(SignerInfo info, byte[] bytes)577throws NoSuchAlgorithmException, SignatureException {578return info.verify(this, bytes);579}580581/**582* Returns all signerInfos which self-verify.583*584* @param bytes the DER encoded content information.585*586* @exception NoSuchAlgorithmException on unrecognized algorithms.587* @exception SignatureException on signature handling errors.588*/589public SignerInfo[] verify(byte[] bytes)590throws NoSuchAlgorithmException, SignatureException {591592Vector<SignerInfo> intResult = new Vector<SignerInfo>();593for (int i = 0; i < signerInfos.length; i++) {594595SignerInfo signerInfo = verify(signerInfos[i], bytes);596if (signerInfo != null) {597intResult.addElement(signerInfo);598}599}600if (!intResult.isEmpty()) {601602SignerInfo[] result = new SignerInfo[intResult.size()];603intResult.copyInto(result);604return result;605}606return null;607}608609/**610* Returns all signerInfos which self-verify.611*612* @exception NoSuchAlgorithmException on unrecognized algorithms.613* @exception SignatureException on signature handling errors.614*/615public SignerInfo[] verify()616throws NoSuchAlgorithmException, SignatureException {617return verify(null);618}619620/**621* Returns the version number of this PKCS7 block.622* @return the version or null if version is not specified623* for the content type.624*/625public BigInteger getVersion() {626return version;627}628629/**630* Returns the message digest algorithms specified in this PKCS7 block.631* @return the array of Digest Algorithms or null if none are specified632* for the content type.633*/634public AlgorithmId[] getDigestAlgorithmIds() {635return digestAlgorithmIds;636}637638/**639* Returns the content information specified in this PKCS7 block.640*/641public ContentInfo getContentInfo() {642return contentInfo;643}644645/**646* Returns the X.509 certificates listed in this PKCS7 block.647* @return a clone of the array of X.509 certificates or null if648* none are specified for the content type.649*/650public X509Certificate[] getCertificates() {651if (certificates != null)652return certificates.clone();653else654return null;655}656657/**658* Returns the X.509 crls listed in this PKCS7 block.659* @return a clone of the array of X.509 crls or null if none660* are specified for the content type.661*/662public X509CRL[] getCRLs() {663if (crls != null)664return crls.clone();665else666return null;667}668669/**670* Returns the signer's information specified in this PKCS7 block.671* @return the array of Signer Infos or null if none are specified672* for the content type.673*/674public SignerInfo[] getSignerInfos() {675return signerInfos;676}677678/**679* Returns the X.509 certificate listed in this PKCS7 block680* which has a matching serial number and Issuer name, or681* null if one is not found.682*683* @param serial the serial number of the certificate to retrieve.684* @param issuerName the Distinguished Name of the Issuer.685*/686public X509Certificate getCertificate(BigInteger serial, X500Name issuerName) {687if (certificates != null) {688if (certIssuerNames == null)689populateCertIssuerNames();690for (int i = 0; i < certificates.length; i++) {691X509Certificate cert = certificates[i];692BigInteger thisSerial = cert.getSerialNumber();693if (serial.equals(thisSerial)694&& issuerName.equals(certIssuerNames[i]))695{696return cert;697}698}699}700return null;701}702703/**704* Populate array of Issuer DNs from certificates and convert705* each Principal to type X500Name if necessary.706*/707private void populateCertIssuerNames() {708if (certificates == null)709return;710711certIssuerNames = new Principal[certificates.length];712for (int i = 0; i < certificates.length; i++) {713X509Certificate cert = certificates[i];714Principal certIssuerName = cert.getIssuerDN();715if (!(certIssuerName instanceof X500Name)) {716// must extract the original encoded form of DN for717// subsequent name comparison checks (converting to a718// String and back to an encoded DN could cause the719// types of String attribute values to be changed)720try {721X509CertInfo tbsCert =722new X509CertInfo(cert.getTBSCertificate());723certIssuerName = (Principal)724tbsCert.get(X509CertInfo.ISSUER + "." +725X509CertInfo.DN_NAME);726} catch (Exception e) {727// error generating X500Name object from the cert's728// issuer DN, leave name as is.729}730}731certIssuerNames[i] = certIssuerName;732}733}734735/**736* Returns the PKCS7 block in a printable string form.737*/738public String toString() {739String out = "";740741out += contentInfo + "\n";742if (version != null)743out += "PKCS7 :: version: " + Debug.toHexString(version) + "\n";744if (digestAlgorithmIds != null) {745out += "PKCS7 :: digest AlgorithmIds: \n";746for (int i = 0; i < digestAlgorithmIds.length; i++)747out += "\t" + digestAlgorithmIds[i] + "\n";748}749if (certificates != null) {750out += "PKCS7 :: certificates: \n";751for (int i = 0; i < certificates.length; i++)752out += "\t" + i + ". " + certificates[i] + "\n";753}754if (crls != null) {755out += "PKCS7 :: crls: \n";756for (int i = 0; i < crls.length; i++)757out += "\t" + i + ". " + crls[i] + "\n";758}759if (signerInfos != null) {760out += "PKCS7 :: signer infos: \n";761for (int i = 0; i < signerInfos.length; i++)762out += ("\t" + i + ". " + signerInfos[i] + "\n");763}764return out;765}766767/**768* Returns true if this is a JDK1.1.x-style PKCS#7 block, and false769* otherwise.770*/771public boolean isOldStyle() {772return this.oldStyle;773}774775/**776* Assembles a PKCS #7 signed data message that optionally includes a777* signature timestamp.778*779* @param signature the signature bytes780* @param signerChain the signer's X.509 certificate chain781* @param content the content that is signed; specify null to not include782* it in the PKCS7 data783* @param signatureAlgorithm the name of the signature algorithm784* @param tsaURI the URI of the Timestamping Authority; or null if no785* timestamp is requested786* @param tSAPolicyID the TSAPolicyID of the Timestamping Authority as a787* numerical object identifier; or null if we leave the TSA server788* to choose one. This argument is only used when tsaURI is provided789* @return the bytes of the encoded PKCS #7 signed data message790* @throws NoSuchAlgorithmException The exception is thrown if the signature791* algorithm is unrecognised.792* @throws CertificateException The exception is thrown if an error occurs793* while processing the signer's certificate or the TSA's794* certificate.795* @throws IOException The exception is thrown if an error occurs while796* generating the signature timestamp or while generating the signed797* data message.798*/799public static byte[] generateSignedData(byte[] signature,800X509Certificate[] signerChain,801byte[] content,802String signatureAlgorithm,803URI tsaURI,804String tSAPolicyID,805String tSADigestAlg)806throws CertificateException, IOException, NoSuchAlgorithmException807{808809// Generate the timestamp token810PKCS9Attributes unauthAttrs = null;811if (tsaURI != null) {812// Timestamp the signature813HttpTimestamper tsa = new HttpTimestamper(tsaURI);814byte[] tsToken = generateTimestampToken(815tsa, tSAPolicyID, tSADigestAlg, signature);816817// Insert the timestamp token into the PKCS #7 signer info element818// (as an unsigned attribute)819unauthAttrs =820new PKCS9Attributes(new PKCS9Attribute[]{821new PKCS9Attribute(822PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_STR,823tsToken)});824}825826// Create the SignerInfo827X500Name issuerName =828X500Name.asX500Name(signerChain[0].getIssuerX500Principal());829BigInteger serialNumber = signerChain[0].getSerialNumber();830String encAlg = AlgorithmId.getEncAlgFromSigAlg(signatureAlgorithm);831String digAlg = AlgorithmId.getDigAlgFromSigAlg(signatureAlgorithm);832SignerInfo signerInfo = new SignerInfo(issuerName, serialNumber,833AlgorithmId.get(digAlg), null,834AlgorithmId.get(encAlg),835signature, unauthAttrs);836837// Create the PKCS #7 signed data message838SignerInfo[] signerInfos = {signerInfo};839AlgorithmId[] algorithms = {signerInfo.getDigestAlgorithmId()};840// Include or exclude content841ContentInfo contentInfo = (content == null)842? new ContentInfo(ContentInfo.DATA_OID, null)843: new ContentInfo(content);844PKCS7 pkcs7 = new PKCS7(algorithms, contentInfo,845signerChain, signerInfos);846ByteArrayOutputStream p7out = new ByteArrayOutputStream();847pkcs7.encodeSignedData(p7out);848849return p7out.toByteArray();850}851852/**853* Requests, processes and validates a timestamp token from a TSA using854* common defaults. Uses the following defaults in the timestamp request:855* SHA-1 for the hash algorithm, a 64-bit nonce, and request certificate856* set to true.857*858* @param tsa the timestamping authority to use859* @param tSAPolicyID the TSAPolicyID of the Timestamping Authority as a860* numerical object identifier; or null if we leave the TSA server861* to choose one862* @param toBeTimestamped the token that is to be timestamped863* @return the encoded timestamp token864* @throws IOException The exception is thrown if an error occurs while865* communicating with the TSA, or a non-null866* TSAPolicyID is specified in the request but it867* does not match the one in the reply868* @throws CertificateException The exception is thrown if the TSA's869* certificate is not permitted for timestamping.870*/871private static byte[] generateTimestampToken(Timestamper tsa,872String tSAPolicyID,873String tSADigestAlg,874byte[] toBeTimestamped)875throws IOException, CertificateException876{877// Generate a timestamp878MessageDigest messageDigest = null;879TSRequest tsQuery = null;880try {881messageDigest = MessageDigest.getInstance(tSADigestAlg);882tsQuery = new TSRequest(tSAPolicyID, toBeTimestamped, messageDigest);883} catch (NoSuchAlgorithmException e) {884throw new IllegalArgumentException(e);885}886887// Generate a nonce888BigInteger nonce = null;889if (SecureRandomHolder.RANDOM != null) {890nonce = new BigInteger(64, SecureRandomHolder.RANDOM);891tsQuery.setNonce(nonce);892}893tsQuery.requestCertificate(true);894895TSResponse tsReply = tsa.generateTimestamp(tsQuery);896int status = tsReply.getStatusCode();897// Handle TSP error898if (status != 0 && status != 1) {899throw new IOException("Error generating timestamp: " +900tsReply.getStatusCodeAsText() + " " +901tsReply.getFailureCodeAsText());902}903904if (tSAPolicyID != null &&905!tSAPolicyID.equals(tsReply.getTimestampToken().getPolicyID())) {906throw new IOException("TSAPolicyID changed in "907+ "timestamp token");908}909PKCS7 tsToken = tsReply.getToken();910911TimestampToken tst = tsReply.getTimestampToken();912try {913if (!tst.getHashAlgorithm().equals(AlgorithmId.get(tSADigestAlg))) {914throw new IOException("Digest algorithm not " + tSADigestAlg + " in "915+ "timestamp token");916}917} catch (NoSuchAlgorithmException nase) {918throw new IllegalArgumentException(); // should have been caught before919}920if (!MessageDigest.isEqual(tst.getHashedMessage(),921tsQuery.getHashedMessage())) {922throw new IOException("Digest octets changed in timestamp token");923}924925BigInteger replyNonce = tst.getNonce();926if (replyNonce == null && nonce != null) {927throw new IOException("Nonce missing in timestamp token");928}929if (replyNonce != null && !replyNonce.equals(nonce)) {930throw new IOException("Nonce changed in timestamp token");931}932933// Examine the TSA's certificate (if present)934for (SignerInfo si: tsToken.getSignerInfos()) {935X509Certificate cert = si.getCertificate(tsToken);936if (cert == null) {937// Error, we've already set tsRequestCertificate = true938throw new CertificateException(939"Certificate not included in timestamp token");940} else {941if (!cert.getCriticalExtensionOIDs().contains(942EXTENDED_KEY_USAGE_OID)) {943throw new CertificateException(944"Certificate is not valid for timestamping");945}946List<String> keyPurposes = cert.getExtendedKeyUsage();947if (keyPurposes == null ||948!keyPurposes.contains(KP_TIMESTAMPING_OID)) {949throw new CertificateException(950"Certificate is not valid for timestamping");951}952}953}954return tsReply.getEncodedToken();955}956}957958959