Exemplo n.º 1
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 attribute in unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken))
                {
                    foreach (Asn1Encodable asn1Encodable in attribute.AttrValues)
                    {
                        try
                        {
                            Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(asn1Encodable.ToAsn1Object());
                            TimeStampToken     timeStampToken = new TimeStampToken(instance);
                            TimeStampTokenInfo timeStampInfo  = timeStampToken.TimeStampInfo;
                            byte[]             a = DigestUtilities.CalculateDigest(TspUtil.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);
        }
Exemplo n.º 2
0
        protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData)
        {
            if (si is null)
            {
                throw new ArgumentNullException(nameof(si));
            }

            if (parameters is null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            SignerInformation newSi         = base.ExtendCMSSignature(signedData, si, parameters, originalData);
            IDictionary       unsignedAttrs = newSi.UnsignedAttributes.ToDictionary();
            CAdESSignature    signature     = new CAdESSignature(signedData, si.SignerID);

            unsignedAttrs = ExtendUnsignedAttributes(
                unsignedAttrs,
                signature.SigningCertificate,
                parameters,
                signature.SigningTime.Value,
                signature.CertificateSource);
            return(SignerInformation.ReplaceUnsignedAttributes(newSi, new BcCms.AttributeTable(unsignedAttrs)));
        }
Exemplo n.º 3
0
 public CAdESSignature(CmsSignedData cms, SignerInformation signerInformation)
 {
     _cmsSignedData         = cms;
     this.signerInformation = signerInformation;
 }
Exemplo n.º 4
0
        public byte[] FirmaFileBouncy(string NomeFile, X509Certificate2 cert, bool GiaFirmato, bool UsaTSA, string TSAurl, string TSAuser, string TSApass, out string RisFirma)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(cert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);
                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();
                var rsa = (RSACryptoServiceProvider)cert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                //mi ricavo il file da firmare
                FileInfo FileDaAprire = new FileInfo(NomeFile);

                /*CmsSignedData Firmato;
                 * if (GiaFirmato) {
                 *      CmsSignedData signedData = new CmsSignedData(File.ReadAllBytes(NomeFile));
                 *      if (signedData!=null){
                 *              SignerInformationStore signers = signedData.GetSignerInfos();
                 *              certList.Add(signers.GetSigners());
                 *              //MessageBox.Show(signedData.ContentInfo.GetEncoded().Length.ToString());
                 *              //signedData.ContentInfo.GetEncoded();
                 *      }
                 *      certList.Insert(0,certCopy);
                 *      CmsProcessableByteArray file = new CmsProcessableByteArray(signedData.ContentInfo.GetEncoded());
                 *      Firmato = cms.Generate(file, true);
                 * } else {
                 *      certList.Add(certCopy);
                 *      CmsProcessableFile file = new CmsProcessableFile(FileDaAprire);
                 *      Firmato = cms.Generate(file, true);
                 * }
                 */
                CmsProcessableFile file    = new CmsProcessableFile(FileDaAprire);
                CmsSignedData      Firmato = cms.Generate(file, true);
                byte[]             Encoded = Firmato.GetEncoded();

                if (UsaTSA)
                {
                    CmsSignedData          sd      = new CmsSignedData(Encoded);
                    SignerInformationStore signers = sd.GetSignerInfos();
                    byte[]            signature    = null;
                    SignerInformation signer       = null;
                    foreach (SignerInformation signer_ in signers.GetSigners())
                    {
                        signer = signer_;
                        break;
                    }

                    signature = signer.GetSignature();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass));
                    signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
                    IList signerInfos = new ArrayList();
                    signerInfos.Add(signer);
                    sd      = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
                    Encoded = sd.GetEncoded();
                }
                RisFirma = "";
                return(Encoded);
            }
            catch (Exception ex)
            {
                RisFirma = ex.ToString();
                return(null);
            }
        }
 internal SecureMimeDigitalSignature(SignerInformation signerInfo)
 {
     SignerInfo = signerInfo;
 }
        public void TestEncapsulatedSignerStoreReplacement()
        {
            IList        certList = new ArrayList();
            MemoryStream bOut     = new MemoryStream();

            certList.Add(OrigCert);
            certList.Add(SignCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);

            gen.AddCertificates(x509Certs);

            Stream sigOut = gen.Open(bOut, true);

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
            sigOut.Write(testBytes, 0, testBytes.Length);

            sigOut.Close();

            //
            // create new Signer
            //
            MemoryStream original = new MemoryStream(bOut.ToArray(), false);

            bOut.SetLength(0);

            gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha224);

            gen.AddCertificates(x509Certs);

            sigOut = gen.Open(bOut, true);

            sigOut.Write(testBytes, 0, testBytes.Length);

            sigOut.Close();

            CmsSignedData sd = new CmsSignedData(bOut.ToArray());

            //
            // replace signer
            //
            MemoryStream newOut = new MemoryStream();

            CmsSignedDataParser.ReplaceSigners(original, sd.GetSignerInfos(), newOut);

            sd = new CmsSignedData(newOut.ToArray());

            IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator();

            signerEnum.MoveNext();
            SignerInformation signer = (SignerInformation)signerEnum.Current;

            Assert.AreEqual(signer.DigestAlgOid, CmsSignedDataStreamGenerator.DigestSha224);

            CmsSignedDataParser sp = new CmsSignedDataParser(newOut.ToArray());

            sp.GetSignedContent().Drain();

            VerifySignatures(sp);
        }
Exemplo n.º 7
0
		private void VerifySigner(SignerInformation signer, X509Certificate cert)
		{
			if (cert.GetPublicKey() is DsaPublicKeyParameters)
			{
				DsaPublicKeyParameters key = (DsaPublicKeyParameters)cert.GetPublicKey();

				if (key.Parameters == null)
				{
					Assert.IsTrue(signer.Verify(GetInheritedKey(key)));
				}
				else
				{
					Assert.IsTrue(signer.Verify(cert));
				}
			}
			else
			{
				Assert.IsTrue(signer.Verify(cert));
			}
		}
Exemplo n.º 8
0
		private void VerifyCounterSignature(SignerInformation signInfo, byte[] certificate)
		{
			SignerInformation csi = GetFirstSignerInfo(signInfo.GetCounterSignatures());

			X509Certificate cert = new X509CertificateParser().ReadCertificate(certificate);

			Assert.IsTrue(csi.Verify(cert));
		}
Exemplo n.º 9
0
 internal virtual void AddSignerCallback(SignerInformation si)
 {
 }
Exemplo n.º 10
0
        protected void Complete(Level?level, Stream embedded, Stream signed, Stream content, X509Certificate2 providedSigner, out TimemarkKey timemarkKey)
        {
#if NETFRAMEWORK
            trace.TraceEvent(TraceEventType.Information, 0, "Completing the message with of {0} bytes to level {1}", signed.Length, level);
#else
            logger.LogInformation("Completing the message with of {0} bytes to level {1}", signed.Length, level);
#endif

            //Create the objects we need
            var gen    = new CmsSignedDataStreamGenerator();
            var parser = new CmsSignedDataParser(signed);
            timemarkKey = new TimemarkKey();

            //preset the digests so we can add the signers afterwards
            gen.AddDigests(parser.DigestOids);

            //Copy the content to the output
            Stream contentOut = gen.Open(embedded, parser.SignedContentType.Id, true);
            if (content != null)
            {
                content.CopyTo(contentOut);
            }
            else
            {
                parser.GetSignedContent().ContentStream.CopyTo(contentOut);
            }

            //Extract the various data from outer layer
            SignerInformation signerInfo    = ExtractSignerInfo(parser);
            IX509Store        embeddedCerts = parser.GetCertificates("Collection");

            //Extract the various data from signer info
            timemarkKey.SignatureValue = signerInfo.GetSignature();
            timemarkKey.SigningTime    = ExtractSigningTime(signerInfo);
            timemarkKey.Signer         = ExtractSignerCert(embeddedCerts, signerInfo, providedSigner);
            if (timemarkKey.Signer != null)
            {
                timemarkKey.SignerId = DotNetUtilities.FromX509Certificate(timemarkKey.Signer).GetSubjectKeyIdentifier();
            }
            else
            {
                timemarkKey.SignerId = signerInfo.SignerID.ExtractSignerId();
            }

            //Extract the various data from unsiged attributes of signer info
            IDictionary unsignedAttributes = signerInfo.UnsignedAttributes != null?signerInfo.UnsignedAttributes.ToDictionary() : new Hashtable();

            TimeStampToken   tst            = ExtractTimestamp(unsignedAttributes);
            RevocationValues revocationInfo = ExtractRevocationInfo(unsignedAttributes);

            //quick check for an expected error and extrapolate some info
            if (timemarkKey.SignerId == null)
            {
#if NETFRAMEWORK
                trace.TraceEvent(TraceEventType.Error, 0, "We could not find any signer information");
#else
                logger.LogError("We could not find any signer information");
#endif
                throw new InvalidMessageException("The message does not contain any valid signer info");
            }

            if (timemarkKey.SigningTime == default && tst != null)
            {
#if NETFRAMEWORK
                trace.TraceEvent(TraceEventType.Information, 0, "Implicit signing time is replaced with time-stamp time {1}", tst.TimeStampInfo.GenTime);
#else
                logger.LogInformation("Implicit signing time is replaced with time-stamp time {1}", tst.TimeStampInfo.GenTime);
#endif
                timemarkKey.SigningTime = tst.TimeStampInfo.GenTime;
            }

            //Are we missing embedded certs and should we add them?
            if ((embeddedCerts == null || embeddedCerts.GetMatches(null).Count <= 1) &&
                timemarkKey.Signer != null &&
                level != null)
            {
                embeddedCerts = GetEmbeddedCerts(timemarkKey);
            }
            if (embeddedCerts != null)
            {
                gen.AddCertificates(embeddedCerts);                        //add the existing or new embedded certs to the output.
            }
            //Are we missing timestamp and should we add them (not that time-mark authorities do not require a timestamp provider)
            if (tst == null &&
                (level & Level.T_Level) == Level.T_Level && timestampProvider != null)
            {
                tst = GetTimestamp(timemarkKey);
                AddTimestamp(unsignedAttributes, tst);
            }

            //should be make sure we have the proper revocation info (it is hard to tell if we have everything, just go for it)
            if ((level & Level.L_Level) == Level.L_Level)
            {
                if (embeddedCerts != null && embeddedCerts.GetMatches(null).Count > 0)
                {
                    //extend the revocation info with info about the embedded certs
                    revocationInfo = GetRevocationValues(timemarkKey, embeddedCerts, revocationInfo);
                }
                if (tst != null)
                {
                    //extend the revocation info with info about the TST
                    revocationInfo = GetRevocationValues(tst, revocationInfo);
                }
                //update the unsigned attributes
                AddRevocationValues(unsignedAttributes, revocationInfo);
            }

            //Update the unsigned attributes of the signer info
            signerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, new BC::Asn1.Cms.AttributeTable(unsignedAttributes));

            //Copy the signer
            gen.AddSigners(new SignerInformationStore(new SignerInformation[] { signerInfo }));

            contentOut.Close();
        }
Exemplo n.º 11
0
        protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData)
        {
            if (si is null)
            {
                throw new System.ArgumentNullException(nameof(si));
            }

            if (SignatureTsa == null)
            {
                throw new System.ArgumentNullException(nameof(SignatureTsa));
            }
            logger.Info("Extend signature with id " + si.SignerID);
            BcCms.AttributeTable unsigned = si.UnsignedAttributes;
            IDictionary          unsignedAttrHash;

            if (unsigned is null)
            {
                unsignedAttrHash = new Dictionary <DerObjectIdentifier, Attribute>();
            }
            else
            {
                unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
            }

            //TODO: jbonilla - What happens if it is already CAdES-T? It should not be extended again.
            Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, SignatureTsa, si.GetSignature());

            unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp);
            SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable
                                                                                      (unsignedAttrHash));

            return(newsi);
        }
Exemplo n.º 12
0
        protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData)
        {
            si = base.ExtendCMSSignature(signedData, si, parameters, originalData);
            using (var toTimestamp = new MemoryStream())
            {
                DerObjectIdentifier attributeId;
                switch (GetExtendedValidationType())
                {
                case 1:
                {
                    attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp;
                    toTimestamp.Write(si.GetSignature());
                    // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5,
                    // NOTE 2)
                    toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrType.GetDerEncoded());
                    toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrValues.GetDerEncoded());
                    break;
                }

                case 2:
                {
                    attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp;
                    break;
                }

                default:
                {
                    return(si);
                }
                }
                toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs].AttrType.GetDerEncoded());
                toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs].AttrValues.GetDerEncoded());
                toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs].AttrType.GetDerEncoded());
                toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs].AttrValues.GetDerEncoded());
                var             unsignedAttrHash  = si.UnsignedAttributes.ToDictionary();
                BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, SignatureTsa, toTimestamp.ToArray());
                unsignedAttrHash.Add(attributeId, extendedTimeStamp);
                return(SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash)));
            }
        }
        /// <summary>
        ///     Verify signed bytes and PKCS#7 signature.
        /// </summary>
        /// <param name="signedBytes">signed bytes</param>
        /// <param name="signatureBytes">signature bytes</param>
        /// <param name="data">other data</param>
        public void Verify(byte[] signedBytes, byte[] signatureBytes, CryptoSignatureVerificationData data = null)
        {
            if (signedBytes == null)
            {
                throw new ArgumentNullException(nameof(signedBytes));
            }

            if (signatureBytes == null)
            {
                throw new ArgumentNullException(nameof(signatureBytes));
            }

            if (_trustAnchors == null && data?.CertificateBytes == null)
            {
                throw new ArgumentException("No trust anchors given.");
            }

            CmsSignedData signedData;

            try
            {
                CmsProcessableByteArray cmsProcessableByteArray = new CmsProcessableByteArray(signedBytes);
                signedData = new CmsSignedData(cmsProcessableByteArray, signatureBytes);
            }
            catch (Exception e)
            {
                throw new PkiVerificationErrorException("Cannot create signature from " + nameof(signatureBytes), e);
            }

            SignerInformationStore signerInformationStore = signedData.GetSignerInfos();
            ICollection            signerCollection       = signerInformationStore.GetSigners();

            if (signerCollection.Count == 0)
            {
                throw new PkiVerificationFailedException("Signature does not contain any SignerInformation element.");
            }

            IX509Store x509Store = signedData.GetCertificates("collection");

            IEnumerator signerInfoCollectionEnumerator = signerCollection.GetEnumerator();

            while (signerInfoCollectionEnumerator.MoveNext())
            {
                SignerInformation signerInfo = (SignerInformation)signerInfoCollectionEnumerator.Current;

                if (signerInfo == null)
                {
                    throw new PkiVerificationErrorException("Signature does not contain any SignerInformation element.");
                }

                ICollection x509Collection = x509Store.GetMatches(signerInfo.SignerID);
                IEnumerator x509CertificateCollectionEnumerator = x509Collection.GetEnumerator();
                if (!x509CertificateCollectionEnumerator.MoveNext())
                {
                    throw new PkiVerificationErrorException("Signature does not contain any x509 certificates.");
                }

                X509Certificate certificate = (X509Certificate)x509CertificateCollectionEnumerator.Current;

                if (data != null)
                {
                    try
                    {
                        CertificateTimeVerifier.Verify(certificate, data.SignTime);
                    }
                    catch (PkiVerificationFailedCertNotValidException ex)
                    {
                        throw new PkiVerificationFailedCertNotValidException("PKCS#7 signature certificate is not valid.", ex);
                    }
                }

                if (_certificateRdnSelector != null)
                {
                    try
                    {
                        // Verify certificate with rdn selector
                        if (!_certificateRdnSelector.IsMatch(certificate))
                        {
                            throw new PkiVerificationFailedException("Certificate did not match with certificate subject rdn selector.");
                        }
                    }
                    catch (PkiVerificationFailedException)
                    {
                        throw;
                    }
                    catch (Exception e)
                    {
                        throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                    }
                }

                try
                {
                    if (!signerInfo.Verify(certificate))
                    {
                        throw new PkiVerificationFailedException("Signer information does not match with certificate.");
                    }
                }
                catch (CmsException e)
                {
                    throw new PkiVerificationFailedException("Failed to verify PKCS#7 signature.", e);
                }
                catch (Exception e)
                {
                    throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                }

                ISet trustAnchors;

                if (data?.CertificateBytes != null)
                {
                    try
                    {
                        trustAnchors = new HashSet
                        {
                            new TrustAnchor(DotNetUtilities.FromX509Certificate(new X509Certificate2(data.CertificateBytes)), null)
                        };
                    }
                    catch (Exception e)
                    {
                        throw new PkiVerificationErrorException("Cannot create trust anchor certificate from " + nameof(data.CertificateBytes), e);
                    }
                }
                else
                {
                    trustAnchors = _trustAnchors;
                }

                try
                {
                    ValidateCertPath(certificate, x509Store, trustAnchors);
                }
                catch (PkiVerificationFailedException)
                {
                    throw;
                }

                catch (Exception e)
                {
                    throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                }
            }
        }
Exemplo n.º 14
0
        public void TestSignerStoreReplacement()
        {
            MemoryStream bOut = new MemoryStream();

            byte[] data = Encoding.ASCII.GetBytes(TestMessage);

            IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert);

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
            gen.AddCertificates(x509Certs);

            Stream sigOut = gen.Open(bOut, false);

            sigOut.Write(data, 0, data.Length);
            sigOut.Close();

            CheckSigParseable(bOut.ToArray());

            //
            // create new Signer
            //
            MemoryStream original = new MemoryStream(bOut.ToArray(), false);

            bOut.SetLength(0);

            gen = new CmsSignedDataStreamGenerator();
            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha224);

            gen.AddCertificates(x509Certs);

            sigOut = gen.Open(bOut);
            sigOut.Write(data, 0, data.Length);
            sigOut.Close();

            CheckSigParseable(bOut.ToArray());

            CmsSignedData sd = new CmsSignedData(bOut.ToArray());

            //
            // replace signer
            //
            MemoryStream newOut = new MemoryStream();

            CmsSignedDataParser.ReplaceSigners(original, sd.GetSignerInfos(), newOut);

            sd = new CmsSignedData(new CmsProcessableByteArray(data), newOut.ToArray());

            IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator();

            signerEnum.MoveNext();
            SignerInformation signer = (SignerInformation)signerEnum.Current;

            Assert.AreEqual(signer.DigestAlgOid, CmsSignedDataStreamGenerator.DigestSha224);

            CmsSignedDataParser sp = new CmsSignedDataParser(new CmsTypedStream(
                                                                 new MemoryStream(data, false)), newOut.ToArray());

            sp.GetSignedContent().Drain();

            VerifySignatures(sp);
        }
Exemplo n.º 15
0
 public CAdESSignature(CmsSignedData cms, SignerID id)
 {
     _cmsSignedData         = cms;
     this.signerInformation = BCStaticHelpers.GetSigner(cms, id);
 }
Exemplo n.º 16
0
 public static global::System.Collections.ICollection GetSignatureTimestamps(SignerInformation signerInfo)
 {
     global::System.Collections.IList         list = Platform.CreateArrayList();
     Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInfo.UnsignedAttributes;
     if (unsignedAttributes != null)
     {
         global::System.Collections.IEnumerator enumerator = unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken).GetEnumerator();
         try
         {
             while (enumerator.MoveNext())
             {
                 Attribute attribute = (Attribute)enumerator.get_Current();
                 {
                     global::System.Collections.IEnumerator enumerator2 = attribute.AttrValues.GetEnumerator();
                     try
                     {
                         while (enumerator2.MoveNext())
                         {
                             Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator2.get_Current();
                             try
                             {
                                 Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(asn1Encodable.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((object)timeStampToken);
                             }
                             catch (SecurityUtilityException)
                             {
                                 throw new TspValidationException("Unknown hash algorithm specified in timestamp");
                             }
                             catch (global::System.Exception)
                             {
                                 throw new TspValidationException("Timestamp could not be parsed");
                             }
                         }
                     }
                     finally
                     {
                         global::System.IDisposable disposable2 = enumerator2 as global::System.IDisposable;
                         if (disposable2 != null)
                         {
                             disposable2.Dispose();
                         }
                     }
                 }
             }
             return((global::System.Collections.ICollection)list);
         }
         finally
         {
             global::System.IDisposable disposable = enumerator as global::System.IDisposable;
             if (disposable != null)
             {
                 disposable.Dispose();
             }
         }
     }
     return((global::System.Collections.ICollection)list);
 }
Exemplo n.º 17
0
        private void VerifySignerInfo4_4(SignerInformation signerInfo, byte[] counterSigCert)
        {
            VerifyCounterSignature(signerInfo, counterSigCert);

            VerifyContentHint(signerInfo);
        }
Exemplo n.º 18
0
		private void VerifySignerInfo4_4(SignerInformation signerInfo, byte[] counterSigCert)
		{
			VerifyCounterSignature(signerInfo, counterSigCert);

			VerifyContentHint(signerInfo);
		}
Exemplo n.º 19
0
 /// <exception cref="System.IO.IOException"></exception>
 protected internal abstract SignerInformation ExtendCMSSignature(CmsSignedData signedData
                                                                  , SignerInformation si, SignatureParameters parameters, Document originalData);
Exemplo n.º 20
0
		private void VerifyContentHint(SignerInformation signInfo)
		{
			Asn1.Cms.AttributeTable attrTable = signInfo.UnsignedAttributes;

			Asn1.Cms.Attribute attr = attrTable[CmsAttributes.ContentHint];

			Assert.AreEqual(1, attr.AttrValues.Count);
		
			Asn1EncodableVector v = new Asn1EncodableVector(
				new DerUtf8String("Content Hints Description Buffer"),
				CmsObjectIdentifiers.Data);

			Assert.IsTrue(attr.AttrValues[0].Equals(new DerSequence(v)));
		}
Exemplo n.º 21
0
        protected internal override SignerInformation ExtendCMSSignature(CmsSignedData cmsSignedData, SignerInformation si, SignatureParameters parameters, Document originalDocument)
        {
            si = base.ExtendCMSSignature(cmsSignedData, si, parameters, originalDocument);
            CAdESSignature signature        = new CAdESSignature(cmsSignedData, si);
            IDictionary    unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
            Attribute      archiveTimeStamp = GetTimeStampAttribute(CAdESProfileA.id_aa_ets_archiveTimestamp, SignatureTsa, signature.GetArchiveTimestampData(0, originalDocument));

            unsignedAttrHash.Add(id_aa_ets_archiveTimestamp, archiveTimeStamp);
            SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new AttributeTable
                                                                                      (unsignedAttrHash));

            return(newsi);
        }
Exemplo n.º 22
0
 internal override void AddSignerCallback(SignerInformation si)
 {
     RegisterDigestOid(si.DigestAlgorithmID.Algorithm.Id);
 }
Exemplo n.º 23
0
 /**
  * generate a set of one or more SignerInformation objects representing counter signatures on
  * the passed in SignerInformation object.
  *
  * @param signer the signer to be countersigned
  * @param sigProvider the provider to be used for counter signing.
  * @return a store containing the signers.
  */
 public SignerInformationStore GenerateCounterSigners(
     SignerInformation signer)
 {
     return(this.Generate(null, new CmsProcessableByteArray(signer.GetSignature()), false).GetSignerInfos());
 }
Exemplo n.º 24
0
 internal SignerInfoNode(SignerInformation signerInformation, SignatureDocument sigDocument)
 {
     _signerInformation = signerInformation;
     _sigDocument       = sigDocument;
     ReadInformation();
 }
Exemplo n.º 25
0
        private DocsPaVO.documento.SignerInfo ExtractSignerInfo(List <string> ErrorMessageLst, IX509Store store, SignerInformation signer)
        {
            DocsPaVO.documento.SignerInfo         thisSinger = new DocsPaVO.documento.SignerInfo();
            Org.BouncyCastle.X509.X509Certificate cert1      = GetCertificate(signer, store);
            try
            {
                if (!signer.Verify(cert1))
                {
                    ErrorMessageLst.Add("Not valid signature");
                }
            }
            catch (Exception e)
            {
                ErrorMessageLst.Add(e.Message);
            }

            thisSinger.isCountersigner = signer.IsCounterSignature;
            if (signer.SignedAttributes != null)
            {
                if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2] == null)
                {
                    ErrorMessageLst.Add("Id-AA-SigningCertificateV2 not found");
                }

                if (signer.SignedAttributes[CmsAttributes.MessageDigest] == null)
                {
                    ErrorMessageLst.Add("Pkcs9AtMessageDigest not found");
                }


                if (!signer.IsCounterSignature) //Pare che i controfirmatari non ncessitino di questo parametro
                {
                    if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtContentType] == null)
                    {
                        ErrorMessageLst.Add("Pkcs9AtContentType not found");
                    }
                }

                thisSinger.SignatureAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(signer.DigestAlgorithmID.ObjectID);
                if (signer.SignedAttributes[CmsAttributes.SigningTime] != null)
                {
                    Org.BouncyCastle.Asn1.Cms.Attribute sigTime = signer.SignedAttributes[CmsAttributes.SigningTime];
                    if (sigTime.AttrValues.Count > 0)
                    {
                        try
                        {
                            thisSinger.SigningTime = GetSigningTime(sigTime.AttrValues[0]);
                        }
                        catch (Exception e)
                        {
                            ErrorMessageLst.Add("Error retriving SigningTime");
                        }
                    }
                }
            }
            else
            {
                ErrorMessageLst.Add("Missing SignedAttributes");
            }

            if (gestioneTSFirma)
            {
                List <TSInfo> tsArr = new List <TSInfo>();
                if (signer.UnsignedAttributes != null && signer.UnsignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASignatureTimeStampToken] != null)
                {
                    ICollection ret = Org.BouncyCastle.Tsp.TspUtil.GetSignatureTimestamps(signer);
                    foreach (Org.BouncyCastle.Tsp.TimeStampToken token in ret)
                    {
                        VerifyTimeStamp verifyTimeStamp = new VerifyTimeStamp();
                        ICollection     certsColl       = token.GetCertificates("COLLECTION").GetMatches(null);
                        TSInfo          timeStamp       = verifyTimeStamp.getTSCertInfo(certsColl);

                        timeStamp.TSdateTime     = token.TimeStampInfo.GenTime.ToLocalTime();
                        timeStamp.TSserialNumber = token.TimeStampInfo.SerialNumber.ToString();
                        timeStamp.TSimprint      = Convert.ToBase64String(token.TimeStampInfo.TstInfo.MessageImprint.GetEncoded());
                        timeStamp.TSdateTime     = token.TimeStampInfo.GenTime;
                        timeStamp.TSType         = TsType.PKCS;
                        tsArr.Add(timeStamp);
                    }
                }

                if (tsArr.Count > 0)
                {
                    thisSinger.SignatureTimeStampInfo = tsArr.ToArray();
                }
            }
            X509Certificate2 cert = new X509Certificate2(cert1.GetEncoded());

            thisSinger.CertificateInfo.RevocationStatus = CheckCertificate(cert);
            thisSinger.CertificateInfo.X509Certificate  = cert1.GetEncoded();

            thisSinger.CertificateInfo.RevocationStatusDescription = DecodeStatus(thisSinger.CertificateInfo.RevocationStatus);
            ParseCNIPASubjectInfo(ref thisSinger.SubjectInfo, cert.SubjectName.Name);

            thisSinger.CertificateInfo.IssuerName         = cert.IssuerName.Name;
            thisSinger.CertificateInfo.SerialNumber       = cert.SerialNumber;
            thisSinger.CertificateInfo.SignatureAlgorithm = cert.SignatureAlgorithm.FriendlyName;
            thisSinger.CertificateInfo.SubjectName        = cert.SubjectName.Name;
            thisSinger.CertificateInfo.ValidFromDate      = cert.NotBefore;
            thisSinger.CertificateInfo.ValidToDate        = cert.NotAfter;
            thisSinger.CertificateInfo.ThumbPrint         = cert.Thumbprint;

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("CertificateInfo.IssuerName: '{0}'", thisSinger.CertificateInfo.IssuerName);
            sb.AppendFormat("CertificateInfo.SerialNumber: '{0}'", thisSinger.CertificateInfo.SerialNumber);
            sb.AppendFormat("CertificateInfo.SignatureAlgorithm: '{0}'", thisSinger.CertificateInfo.SignatureAlgorithm);
            sb.AppendFormat("CertificateInfo.SubjectName: '{0}'", thisSinger.CertificateInfo.SubjectName);
            sb.AppendFormat("CertificateInfo.ValidFromDate: '{0}'", thisSinger.CertificateInfo.ValidFromDate);
            sb.AppendFormat("CertificateInfo.ValidToDate: '{0}'", thisSinger.CertificateInfo.ValidToDate);
            sb.AppendFormat("CertificateInfo.ThumbPrint: '{0}'", thisSinger.CertificateInfo.ThumbPrint);
            //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - {0}", sb.ToString()));


            //gestione controfirma
            if (signer.UnsignedAttributes != null)
            {
                if (signer.UnsignedAttributes[CmsAttributes.CounterSignature] != null)
                {
                    List <DocsPaVO.documento.SignerInfo> cSigsList = new List <DocsPaVO.documento.SignerInfo>();
                    List <string>          csignErrs         = new List <string> ();
                    SignerInformationStore counterSignatures = signer.GetCounterSignatures();
                    foreach (SignerInformation conunterSig in counterSignatures.GetSigners())
                    {
                        DocsPaVO.documento.SignerInfo cSigs = ExtractSignerInfo(csignErrs, store, conunterSig);
                        cSigsList.Add(cSigs);
                    }
                    if (csignErrs.Count > 0)
                    {
                        ErrorMessageLst.AddRange(csignErrs);
                    }
                    if (cSigsList.Count > 0)
                    {
                        thisSinger.counterSignatures = cSigsList.ToArray();
                    }
                }
            }
            return(thisSinger);
        }
Exemplo n.º 26
0
        public TimeStampToken(
            CmsSignedData signedData)
        {
            this.tsToken = signedData;

            if (!this.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 signerEnum = signers.GetEnumerator();

            signerEnum.MoveNext();
            tsaSignerInfo = (SignerInformation)signerEnum.Current;

            try
            {
                CmsProcessable content = tsToken.SignedContent;
                MemoryStream   bOut    = new MemoryStream();

                content.Write(bOut);

                this.tstInfo = new TimeStampTokenInfo(
                    TstInfo.GetInstance(
                        Asn1Object.FromByteArray(bOut.ToArray())));

                Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[
                    PkcsObjectIdentifiers.IdAASigningCertificate];

//				if (attr == null)
//				{
//					throw new TspValidationException(
//						"no signing certificate attribute found, time stamp invalid.");
//				}
//
//				SigningCertificate signCert = SigningCertificate.GetInstance(
//					attr.AttrValues[0]);
//
//				this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]);

                if (attr != null)
                {
                    SigningCertificate signCert = SigningCertificate.GetInstance(attr.AttrValues[0]);

                    this.certID = new CertID(EssCertID.GetInstance(signCert.GetCerts()[0]));
                }
                else
                {
                    attr = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];

                    if (attr == null)
                    {
                        throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
                    }

                    SigningCertificateV2 signCertV2 = SigningCertificateV2.GetInstance(attr.AttrValues[0]);

                    this.certID = new CertID(EssCertIDv2.GetInstance(signCertV2.GetCerts()[0]));
                }
            }
            catch (CmsException e)
            {
                throw new TspException(e.Message, e.InnerException);
            }
        }
Exemplo n.º 27
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual byte[] GetArchiveTimestampData(int index, Document originalDocument
                                                      )
        {
            ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

            BcCms.ContentInfo contentInfo = cmsSignedData.ContentInfo;
            BcCms.SignedData  signedData  = BcCms.SignedData.GetInstance(contentInfo.Content);
            // 5.4.1
            if (signedData.EncapContentInfo == null || signedData.EncapContentInfo.
                Content == null)
            {
                if (originalDocument != null)
                {
                    //jbonilla Hack para leer un InputStream en su totalidad.
                    toTimestamp.Write(Streams.ReadAll(
                                          originalDocument.OpenStream()));
                }
                else
                {
                    throw new RuntimeException("Signature is detached and no original data provided."
                                               );
                }
            }
            else
            {
                BcCms.ContentInfo content = signedData.EncapContentInfo;
                DerOctetString    octet   = (DerOctetString)content.Content;
                BcCms.ContentInfo info2   = new BcCms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1"
                                                                                          ), new BerOctetString(octet.GetOctets()));
                toTimestamp.Write(info2.GetEncoded());
            }
            if (signedData.Certificates != null)
            {
                DerOutputStream output = new DerOutputStream(toTimestamp);
                output.WriteObject(signedData.Certificates);
                output.Close();
            }
            if (signedData.CRLs != null)
            {
                toTimestamp.Write(signedData.CRLs.GetEncoded());
            }
            if (signerInformation.UnsignedAttributes != null)
            {
                Asn1EncodableVector original = signerInformation.UnsignedAttributes.ToAsn1EncodableVector
                                                   ();
                IList <BcCms.Attribute> timeStampToRemove = GetTimeStampToRemove(index);
                Asn1EncodableVector     filtered          = new Asn1EncodableVector();
                for (int i = 0; i < original.Count; i++)
                {
                    Asn1Encodable enc = original[i];
                    if (!timeStampToRemove.Contains(enc))
                    {
                        filtered.Add(original[i]);
                    }
                }
                SignerInformation filteredInfo = SignerInformation.ReplaceUnsignedAttributes(signerInformation
                                                                                             , new BcCms.AttributeTable(filtered));
                toTimestamp.Write(filteredInfo.ToSignerInfo().GetEncoded());
            }
            return(toTimestamp.ToByteArray());
        }