Exemplo n.º 1
0
 internal SignerInfo(SignedCms signedCms, SafeLocalAllocHandle pbCmsgSignerInfo)
 {
     this.m_signedCms = signedCms;
     this.m_parentSignerInfo = (SignerInfo)null;
     this.m_encodedSignerInfo = (byte[])null;
     this.m_pbCmsgSignerInfo = pbCmsgSignerInfo;
     this.m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO)Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));
 }
Exemplo n.º 2
0
 internal SignerInfo(SignedCms signedCms, SignerInfo parentSignerInfo, byte[] encodedSignerInfo)
 {
     uint cbDecodedValue = 0U;
     SafeLocalAllocHandle decodedValue = SafeLocalAllocHandle.InvalidHandle;
     fixed (byte* numPtr = &encodedSignerInfo[0])
     {
         if (!CAPI.DecodeObject(new IntPtr(500L), new IntPtr((void*)numPtr), (uint)encodedSignerInfo.Length, out decodedValue, out cbDecodedValue))
             throw new CryptographicException(Marshal.GetLastWin32Error());
     }
     this.m_signedCms = signedCms;
     this.m_parentSignerInfo = parentSignerInfo;
     this.m_encodedSignerInfo = (byte[])encodedSignerInfo.Clone();
     this.m_pbCmsgSignerInfo = decodedValue;
     this.m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));
 }
Exemplo n.º 3
0
        public static void CheckSignature_ThrowsOnNullStore()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPssDocument);
            SignerInfo signer = cms.SignerInfos[0];

            AssertExtensions.Throws <ArgumentNullException>(
                "extraStore",
                () => signer.CheckSignature(null, true));

            AssertExtensions.Throws <ArgumentNullException>(
                "extraStore",
                () => signer.CheckSignature(null, false));
        }
Exemplo n.º 4
0
        public static void CheckSignature_ExtraStore_IsAdditional()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
            SignerInfo signer = cms.SignerInfos[0];

            Assert.NotNull(signer.Certificate);

            // Assert.NotThrows
            signer.CheckSignature(true);

            // Assert.NotThrows
            signer.CheckSignature(new X509Certificate2Collection(), true);
        }
        private bool CheckForVersion3(
            IList signerInfos)
        {
            foreach (SignerInformation si in signerInfos)
            {
                SignerInfo s = SignerInfo.GetInstance(si.ToSignerInfo());

                if (s.Version.Value.IntValue == 3)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 6
0
        private static void VerifySigningCertificate(
            SignedCms signedCms,
            SignerInfo signerInfo,
            SigningSpecifications signingSpecifications)
        {
            var certificates = SignatureUtility.GetPrimarySignatureCertificates(
                signedCms,
                signerInfo,
                signingSpecifications);

            if (certificates == null || certificates.Count == 0)
            {
                ThrowForInvalidPrimarySignature();
            }
        }
Exemplo n.º 7
0
        public static void AddCounterSigner_DuplicateCert_RSA()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
            Assert.Single(cms.Certificates);

            SignerInfo firstSigner = cms.SignerInfos[0];

            Assert.Empty(firstSigner.CounterSignerInfos);
            Assert.Empty(firstSigner.UnsignedAttributes);

            using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
                firstSigner.ComputeCounterSignature(signer);
            }

            Assert.Empty(firstSigner.CounterSignerInfos);
            Assert.Empty(firstSigner.UnsignedAttributes);

            SignerInfo firstSigner2 = cms.SignerInfos[0];

            Assert.Single(firstSigner2.CounterSignerInfos);
            Assert.Single(firstSigner2.UnsignedAttributes);

            SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];

            Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner.SignerIdentifier.Type);

            // On NetFx there will be two attributes, because Windows emits the
            // content-type attribute even for counter-signers.
            int expectedAttrCount = 1;

            // One of them is a V3 signer.
#if netfx
            expectedAttrCount = 2;
#endif
            Assert.Equal(expectedAttrCount, counterSigner.SignedAttributes.Count);
            Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedAttrCount - 1].Oid.Value);

            Assert.Equal(firstSigner2.Certificate, counterSigner.Certificate);
            Assert.Single(cms.Certificates);

            counterSigner.CheckSignature(true);
            firstSigner2.CheckSignature(true);
            cms.CheckSignature(true);
        }
Exemplo n.º 8
0
 public SignerInformationStore GetSignerInfos()
 {
     //IL_00e9: Expected O, but got Unknown
     if (_signerInfoStore == null)
     {
         PopulateCertCrlSets();
         global::System.Collections.IList list = Platform.CreateArrayList();
         IDictionary val = Platform.CreateHashtable();
         {
             global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)_digests.get_Keys()).GetEnumerator();
             try
             {
                 while (enumerator.MoveNext())
                 {
                     object current = enumerator.get_Current();
                     val.set_Item(current, (object)DigestUtilities.DoFinal((IDigest)_digests.get_Item(current)));
                 }
             }
             finally
             {
                 global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                 if (disposable != null)
                 {
                     disposable.Dispose();
                 }
             }
         }
         try
         {
             Asn1SetParser    signerInfos = _signedData.GetSignerInfos();
             IAsn1Convertible asn1Convertible;
             while ((asn1Convertible = signerInfos.ReadObject()) != null)
             {
                 SignerInfo instance      = SignerInfo.GetInstance(asn1Convertible.ToAsn1Object());
                 string     digestAlgName = Helper.GetDigestAlgName(instance.DigestAlgorithm.Algorithm.Id);
                 byte[]     digest        = (byte[])val.get_Item((object)digestAlgName);
                 list.Add((object)new SignerInformation(instance, _signedContentType, null, new BaseDigestCalculator(digest)));
             }
         }
         catch (IOException val2)
         {
             IOException val3 = val2;
             throw new CmsException("io exception: " + ((global::System.Exception)(object) val3).get_Message(), (global::System.Exception)(object) val3);
         }
         _signerInfoStore = new SignerInformationStore((global::System.Collections.ICollection)list);
     }
     return(_signerInfoStore);
 }
Exemplo n.º 9
0
        /// <summary>
        /// Verifies the digital signature.
        /// </summary>
        /// <remarks>
        /// Verifies the digital signature.
        /// </remarks>
        /// <returns><c>true</c> if the signature is valid; otherwise <c>false</c>.</returns>
        /// <exception cref="DigitalSignatureVerifyException">
        /// An error verifying the signature has occurred.
        /// </exception>
        public bool Verify()
        {
            if (vex != null)
            {
                throw vex;
            }

            try {
                SignerInfo.CheckSignature(false);
                return(true);
            } catch (Exception ex) {
                var message = string.Format("Failed to verify digital signature: {0}", ex.Message);
                vex = new DigitalSignatureVerifyException(message, ex);
                throw vex;
            }
        }
Exemplo n.º 10
0
        public static void RemoveCounterSignature_TooBigByValue()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
            SignerInfo signer = cms.SignerInfos[0];

            Assert.Throws <CryptographicException>(
                () => signer.RemoveCounterSignature(2));

            signer.RemoveCounterSignature(1);
            Assert.Equal(2, signer.CounterSignerInfos.Count);

            Assert.Throws <CryptographicException>(
                () => signer.RemoveCounterSignature(1));
        }
Exemplo n.º 11
0
 /**
  * Protected constructor. In some cases clients have their own idea about how to encode
  * the signed attributes and calculate the signature. This constructor is to allow developers
  * to deal with that by extending off the class and overridng methods like getSignedAttributes().
  *
  * @param baseInfo the SignerInformation to base this one on.
  */
 protected SignerInformation(SignerInformation baseInfo)
 {
     this.info               = baseInfo.info;
     this.contentType        = baseInfo.contentType;
     this.isCounterSignature = baseInfo.IsCounterSignature;
     this.sid                    = baseInfo.SignerID;
     this.digestAlgorithm        = info.DigestAlgorithm;
     this.signedAttributeSet     = info.AuthenticatedAttributes;
     this.unsignedAttributeSet   = info.UnauthenticatedAttributes;
     this.encryptionAlgorithm    = info.DigestEncryptionAlgorithm;
     this.signature              = info.EncryptedDigest.GetOctets();
     this.content                = baseInfo.content;
     this.resultDigest           = baseInfo.resultDigest;
     this.signedAttributeTable   = baseInfo.signedAttributeTable;
     this.unsignedAttributeTable = baseInfo.unsignedAttributeTable;
 }
Exemplo n.º 12
0
        public static void RemoveCounterSignature_TooBigByMatch()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
            SignerInfo signer        = cms.SignerInfos[0];
            SignerInfo counterSigner = signer.CounterSignerInfos[1];

            // This succeeeds, but reduces the real count to 1.
            signer.RemoveCounterSignature(counterSigner);
            Assert.Equal(2, signer.CounterSignerInfos.Count);
            Assert.Single(cms.SignerInfos[0].CounterSignerInfos);

            Assert.Throws <CryptographicException>(
                () => signer.RemoveCounterSignature(counterSigner));
        }
Exemplo n.º 13
0
        private void AppendRowsStatus()
        {
            //SignerInfo signerInfo=this._signatureResult.PKCS7Documents[this._requestDocumentIndex].SignersInfo[this._requestSignerIndex];
            SignerInfo signerInfo = getSignerInfo(this._requestDocumentIndex, Request.QueryString["index"]);
            TableRow   row        = this.CreateHeaderTableRow();

            row.Cells[0].Text = "Risultato verifica";

            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Stato della firma";

            row.Cells[1].Controls.Add(this.GetStatusFirmaImage(signerInfo != null));

            // Per verificare la validità della firma,
            // verifica la presenza di almeno un firmatario
            if (signerInfo.CertificateInfo.ThumbPrint != null && signerInfo.CertificateInfo.ThumbPrint != "")
            {
                row.Cells[2].Text = "Valido";
                //controlliamo l'aa
                if (this._signatureResult.StatusCode == -5)
                {
                    row.Cells[2].Text = "Non Conforme CADES (idaasigningcertificateV2 non trovato nella firma)";
                }
            }
            else
            {
                row.Cells[2].Text = "Non valido";
            }

            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Stato del certificato";
            row.Cells[1].Controls.Add(this.GetStatusImage(signerInfo.CertificateInfo.RevocationStatus == 0));
            row.Cells[2].Text = signerInfo.CertificateInfo.RevocationStatusDescription;
            row = null;

            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Verifica CRL:";
            if (this._signatureResult.CRLOnlineCheck)
            {
                row.Cells[2].Text = "In linea";
            }
            else
            {
                row.Cells[2].Text = "Locale";
            }
            row = null;
        }
Exemplo n.º 14
0
        public static void AddCounterSigner_RSA(SubjectIdentifierType identifierType)
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
            Assert.Single(cms.Certificates);

            SignerInfo firstSigner = cms.SignerInfos[0];

            Assert.Empty(firstSigner.CounterSignerInfos);
            Assert.Empty(firstSigner.UnsignedAttributes);

            using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer = new CmsSigner(identifierType, signerCert);
                firstSigner.ComputeCounterSignature(signer);
            }

            Assert.Empty(firstSigner.CounterSignerInfos);
            Assert.Empty(firstSigner.UnsignedAttributes);

            SignerInfo firstSigner2 = cms.SignerInfos[0];

            Assert.Single(firstSigner2.CounterSignerInfos);
            Assert.Single(firstSigner2.UnsignedAttributes);

            SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];

            Assert.Equal(identifierType, counterSigner.SignerIdentifier.Type);

            // On .NET Framework there will be two attributes, because Windows emits the
            // content-type attribute even for counter-signers.
            int expectedCount = 1;

#if NETFRAMEWORK
            expectedCount = 2;
#endif
            Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count);
            Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value);

            Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate);
            Assert.Equal(2, cms.Certificates.Count);

            counterSigner.CheckSignature(true);
            firstSigner2.CheckSignature(true);
            cms.CheckSignature(true);
        }
Exemplo n.º 15
0
            public SignedData(ASN1 asn1)
            {
                if (asn1[0].Tag != 48 || asn1[0].Count < 4)
                {
                    throw new ArgumentException("Invalid SignedData");
                }
                if (asn1[0][0].Tag != 2)
                {
                    throw new ArgumentException("Invalid version");
                }
                version     = asn1[0][0].Value[0];
                contentInfo = new ContentInfo(asn1[0][2]);
                int num = 3;

                certs = new X509CertificateCollection();
                if (asn1[0][num].Tag == 160)
                {
                    for (int i = 0; i < asn1[0][num].Count; i++)
                    {
                        certs.Add(new X509Certificate(asn1[0][num][i].GetBytes()));
                    }
                    num++;
                }
                crls = new ArrayList();
                if (asn1[0][num].Tag == 161)
                {
                    for (int j = 0; j < asn1[0][num].Count; j++)
                    {
                        crls.Add(asn1[0][num][j].GetBytes());
                    }
                    num++;
                }
                if (asn1[0][num].Count > 0)
                {
                    signerInfo = new SignerInfo(asn1[0][num]);
                }
                else
                {
                    signerInfo = new SignerInfo();
                }
                if (signerInfo.HashName != null)
                {
                    HashName = OidToName(signerInfo.HashName);
                }
                mda = (signerInfo.AuthenticatedAttributes.Count > 0);
            }
Exemplo n.º 16
0
        private void AppendRowsCertificate()
        {
            //SignerInfo signerInfo=this._signatureResult.PKCS7Documents[this._requestDocumentIndex].SignersInfo[this._requestSignerIndex];
            SignerInfo      signerInfo = getSignerInfo(this._requestDocumentIndex, Request.QueryString["index"]);
            CertificateInfo certInfo   = signerInfo.CertificateInfo;

            TableRow row = this.CreateHeaderTableRow();

            row.Cells[0].Text = "Certificato";
            row = null;

            //Mev Firma1 < aggiunta info ente certificatore
            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Ente Certificatore:";
            row.Cells[2].Text = Utils.getEnteCertificatore(certInfo.IssuerName);
            row = null;
            //>
            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "S.N. certificato:";
            row.Cells[2].Text = certInfo.SerialNumber;
            row = null;

            //Mev Firma1 < posizionameto orizzontale delle info date dal - al
            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Valido dal:";
            row.Cells[2].Text = string.Format("{0}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Valido sino al: {1}", certInfo.ValidFromDate.ToLongDateString(), certInfo.ValidToDate.ToLongDateString());;
            row = null;
            //>

            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Algoritmo Firma Certificato:";
            row.Cells[2].Text = certInfo.SignatureAlgorithm;
            row = null;

            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Firmatario:";
            row.Cells[2].Text = this.GetItemValue(signerInfo.SubjectInfo.Cognome + " " + signerInfo.SubjectInfo.Nome);
            row = null;

            row = this.CreateStandardTableRow();
            row.Cells[0].Text = "Thumbprint Certificato:";
            row.Cells[2].Text = certInfo.ThumbPrint;
            row = null;

            certInfo = null;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Get timestamps from the signer info
        /// </summary>
        /// <param name="signer"></param>
        /// <returns></returns>
        private static IReadOnlyList <Timestamp> GetTimestamps(SignerInfo signer)
        {
            var authorUnsignedAttributes = signer.UnsignedAttributes;

            var timestampList = new List <Timestamp>();

            foreach (var attribute in authorUnsignedAttributes)
            {
                if (string.Equals(attribute.Oid.Value, Oids.SignatureTimeStampTokenAttributeOid, StringComparison.Ordinal))
                {
                    var timestampCms = new SignedCms();
                    timestampCms.Decode(attribute.Values[0].RawData);
                    timestampList.Add(new Timestamp(timestampCms));;
                }
            }
            return(timestampList);
        }
Exemplo n.º 18
0
        public static void AddFirstSigner_RSA(SubjectIdentifierType identifierType, bool detached)
        {
            ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
            SignedCms   cms         = new SignedCms(contentInfo, detached);

            using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer = new CmsSigner(identifierType, signerCert);
                cms.ComputeSignature(signer);
            }

            Assert.Same(contentInfo.Content, cms.ContentInfo.Content);
            Assert.Single(cms.SignerInfos);
            Assert.Single(cms.Certificates);

            int expectedVersion = identifierType == SubjectIdentifierType.SubjectKeyIdentifier ? 3 : 1;

            Assert.Equal(expectedVersion, cms.Version);

            SignerInfo firstSigner = cms.SignerInfos[0];

            Assert.Equal(identifierType, firstSigner.SignerIdentifier.Type);
            Assert.NotNull(firstSigner.Certificate);
            Assert.NotSame(cms.Certificates[0], firstSigner.Certificate);
            Assert.Equal(cms.Certificates[0], firstSigner.Certificate);

            cms.CheckSignature(true);
            byte[] encoded = cms.Encode();

            cms = new SignedCms();
            cms.Decode(encoded);
            Assert.Single(cms.SignerInfos);
            Assert.Single(cms.Certificates);
            Assert.Equal(expectedVersion, cms.Version);
            Assert.Equal(identifierType, cms.SignerInfos[0].SignerIdentifier.Type);
            Assert.Equal(firstSigner.Certificate, cms.SignerInfos[0].Certificate);

            if (detached)
            {
                Assert.Throws <CryptographicException>(() => cms.CheckSignature(true));
                cms = new SignedCms(contentInfo, detached);
                cms.Decode(encoded);
            }

            cms.CheckSignature(true);
        }
Exemplo n.º 19
0
        public static void RemoveSignature_MatchesSubjectKeyIdentifier()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPssDocument);
            Assert.Single(cms.SignerInfos);

            SignerInfo signerInfo = cms.SignerInfos[0];

            Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, signerInfo.SignerIdentifier.Type);

            int certCount = cms.Certificates.Count;

            cms.RemoveSignature(signerInfo);
            Assert.Empty(cms.SignerInfos);
            Assert.Equal(certCount, cms.Certificates.Count);
        }
Exemplo n.º 20
0
 private static void VerifySigningCertificate(
     SignedCms signedCms,
     SignerInfo signerInfo,
     SigningSpecifications signingSpecifications)
 {
     using (var certificates = SignatureUtility.GetCertificateChain(
                signedCms,
                signerInfo,
                signingSpecifications,
                Strings.PrimarySignatureFriendlyName))
     {
         if (certificates == null || certificates.Count == 0)
         {
             ThrowForInvalidPrimarySignature();
         }
     }
 }
Exemplo n.º 21
0
        /**
         * return the collection of signers that are associated with the
         * signatures for the message.
         */
        public SignerInformationStore GetSignerInfos()
        {
            if (signerInfoStore == null)
            {
                IList   signerInfos = new ArrayList();
                Asn1Set s           = signedData.SignerInfos;

                foreach (object obj in s)
                {
                    signerInfos.Add(new SignerInformation(SignerInfo.GetInstance(obj),
                                                          signedData.EncapContentInfo.ContentType, signedContent, null));
                }

                signerInfoStore = new SignerInformationStore(signerInfos);
            }

            return(signerInfoStore);
        }
Exemplo n.º 22
0
        /**
         * return the collection of signers that are associated with the
         * signatures for the message.
         * @throws CmsException
         */
        public SignerInformationStore GetSignerInfos()
        {
            if (_signerInfoStore == null)
            {
                IList       signerInfos = new ArrayList();
                IDictionary hashes      = new Hashtable();

                foreach (object digestKey in _digests.Keys)
                {
                    hashes[digestKey] = DigestUtilities.DoFinal(
                        (IDigest)_digests[digestKey]);
                }

                try
                {
                    Asn1SetParser    s = _signedData.GetSignerInfos();
                    IAsn1Convertible o;

                    while ((o = s.ReadObject()) != null)
                    {
                        SignerInfo info       = SignerInfo.GetInstance(o.ToAsn1Object());
                        string     digestName = Helper.GetDigestAlgName(
                            info.DigestAlgorithm.ObjectID.Id);

                        byte[] hash = (byte[])hashes[digestName];

                        signerInfos.Add(
                            new SignerInformation(
                                info,
                                new DerObjectIdentifier(_signedContent.ContentType),
                                null,
                                hash));
                    }
                }
                catch (IOException e)
                {
                    throw new CmsException("io exception: " + e.Message, e);
                }

                _signerInfoStore = new SignerInformationStore(signerInfos);
            }

            return(_signerInfoStore);
        }
Exemplo n.º 23
0
        internal SignerInformation(
            SignerInfo info,
            DerObjectIdentifier contentType,
            CmsProcessable content,
            IDigestCalculator digestCalculator)
        {
            this.info               = info;
            this.sid                = new SignerID();
            this.contentType        = contentType;
            this.isCounterSignature = contentType == null;

            try
            {
                SignerIdentifier s = info.SignerID;

                if (s.IsTagged)
                {
                    Asn1OctetString octs = Asn1OctetString.GetInstance(s.ID);

                    sid.SubjectKeyIdentifier = octs.GetEncoded();
                }
                else
                {
                    Asn1.Cms.IssuerAndSerialNumber iAnds =
                        Asn1.Cms.IssuerAndSerialNumber.GetInstance(s.ID);

                    sid.Issuer       = iAnds.Name;
                    sid.SerialNumber = iAnds.SerialNumber.Value;
                }
            }
            catch (IOException)
            {
                throw new ArgumentException("invalid sid in SignerInfo");
            }

            this.digestAlgorithm      = info.DigestAlgorithm;
            this.signedAttributeSet   = info.AuthenticatedAttributes;
            this.unsignedAttributeSet = info.UnauthenticatedAttributes;
            this.encryptionAlgorithm  = info.DigestEncryptionAlgorithm;
            this.signature            = info.EncryptedDigest.GetOctets();

            this.content          = content;
            this.digestCalculator = digestCalculator;
        }
Exemplo n.º 24
0
        private async Task CreateTimeStamp(SignedCms signedCms)
        {
            // See: https://www.glennwatson.net/posts/rfc-3161-signing

            const string timeStampAuthorityUri = "http://time.certum.pl/";

            byte[] nonce = new byte[8];
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(nonce);
            }

            SignerInfo newSignerInfo        = signedCms.SignerInfos[0];
            Rfc3161TimestampRequest?request = Rfc3161TimestampRequest.CreateFromSignerInfo(
                newSignerInfo,
                HashAlgorithmName.SHA256,
                requestSignerCertificates: true,
                nonce: nonce);

            using HttpClient client             = new HttpClient();
            using ReadOnlyMemoryContent content = new ReadOnlyMemoryContent(request.Encode());
            content.Headers.ContentType         = new MediaTypeHeaderValue("application/timestamp-query");

            using HttpResponseMessage? httpResponse = await client.PostAsync(timeStampAuthorityUri, content).ConfigureAwait(false);

            if (!httpResponse.IsSuccessStatusCode)
            {
                throw new CryptographicException($"There was a error from the timestamp authority. It responded with {httpResponse.StatusCode} {(int)httpResponse.StatusCode}: {httpResponse.Content}");
            }

            if (httpResponse.Content.Headers.ContentType.MediaType != "application/timestamp-reply")
            {
                throw new CryptographicException("The reply from the time stamp server was in a invalid format.");
            }

            byte[]? data = await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

            Rfc3161TimestampToken?timestampToken = request.ProcessResponse(data, out _);

            Oid signatureTimeStampOid = new Oid("1.2.840.113549.1.9.16.2.14");

            newSignerInfo.AddUnsignedAttribute(new AsnEncodedData(signatureTimeStampOid, timestampToken.AsSignedCms().Encode()));
        }
Exemplo n.º 25
0
        public static void RemoveCounterSignature_EncodedInSingleAttribute_ByIndex(int indexToRemove)
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPkcs1TwoCounterSignaturesInSingleAttribute);
            SignerInfo signerInfo = cms.SignerInfos[0];

            Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
            signerInfo.RemoveCounterSignature(indexToRemove);
            Assert.Equal(1, signerInfo.CounterSignerInfos.Count);

            cms.CheckSignature(true);

            byte[] encoded = cms.Encode();
            cms.Decode(encoded);

            Assert.Equal(1, cms.SignerInfos[0].CounterSignerInfos.Count);
            cms.CheckSignature(true);
        }
Exemplo n.º 26
0
        public X509Certificate2 Verify(bool skipCertValidation)
        {
            if (!this.IsSigned)
            {
                throw new Exception("Package is not signed");
            }

            IntegrityList computedIntegrityList = this.ComputeIntegrityList(out byte[] integrityListContent, out byte[] integrityListSignatureContent);
            IntegrityList embeddedIntegrityList = IntegrityList.FromByteArray(integrityListContent);

            SignerInfo signerInfo = CryptoUtils.VerifyDetachedCmsSignature(integrityListContent, integrityListSignatureContent, skipCertValidation);

            if (!computedIntegrityList.SequenceEqual(embeddedIntegrityList))
            {
                throw new InvalidSignatureException("Package content has been altered");
            }

            return(signerInfo.Certificate);
        }
Exemplo n.º 27
0
        public static void SignerInfo_AddRemoveUnsignedAttributeWithDetachtedSigner_Throws()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);

            // Detatch signer (and its counter signers)
            SignerInfo counterSigner = cms.SignerInfos[0].CounterSignerInfos[0];

            cms.RemoveSignature(0);

            // we shouldn't throw
            Assert.Equal(0, counterSigner.UnsignedAttributes.Count);

            AsnEncodedData attribute = CreateTimestampToken(1);

            Assert.Throws <CryptographicException>(() => counterSigner.AddUnsignedAttribute(attribute));
            Assert.Throws <CryptographicException>(() => counterSigner.RemoveUnsignedAttribute(attribute));
        }
Exemplo n.º 28
0
        internal static Signer FromSignerInfo(SignerInfo signerInfo)
        {
            DateTime?signingTime = null;
            var      attr        = signerInfo
                                   .SignedAttributes
                                   .Cast <CryptographicAttributeObject>()
                                   .Where(a => a.Oid.Value.Equals("1.2.840.113549.1.9.5", StringComparison.OrdinalIgnoreCase))
                                   .Select(a => new Pkcs9SigningTime(a.Values.Cast <AsnEncodedData>().First().RawData))
                                   .FirstOrDefault();

            if (attr != null)
            {
                signingTime = attr.SigningTime.ToUniversalTime();
            }

            return(new Signer(
                       signerInfo.Certificate.ComputePublicKeyIdentifier(),
                       signerInfo.Certificate,
                       signingTime));
        }
Exemplo n.º 29
0
 internal SignerInfoCollection(SignedCms signedCms)
 {
     uint num1 = 0U;
     uint num2 = (uint)Marshal.SizeOf(typeof(uint));
     SafeCryptMsgHandle cryptMsgHandle = signedCms.GetCryptMsgHandle();
     if (!CAPI.CAPISafe.CryptMsgGetParam(cryptMsgHandle, 5U, 0U, new IntPtr((void*)&num1), new IntPtr((void*)&num2)))
         throw new CryptographicException(Marshal.GetLastWin32Error());
     SignerInfo[] signerInfoArray = new SignerInfo[(IntPtr)num1];
     for (int index = 0; (long)index < (long)num1; ++index)
     {
         uint num3 = 0U;
         if (!CAPI.CAPISafe.CryptMsgGetParam(cryptMsgHandle, 6U, (uint)index, IntPtr.Zero, new IntPtr((void*)&num3)))
             throw new CryptographicException(Marshal.GetLastWin32Error());
         SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(0U, new IntPtr((long)num3));
         if (!CAPI.CAPISafe.CryptMsgGetParam(cryptMsgHandle, 6U, (uint)index, localAllocHandle, new IntPtr((void*)&num3)))
             throw new CryptographicException(Marshal.GetLastWin32Error());
         signerInfoArray[index] = new SignerInfo(signedCms, localAllocHandle);
     }
     this.m_signerInfos = signerInfoArray;
 }
Exemplo n.º 30
0
        /**
         * return the collection of signers that are associated with the
         * signatures for the message.
         * @throws CmsException
         */
        public SignerInformationStore GetSignerInfos()
        {
            if (_signerInfoStore == null)
            {
                PopulateCertCrlSets();

                IList       signerInfos = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
                IDictionary hashes      = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();

                foreach (object digestKey in _digests.Keys)
                {
                    hashes[digestKey] = DigestUtilities.DoFinal(
                        (IDigest)_digests[digestKey]);
                }

                try
                {
                    Asn1SetParser    s = _signedData.GetSignerInfos();
                    IAsn1Convertible o;

                    while ((o = s.ReadObject()) != null)
                    {
                        SignerInfo info       = SignerInfo.GetInstance(o.ToAsn1Object());
                        string     digestName = Helper.GetDigestAlgName(
                            info.DigestAlgorithm.Algorithm.Id);

                        byte[] hash = (byte[])hashes[digestName];

                        signerInfos.Add(new SignerInformation(info, _signedContentType, null, new BaseDigestCalculator(hash)));
                    }
                }
                catch (IOException e)
                {
                    throw new CmsException("io exception: " + e.Message, e);
                }

                _signerInfoStore = new SignerInformationStore(signerInfos);
            }

            return(_signerInfoStore);
        }
Exemplo n.º 31
0
        public static void CreateSignature_RsaPss(string digestOid, bool assignByConstructor)
        {
            ContentInfo content = new ContentInfo(new byte[] { 1, 2, 3 });
            SignedCms   cms     = new SignedCms(content);

            byte[] cmsBytes;

            using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer;

                if (assignByConstructor)
                {
                    signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert, null, RSASignaturePadding.Pss);
                }
                else
                {
                    signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);
                    signer.SignaturePadding = RSASignaturePadding.Pss;
                }

                signer.DigestAlgorithm = new Oid(digestOid, null);
                if (!SignatureSupport.SupportsRsaSha1Signatures &&
                    digestOid == Oids.Sha1)
                {
                    Assert.ThrowsAny <CryptographicException>(() => cms.ComputeSignature(signer));
                }
                else
                {
                    cms.ComputeSignature(signer);
                    cmsBytes = cms.Encode();
                    cms      = new SignedCms();
                    cms.Decode(cmsBytes);
                    cms.CheckSignature(true); // Assert.NoThrow
                    Assert.Single(cms.SignerInfos);

                    SignerInfo signerInfo = cms.SignerInfos[0];
                    Assert.Equal(Oids.RsaPss, signerInfo.SignatureAlgorithm.Value);
                }
            }
        }
Exemplo n.º 32
0
        /**
         * Return a signer information object with passed in SignerInformationStore representing counter
         * signatures attached as an unsigned attribute.
         *
         * @param signerInformation the signerInfo to be used as the basis.
         * @param counterSigners signer info objects carrying counter signature.
         * @return a copy of the original SignerInformationObject with the changed attributes.
         */
        public static SignerInformation AddCounterSigners(
            SignerInformation signerInformation,
            SignerInformationStore counterSigners)
        {
            // TODO Perform checks from RFC 3852 11.4

            SignerInfo sInfo = signerInformation.info;

            Asn1.Cms.AttributeTable unsignedAttr = signerInformation.UnsignedAttributes;
            Asn1EncodableVector     v;

            if (unsignedAttr != null)
            {
                v = unsignedAttr.ToAsn1EncodableVector();
            }
            else
            {
                v = new Asn1EncodableVector();
            }

            Asn1EncodableVector sigs = new Asn1EncodableVector();

            foreach (SignerInformation sigInf in counterSigners.GetSigners())
            {
                sigs.Add(sigInf.ToSignerInfo());
            }

            v.Add(new Asn1.Cms.Attribute(CmsAttributes.CounterSignature, new DerSet(sigs)));

            return(new SignerInformation(
                       new SignerInfo(
                           sInfo.SignerID,
                           sInfo.DigestAlgorithm,
                           sInfo.AuthenticatedAttributes,
                           sInfo.DigestEncryptionAlgorithm,
                           sInfo.EncryptedDigest,
                           new DerSet(v)),
                       signerInformation.contentType,
                       signerInformation.content,
                       null));
        }
Exemplo n.º 33
0
        public static void BuildFromSignerInfo()
        {
            ContentInfo content = new ContentInfo(new byte[] { 1, 2, 3, 4 });
            SignedCms   cms     = new SignedCms(content, false);

            using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signerCert);
                signer.SignedAttributes.Add(new Pkcs9SigningTime());
                cms.ComputeSignature(signer);
            }

            SignerInfo signerInfo = cms.SignerInfos[0];

            byte[] sig = signerInfo.GetSignature();

            Rfc3161TimestampRequest fromSigner = Rfc3161TimestampRequest.CreateFromSignerInfo(signerInfo, HashAlgorithmName.SHA256);
            Rfc3161TimestampRequest fromData   = Rfc3161TimestampRequest.CreateFromData(sig, HashAlgorithmName.SHA256);

            Assert.Equal(fromData.Encode().ByteArrayToHex(), fromSigner.Encode().ByteArrayToHex());
        }
Exemplo n.º 34
0
 internal SignerInfoCollection(SignedCms signedCms, SignerInfo signerInfo)
 {
     SignerInfo[] signerInfoArray1 = new SignerInfo[0];
     int length = 0;
     int num = 0;
     foreach (CryptographicAttributeObject cryptographicAttributeObject in signerInfo.UnsignedAttributes)
     {
         if (cryptographicAttributeObject.Oid.Value == "1.2.840.113549.1.9.6")
             length += cryptographicAttributeObject.Values.Count;
     }
     SignerInfo[] signerInfoArray2 = new SignerInfo[length];
     foreach (CryptographicAttributeObject cryptographicAttributeObject in signerInfo.UnsignedAttributes)
     {
         if (cryptographicAttributeObject.Oid.Value == "1.2.840.113549.1.9.6")
         {
             for (int index = 0; index < cryptographicAttributeObject.Values.Count; ++index)
             {
                 AsnEncodedData asnEncodedData = cryptographicAttributeObject.Values[index];
                 signerInfoArray2[num++] = new SignerInfo(signedCms, signerInfo, asnEncodedData.RawData);
             }
         }
     }
     this.m_signerInfos = signerInfoArray2;
 }
Exemplo n.º 35
0
			public SignedData () 
			{
				version = 1;
				contentInfo = new ContentInfo ();
				certs = new X509CertificateCollection ();
				crls = new ArrayList ();
				signerInfo = new SignerInfo ();
				mda = true;
				signed = false;
			}
 public void RemoveCounterSignature(SignerInfo counterSignerInfo)
 {
 }
Exemplo n.º 37
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.SignerInfoCollection.CopyTo(System.Security.Cryptography.Pkcs.SignerInfo[],System.Int32)"/> method copies the <see cref="T:System.Security.Cryptography.Pkcs.SignerInfoCollection"/> collection to a <see cref="T:System.Security.Cryptography.Pkcs.SignerInfo"/> array.
 /// </summary>
 /// <param name="array">An array of <see cref="T:System.Security.Cryptography.Pkcs.SignerInfo"/> objects where the <see cref="T:System.Security.Cryptography.Pkcs.SignerInfoCollection"/> collection is to be copied.</param><param name="index">The zero-based index in <paramref name="array"/> where the <see cref="T:System.Security.Cryptography.Pkcs.SignerInfoCollection"/> collection is copied.</param><exception cref="T:System.ArgumentException">One of the arguments provided to a method was not valid.</exception><exception cref="T:System.ArgumentNullException">A null reference was passed to a method that does not accept it as a valid argument. </exception><exception cref="T:System.ArgumentOutOfRangeException">The value of an argument was outside the allowable range of values as defined by the called method.</exception>
 public void CopyTo(SignerInfo[] array, int index)
 {
     this.CopyTo((Array)array, index);
 }
Exemplo n.º 38
0
			public SignedData (ASN1 asn1) 
			{
				if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 4))
					throw new ArgumentException ("Invalid SignedData");

				if (asn1[0][0].Tag != 0x02)
					throw new ArgumentException ("Invalid version");
				version = asn1[0][0].Value[0];

				contentInfo = new ContentInfo (asn1[0][2]);

				int n = 3;
				certs = new X509CertificateCollection ();
				if (asn1[0][n].Tag == 0xA0) {
					for (int i=0; i < asn1[0][n].Count; i++)
						certs.Add (new X509Certificate (asn1[0][n][i].GetBytes ()));
					n++;
				}

				crls = new ArrayList ();
				if (asn1[0][n].Tag == 0xA1) {
					for (int i=0; i < asn1[0][n].Count; i++)
						crls.Add (asn1[0][n][i].GetBytes ());
					n++;
				}

				if (asn1[0][n].Count > 0)
					signerInfo = new SignerInfo (asn1[0][n]);
				else
					signerInfo = new SignerInfo ();

				// Exchange hash algorithm Oid from SignerInfo
				if (signerInfo.HashName != null) {
					HashName = OidToName(signerInfo.HashName);
				}
				
				// Check if SignerInfo has authenticated attributes
				mda = (signerInfo.AuthenticatedAttributes.Count > 0);
			}
 public void CopyTo(SignerInfo[] array, int index)
 {
 }
Exemplo n.º 40
0
 public void RemoveCounterSignature(SignerInfo counterSignerInfo)
 {
     if (this.m_parentSignerInfo != null)
         throw new CryptographicException(-2147483647);
     if (counterSignerInfo == null)
         throw new ArgumentNullException("counterSignerInfo");
     foreach (CryptographicAttributeObject cryptographicAttributeObject in this.UnsignedAttributes)
     {
         if (string.Compare(cryptographicAttributeObject.Oid.Value, "1.2.840.113549.1.9.6", StringComparison.OrdinalIgnoreCase) == 0)
         {
             for (int childIndex = 0; childIndex < cryptographicAttributeObject.Values.Count; ++childIndex)
             {
                 SignerInfo signerInfo = new SignerInfo(this.m_signedCms, this.m_parentSignerInfo, cryptographicAttributeObject.Values[childIndex].RawData);
                 if (counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber && signerInfo.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)
                 {
                     X509IssuerSerial x509IssuerSerial1 = (X509IssuerSerial)counterSignerInfo.SignerIdentifier.Value;
                     X509IssuerSerial x509IssuerSerial2 = (X509IssuerSerial)signerInfo.SignerIdentifier.Value;
                     if (string.Compare(x509IssuerSerial1.IssuerName, x509IssuerSerial2.IssuerName, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(x509IssuerSerial1.SerialNumber, x509IssuerSerial2.SerialNumber, StringComparison.OrdinalIgnoreCase) == 0)
                     {
                         this.RemoveCounterSignature(PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0), childIndex);
                         return;
                     }
                 }
                 else if (counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier && signerInfo.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier && string.Compare(counterSignerInfo.SignerIdentifier.Value as string, signerInfo.SignerIdentifier.Value as string, StringComparison.OrdinalIgnoreCase) == 0)
                 {
                     this.RemoveCounterSignature(PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0), childIndex);
                     return;
                 }
             }
         }
     }
     throw new CryptographicException(-2146889714);
 }
 public void RemoveSignature(SignerInfo signerInfo)
 {
 }
Exemplo n.º 42
0
 public void RemoveSignature(SignerInfo signerInfo)
 {
     if (signerInfo == null)
         throw new ArgumentNullException("signerInfo");
     this.RemoveSignature(PkcsUtils.GetSignerIndex(this.m_safeCryptMsgHandle, signerInfo, 0));
 }