コード例 #1
0
        /**
         * Get timestamp token - Bouncy Castle request encoding / decoding layer
         */
        protected internal byte[] GetTimeStampToken(byte[] imprint)
        {
            byte[] respBytes = null;
            // Setup the time stamp request
            TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();

            tsqGenerator.SetCertReq(true);
            // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
            BigInteger       nonce   = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount);
            TimeStampRequest request = tsqGenerator.Generate(X509ObjectIdentifiers.IdSha1.Id, imprint, nonce);

            byte[] requestBytes = request.GetEncoded();

            // Call the communications layer
            respBytes = GetTSAResponse(requestBytes);

            // Handle the TSA response
            TimeStampResponse response = new TimeStampResponse(respBytes);

            // validate communication level attributes (RFC 3161 PKIStatus)
            response.Validate(request);
            PkiFailureInfo failure = response.GetFailInfo();
            int            value   = (failure == null) ? 0 : failure.IntValue;

            if (value != 0)
            {
                // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string
                throw new Exception(MessageLocalization.GetComposedMessage("invalid.tsa.1.response.code.2", tsaURL, value));
            }
            // @todo: validate the time stap certificate chain (if we want
            //        assure we do not sign using an invalid timestamp).

            // extract just the time stamp token (removes communication status info)
            TimeStampToken tsToken = response.TimeStampToken;

            if (tsToken == null)
            {
                throw new Exception(MessageLocalization.GetComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.GetStatusString()));
            }
            TimeStampTokenInfo info = tsToken.TimeStampInfo; // to view details

            byte[] encoded = tsToken.GetEncoded();

            // Update our token size estimate for the next call (padded to be safe)
            this.tokSzEstimate = encoded.Length + 32;
            return(encoded);
        }
コード例 #2
0
    public TimeStampToken(CmsSignedData signedData)
    {
        tsToken = signedData;
        if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo))
        {
            throw new TspValidationException("ContentInfo object not for a time stamp.");
        }
        ICollection signers = tsToken.GetSignerInfos().GetSigners();

        if (signers.Count != 1)
        {
            throw new ArgumentException("Time-stamp token signed by " + signers.Count + " signers, but it must contain just the TSA signature.");
        }
        IEnumerator enumerator = signers.GetEnumerator();

        enumerator.MoveNext();
        tsaSignerInfo = (SignerInformation)enumerator.Current;
        try
        {
            CmsProcessable signedContent = tsToken.SignedContent;
            MemoryStream   memoryStream  = new MemoryStream();
            signedContent.Write(memoryStream);
            tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(memoryStream.ToArray())));
            Org.BouncyCastle.Asn1.Cms.Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
            if (attribute != null)
            {
                SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]);
                certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0]));
            }
            else
            {
                attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
                if (attribute == null)
                {
                    throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
                }
                SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]);
                certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0]));
            }
        }
        catch (CmsException ex)
        {
            throw new TspException(ex.Message, ex.InnerException);
        }
    }
コード例 #3
0
        private void testAccuracyZeroCerts(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2");

            tsTokenGen.SetCertificates(certs);

            tsTokenGen.SetAccuracySeconds(1);
            tsTokenGen.SetAccuracyMillis(2);
            tsTokenGen.SetAccuracyMicros(3);

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsResp.Validate(request);

            TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

            GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy;

            Assert.IsTrue(1 == accuracy.Seconds);
            Assert.IsTrue(2 == accuracy.Millis);
            Assert.IsTrue(3 == accuracy.Micros);

            Assert.IsTrue(new BigInteger("23").Equals(tstInfo.SerialNumber));

            Assert.IsTrue("1.2" == tstInfo.Policy);

            IX509Store store = tsToken.GetCertificates();

            ICollection certificates = store.GetMatches(null);

            Assert.IsTrue(0 == certificates.Count);
        }
コード例 #4
0
    public void Validate(TimeStampRequest request)
    {
        TimeStampToken timeStampToken = TimeStampToken;

        if (timeStampToken != null)
        {
            TimeStampTokenInfo timeStampInfo = timeStampToken.TimeStampInfo;
            if (request.Nonce != null && !request.Nonce.Equals(timeStampInfo.Nonce))
            {
                throw new TspValidationException("response contains wrong nonce value.");
            }
            if (Status != 0 && Status != 1)
            {
                throw new TspValidationException("time stamp token found in failed request.");
            }
            if (!Arrays.ConstantTimeAreEqual(request.GetMessageImprintDigest(), timeStampInfo.GetMessageImprintDigest()))
            {
                throw new TspValidationException("response for different message imprint digest.");
            }
            if (!timeStampInfo.MessageImprintAlgOid.Equals(request.MessageImprintAlgOid))
            {
                throw new TspValidationException("response for different message imprint algorithm.");
            }
            Org.BouncyCastle.Asn1.Cms.Attribute attribute  = timeStampToken.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
            Org.BouncyCastle.Asn1.Cms.Attribute attribute2 = timeStampToken.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
            if (attribute == null && attribute2 == null)
            {
                throw new TspValidationException("no signing certificate attribute present.");
            }
            if (attribute == null)
            {
            }
            if (request.ReqPolicy != null && !request.ReqPolicy.Equals(timeStampInfo.Policy))
            {
                throw new TspValidationException("TSA policy wrong for request.");
            }
        }
        else if (Status == 0 || Status == 1)
        {
            throw new TspValidationException("no time stamp token found and one expected.");
        }
    }
コード例 #5
0
        public void TestBasicSha256()
        {
            var sInfoGenerator = makeInfoGenerator(privateKey, cert, TspAlgorithms.Sha256, null, null);
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                sInfoGenerator,
                Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256), new DerObjectIdentifier("1.2"), true);


            tsTokenGen.SetCertificates(certs);

            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha256, new byte[32]);

            Assert.IsFalse(request.CertReq);

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

            AttributeTable table = tsToken.SignedAttributes;

            var r = table.Get(PkcsObjectIdentifiers.IdAASigningCertificateV2);

            Assert.NotNull(r);
            Assert.AreEqual(PkcsObjectIdentifiers.IdAASigningCertificateV2, r.AttrType);
            var set = r.AttrValues;
            SigningCertificateV2 sCert = SigningCertificateV2.GetInstance(set[0]);

            var issSerNum = sCert.GetCerts()[0].IssuerSerial;

            Assert.AreEqual(cert.SerialNumber, issSerNum.Serial.Value);
        }
コード例 #6
0
    public static ICollection GetSignatureTimestamps(SignerInformation signerInfo)
    {
        IList list = Platform.CreateArrayList();

        Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInfo.UnsignedAttributes;
        if (unsignedAttributes != null)
        {
            foreach (Org.BouncyCastle.Asn1.Cms.Attribute item in unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken))
            {
                foreach (Asn1Encodable attrValue in item.AttrValues)
                {
                    try
                    {
                        Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(attrValue.ToAsn1Object());
                        TimeStampToken     timeStampToken = new TimeStampToken(instance);
                        TimeStampTokenInfo timeStampInfo  = timeStampToken.TimeStampInfo;
                        byte[]             a = DigestUtilities.CalculateDigest(GetDigestAlgName(timeStampInfo.MessageImprintAlgOid), signerInfo.GetSignature());
                        if (!Arrays.ConstantTimeAreEqual(a, timeStampInfo.GetMessageImprintDigest()))
                        {
                            throw new TspValidationException("Incorrect digest in message imprint");
                        }
                        list.Add(timeStampToken);
                    }
                    catch (SecurityUtilityException)
                    {
                        throw new TspValidationException("Unknown hash algorithm specified in timestamp");
                    }
                    catch (Exception)
                    {
                        throw new TspValidationException("Timestamp could not be parsed");
                    }
                }
            }
            return(list);
        }
        return(list);
    }
コード例 #7
0
        public void TestAccuracyWithCertsAndOrdering()
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2.3");

            tsTokenGen.SetCertificates(certs);

            tsTokenGen.SetAccuracySeconds(3);
            tsTokenGen.SetAccuracyMillis(1);
            tsTokenGen.SetAccuracyMicros(2);

            tsTokenGen.SetOrdering(true);

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            reqGen.SetCertReq(true);

            TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));

            Assert.IsTrue(request.CertReq);

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            //
            // check validation
            //
            tsResp.Validate(request);

            //
            // check tstInfo
            //
            TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

            //
            // check accuracy
            //
            GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy;

            Assert.AreEqual(3, accuracy.Seconds);
            Assert.AreEqual(1, accuracy.Millis);
            Assert.AreEqual(2, accuracy.Micros);

            Assert.AreEqual(BigInteger.ValueOf(23), tstInfo.SerialNumber);

            Assert.AreEqual("1.2.3", tstInfo.Policy);

            Assert.AreEqual(true, tstInfo.IsOrdered);

            Assert.AreEqual(tstInfo.Nonce, BigInteger.ValueOf(100));

            //
            // test certReq
            //
            IX509Store store = tsToken.GetCertificates("Collection");

            ICollection certificates = store.GetMatches(null);

            Assert.AreEqual(2, certificates.Count);
        }
コード例 #8
0
 public void InspectTimeStampTokenInfo(TimeStampTokenInfo info)
 {
     Console.WriteLine(info.GenTime);
 }
コード例 #9
0
ファイル: PdfPKCS7.cs プロジェクト: mohsenmetn/itextsharp
        /**
         * Use this constructor if you want to verify a signature using
         * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param tsp set to true if there's a PAdES LTV time stamp.
         * @param provider the provider or <code>null</code> for the default provider
         */
        public PdfPKCS7(byte[] contentsKey, bool tsp)
        {
            isTsp = tsp;
            Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));

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

            try {
                pkcs = din.ReadObject();
            }
            catch  {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object"));
            }
            if (!(pkcs is Asn1Sequence))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
            }
            Asn1Sequence        signedData = (Asn1Sequence)pkcs;
            DerObjectIdentifier objId      = (DerObjectIdentifier)signedData[0];

            if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
            }
            Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[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 = ((DerInteger)content[0]).Value.IntValue;

            // the digestAlgorithms
            digestalgos = new Dictionary <string, object>();
            IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();

            while (e.MoveNext())
            {
                Asn1Sequence        s = (Asn1Sequence)e.Current;
                DerObjectIdentifier o = (DerObjectIdentifier)s[0];
                digestalgos[o.Id] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser();

            certs = new List <X509Certificate>();
            foreach (X509Certificate cc in cf.ReadCertificates(contentsKey))
            {
                certs.Add(cc);
            }
            crls = new List <X509Crl>();

            // the possible ID_PKCS7_DATA
            Asn1Sequence rsaData = (Asn1Sequence)content[2];

            if (rsaData.Count > 1)
            {
                Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject();
                RSAdata = rsaDataContent.GetOctets();
            }

            // the signerInfos
            int next = 3;

            while (content[next] is Asn1TaggedObject)
            {
                ++next;
            }
            Asn1Set signerInfos = (Asn1Set)content[next];

            if (signerInfos.Count != 1)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
            }
            Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[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 = ((DerInteger)signerInfo[0]).Value.IntValue;
            // Get the signing certificate
            Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];

            Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]);
            BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;

            foreach (X509Certificate cert in certs)
            {
                if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber))
                {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1",
                                                                                   issuer.ToString() + " / " + serialNumber.ToString(16)));
            }
            CalcSignCertificateChain();
            digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
            next = 3;
            if (signerInfo[next] is Asn1TaggedObject)
            {
                Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
                Asn1Set          sseq   = Asn1Set.GetInstance(tagsig, false);
                sigAttr = sseq.GetEncoded(Asn1Encodable.Der);

                for (int k = 0; k < sseq.Count; ++k)
                {
                    Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
                    if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_MESSAGE_DIGEST))
                    {
                        Asn1Set sset = (Asn1Set)seq2[1];
                        digestAttr = ((DerOctetString)sset[0]).GetOctets();
                    }
                    else if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_ADBE_REVOCATION))
                    {
                        Asn1Set      setout = (Asn1Set)seq2[1];
                        Asn1Sequence seqout = (Asn1Sequence)setout[0];
                        for (int j = 0; j < seqout.Count; ++j)
                        {
                            Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                            if (tg.TagNo == 1)
                            {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindOcsp(seqin);
                            }
                            if (tg.TagNo == 0)
                            {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindCRL(seqin);
                            }
                        }
                    }
                }
                if (digestAttr == null)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest"));
                }
                ++next;
            }
            digestEncryptionAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
            digest = ((Asn1OctetString)signerInfo[next++]).GetOctets();
            if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject))
            {
                Asn1TaggedObject taggedObject = (Asn1TaggedObject)signerInfo[next];
                Asn1Set          unat         = Asn1Set.GetInstance(taggedObject, false);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
                Org.BouncyCastle.Asn1.Cms.Attribute      ts     = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
                if (ts != null && ts.AttrValues.Count > 0)
                {
                    Asn1Set      attributeValues = ts.AttrValues;
                    Asn1Sequence tokenSequence   = Asn1Sequence.GetInstance(attributeValues[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.TimeStampInfo;
                String             algOID = info.MessageImprintAlgOid;
                messageDigest = DigestUtilities.GetDigest(algOID);
            }
            else
            {
                if (RSAdata != null || digestAttr != null)
                {
                    messageDigest = GetHashClass();
                    encContDigest = GetHashClass();
                }
                sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
                sig.Init(false, signCert.GetPublicKey());
            }
        }