コード例 #1
0
 internal SignerInfo(SignedCms signedCms, System.Security.Cryptography.SafeLocalAllocHandle pbCmsgSignerInfo)
 {
     this.m_signedCms = signedCms;
     this.m_parentSignerInfo = null;
     this.m_encodedSignerInfo = null;
     this.m_pbCmsgSignerInfo = pbCmsgSignerInfo;
     this.m_cmsgSignerInfo = (System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO));
 }
コード例 #2
0
		public void CopyTo (SignerInfo[] array, int index)
		{
			if (array == null)
				throw new ArgumentNullException ("array");
			if ((index < 0) || (index >= array.Length))
				throw new ArgumentOutOfRangeException ("index");

			_list.CopyTo (array, index);
		}
コード例 #3
0
        internal SignerInfo (SignedCms signedCms, SafeLocalAllocHandle pbCmsgSignerInfo) {
            // Sanity check.
            Debug.Assert(signedCms != null && pbCmsgSignerInfo != null && !pbCmsgSignerInfo.IsInvalid);

            m_signedCms = signedCms;
            m_parentSignerInfo = null;
            m_encodedSignerInfo = null;
            m_pbCmsgSignerInfo = pbCmsgSignerInfo;
            m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));
        }
コード例 #4
0
ファイル: MessageSignature.cs プロジェクト: DM-TOR/nhin-d
 /// <summary>
 /// Create a signature from <see cref="SignerInfo"/>
 /// </summary>
 /// <param name="signer">The <see cref="SignerInfo"/> for this signature</param>
 /// <param name="usesOrgCertificate"><c>true</c> if the signature is at an organizational,
 /// not an individual level, <c>false</c> if an individual signature.</param>
 public MessageSignature(SignerInfo signer, bool usesOrgCertificate)
 {
     if (signer == null)
     {
         throw new ArgumentNullException("signer");
     }            
     
     m_signer = signer;
     m_signatureValid = null;
     m_usesOrgCertificate = usesOrgCertificate;
     m_thumbprintVerified = null;
 }    
コード例 #5
0
        public bool VerifySignatureForSignerInfo(
            SignerInfo signerInfo,
            out X509Certificate2 signerCertificate,
            X509Certificate2Collection extraCandidates = null)
        {
            if (signerInfo == null)
            {
                throw new ArgumentNullException(nameof(signerInfo));
            }

            return(VerifySignatureForData(
                       signerInfo.GetSignatureMemory().Span,
                       out signerCertificate,
                       extraCandidates));
        }
コード例 #6
0
        public void RemoveSignature(SignerInfo signerInfo)
        {
            if (signerInfo == null)
            {
                throw new ArgumentNullException(nameof(signerInfo));
            }

            int idx = SignerInfos.FindIndexForSigner(signerInfo);

            if (idx < 0)
            {
                throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
            }

            RemoveSignature(idx);
        }
コード例 #7
0
        public void RemoveCounterSignature(SignerInfo counterSignerInfo)
        {
            if (this.m_parentSignerInfo != null)
            {
                throw new CryptographicException(-2147483647);
            }
            if (counterSignerInfo == null)
            {
                throw new ArgumentNullException("counterSignerInfo");
            }
            CryptographicAttributeObjectEnumerator enumerator = this.UnsignedAttributes.GetEnumerator();

            while (enumerator.MoveNext())
            {
                CryptographicAttributeObject current = enumerator.Current;
                if (string.Compare(current.Oid.Value, "1.2.840.113549.1.9.6", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    for (int i = 0; i < current.Values.Count; i++)
                    {
                        AsnEncodedData data = current.Values[i];
                        SignerInfo     info = new SignerInfo(this.m_signedCms, this.m_parentSignerInfo, data.RawData);
                        if ((counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber) && (info.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber))
                        {
                            X509IssuerSerial serial  = (X509IssuerSerial)counterSignerInfo.SignerIdentifier.Value;
                            X509IssuerSerial serial2 = (X509IssuerSerial)info.SignerIdentifier.Value;
                            if ((string.Compare(serial.IssuerName, serial2.IssuerName, StringComparison.OrdinalIgnoreCase) != 0) || (string.Compare(serial.SerialNumber, serial2.SerialNumber, StringComparison.OrdinalIgnoreCase) != 0))
                            {
                                continue;
                            }
                            this.RemoveCounterSignature(PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0), i);
                            return;
                        }
                        if ((counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier) && (info.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier))
                        {
                            string strA = counterSignerInfo.SignerIdentifier.Value as string;
                            string strB = info.SignerIdentifier.Value as string;
                            if (string.Compare(strA, strB, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                this.RemoveCounterSignature(PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0), i);
                                return;
                            }
                        }
                    }
                }
            }
            throw new CryptographicException(-2146889714);
        }
コード例 #8
0
        private static void CheckHashes(SignerInfoCollection signers)
        {
            if ((signers == null) || (signers.Count < 1))
            {
                throw new CryptographicException(-2146885618);
            }
            SignerInfoEnumerator enumerator = signers.GetEnumerator();

            while (enumerator.MoveNext())
            {
                SignerInfo current = enumerator.Current;
                if (current.SignerIdentifier.Type == SubjectIdentifierType.NoSignature)
                {
                    current.CheckHash();
                }
            }
        }
コード例 #9
0
 internal unsafe SignerInfo(SignedCms signedCms, SignerInfo parentSignerInfo, byte[] encodedSignerInfo)
 {
     uint cbDecodedValue = 0;
     System.Security.Cryptography.SafeLocalAllocHandle invalidHandle = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle;
     fixed (byte* numRef = encodedSignerInfo)
     {
         if (!System.Security.Cryptography.CAPI.DecodeObject(new IntPtr(500L), new IntPtr((void*) numRef), (uint) encodedSignerInfo.Length, out invalidHandle, out cbDecodedValue))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
     }
     this.m_signedCms = signedCms;
     this.m_parentSignerInfo = parentSignerInfo;
     this.m_encodedSignerInfo = (byte[]) encodedSignerInfo.Clone();
     this.m_pbCmsgSignerInfo = invalidHandle;
     this.m_cmsgSignerInfo = (System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO));
 }
コード例 #10
0
        private static void CheckSignatures(SignerInfoCollection signers, X509Certificate2Collection extraStore, bool verifySignatureOnly)
        {
            if ((signers == null) || (signers.Count < 1))
            {
                throw new CryptographicException(-2146885618);
            }
            SignerInfoEnumerator enumerator = signers.GetEnumerator();

            while (enumerator.MoveNext())
            {
                SignerInfo current = enumerator.Current;
                current.CheckSignature(extraStore, verifySignatureOnly);
                if (current.CounterSignerInfos.Count > 0)
                {
                    CheckSignatures(current.CounterSignerInfos, extraStore, verifySignatureOnly);
                }
            }
        }
コード例 #11
0
        private static int FindIndexForSigner(SignerInfo[] signerInfos, SignerInfo signer)
        {
            Debug.Assert(signer != null);
            SubjectIdentifier id = signer.SignerIdentifier;

            for (int i = 0; i < signerInfos.Length; i++)
            {
                SignerInfo        current   = signerInfos[i];
                SubjectIdentifier currentId = current.SignerIdentifier;

                if (id.IsEquivalentTo(currentId))
                {
                    return(i);
                }
            }

            return(-1);
        }
コード例 #12
0
        internal unsafe SignerInfoCollection(SignedCms signedCms)
        {
            uint dwSigners = 0;
            uint cbCount   = (uint)Marshal.SizeOf(typeof(uint));
            SafeCryptMsgHandle safeCryptMsgHandle = signedCms.GetCryptMsgHandle();

            if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                CAPI.CMSG_SIGNER_COUNT_PARAM,
                                                0,
                                                new IntPtr(&dwSigners),
                                                new IntPtr(&cbCount)))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            SignerInfo[] signerInfos = new SignerInfo[dwSigners];
            for (int index = 0; index < dwSigners; index++)
            {
                uint cbCmsgSignerInfo = 0;
                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                    CAPI.CMSG_SIGNER_INFO_PARAM,
                                                    (uint)index,
                                                    IntPtr.Zero,
                                                    new IntPtr(&cbCmsgSignerInfo)))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }

                SafeLocalAllocHandle pbCmsgSignerInfo = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbCmsgSignerInfo));

                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                    CAPI.CMSG_SIGNER_INFO_PARAM,
                                                    (uint)index,
                                                    pbCmsgSignerInfo,
                                                    new IntPtr(&cbCmsgSignerInfo)))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }

                signerInfos[index] = new SignerInfo(signedCms, pbCmsgSignerInfo);
            }

            m_signerInfos = signerInfos;
        }
コード例 #13
0
        internal unsafe SignerInfo(SignedCms signedCms, SignerInfo parentSignerInfo, byte[] encodedSignerInfo)
        {
            uint cbDecodedValue = 0;

            System.Security.Cryptography.SafeLocalAllocHandle invalidHandle = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle;
            fixed(byte *numRef = encodedSignerInfo)
            {
                if (!System.Security.Cryptography.CAPI.DecodeObject(new IntPtr(500L), new IntPtr((void *)numRef), (uint)encodedSignerInfo.Length, out invalidHandle, out cbDecodedValue))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }

            this.m_signedCms         = signedCms;
            this.m_parentSignerInfo  = parentSignerInfo;
            this.m_encodedSignerInfo = (byte[])encodedSignerInfo.Clone();
            this.m_pbCmsgSignerInfo  = invalidHandle;
            this.m_cmsgSignerInfo    = (System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO));
        }
コード例 #14
0
ファイル: Signer.cs プロジェクト: hishamco/Signing
        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);
        }
コード例 #15
0
        public static Pkcs8PrivateKeyInfo Decode(
            ReadOnlyMemory <byte> source,
            out int bytesRead,
            bool skipCopy = false)
        {
            if (!skipCopy)
            {
                AsnReader reader = new AsnReader(source, AsnEncodingRules.BER);
                source = reader.GetEncodedValue().ToArray();
            }

            PrivateKeyInfoAsn privateKeyInfo =
                AsnSerializer.Deserialize <PrivateKeyInfoAsn>(source, AsnEncodingRules.BER, out bytesRead);

            return(new Pkcs8PrivateKeyInfo(
                       privateKeyInfo.PrivateKeyAlgorithm.Algorithm,
                       privateKeyInfo.PrivateKeyAlgorithm.Parameters,
                       privateKeyInfo.PrivateKey,
                       SignerInfo.MakeAttributeCollection(privateKeyInfo.Attributes)));
        }
コード例 #16
0
        public void ComputeCounterSignature(CmsSigner signer)
        {
            if (_parentSignerInfo != null)
            {
                throw new CryptographicException(SR.Cryptography_Cms_NoCounterCounterSigner);
            }
            if (signer == null)
            {
                throw new ArgumentNullException(nameof(signer));
            }

            signer.CheckCertificateValue();

            int myIdx = _document.SignerInfos.FindIndexForSigner(this);

            if (myIdx < 0)
            {
                throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
            }

            // Make sure that we're using the most up-to-date version of this that we can.
            SignerInfo effectiveThis = _document.SignerInfos[myIdx];
            X509Certificate2Collection chain;
            SignerInfoAsn newSignerInfo = signer.Sign(effectiveThis._signature, null, false, out chain);

            AttributeAsn newUnsignedAttr;

            using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
            {
                writer.PushSetOf();
                AsnSerializer.Serialize(newSignerInfo, writer);
                writer.PopSetOf();

                newUnsignedAttr = new AttributeAsn
                {
                    AttrType   = new Oid(Oids.CounterSigner, Oids.CounterSigner),
                    AttrValues = writer.Encode(),
                };
            }

            ref SignedDataAsn signedData = ref _document.GetRawData();
コード例 #17
0
        public static Pkcs8PrivateKeyInfo Decode(
            ReadOnlyMemory <byte> source,
            out int bytesRead,
            bool skipCopy = false)
        {
            AsnValueReader reader = new AsnValueReader(source.Span, AsnEncodingRules.BER);
            // By using the default/empty ReadOnlyMemory value, the Decode method will have to
            // make copies of the data when assigning ReadOnlyMemory fields.
            ReadOnlyMemory <byte> rebind = skipCopy ? source : default;

            int localRead = reader.PeekEncodedValue().Length;

            PrivateKeyInfoAsn.Decode(ref reader, rebind, out PrivateKeyInfoAsn privateKeyInfo);
            bytesRead = localRead;

            return(new Pkcs8PrivateKeyInfo(
                       privateKeyInfo.PrivateKeyAlgorithm.Algorithm,
                       privateKeyInfo.PrivateKeyAlgorithm.Parameters,
                       privateKeyInfo.PrivateKey,
                       SignerInfo.MakeAttributeCollection(privateKeyInfo.Attributes)));
        }
コード例 #18
0
        internal unsafe SignerInfo (SignedCms signedCms, SignerInfo parentSignerInfo, byte[] encodedSignerInfo) {
            // Sanity check.
            Debug.Assert(signedCms != null && encodedSignerInfo != null && encodedSignerInfo.Length > 0);

            uint cbCmsgSignerInfo = 0;
            SafeLocalAllocHandle pbCmsgSignerInfo = SafeLocalAllocHandle.InvalidHandle;

            fixed (byte * pEncodedSignerInfo = &encodedSignerInfo[0]) {
                if (!CAPI.DecodeObject(new IntPtr(CAPI.PKCS7_SIGNER_INFO),
                                       new IntPtr(pEncodedSignerInfo),
                                       (uint) encodedSignerInfo.Length,
                                       out pbCmsgSignerInfo,
                                       out cbCmsgSignerInfo))
                    throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            m_signedCms = signedCms;
            m_parentSignerInfo = parentSignerInfo;
            m_encodedSignerInfo = (byte[]) encodedSignerInfo.Clone();
            m_pbCmsgSignerInfo = pbCmsgSignerInfo;
            m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));
        }
コード例 #19
0
        public static Pkcs8PrivateKeyInfo Decode(
            ReadOnlyMemory <byte> source,
            out int bytesRead,
            bool skipCopy = false)
        {
            AsnReader reader = new AsnReader(source, AsnEncodingRules.BER);

            if (!skipCopy)
            {
                reader = new AsnReader(reader.ReadEncodedValue().ToArray(), AsnEncodingRules.BER);
            }

            int localRead = reader.PeekEncodedValue().Length;

            PrivateKeyInfoAsn.Decode(reader, out PrivateKeyInfoAsn privateKeyInfo);
            bytesRead = localRead;

            return(new Pkcs8PrivateKeyInfo(
                       privateKeyInfo.PrivateKeyAlgorithm.Algorithm,
                       privateKeyInfo.PrivateKeyAlgorithm.Parameters,
                       privateKeyInfo.PrivateKey,
                       SignerInfo.MakeAttributeCollection(privateKeyInfo.Attributes)));
        }
コード例 #20
0
 internal int FindIndexForSigner(SignerInfo signer)
 {
     return(FindIndexForSigner(_signerInfos, signer));
 }
コード例 #21
0
ファイル: SignedPkcs7.cs プロジェクト: JianwenSun/cc
        public void RemoveSignature (SignerInfo signerInfo) {
            if (signerInfo == null)
                throw new ArgumentNullException("signerInfo");

            RemoveSignature(PkcsUtils.GetSignerIndex(m_safeCryptMsgHandle, signerInfo, 0));
        }
コード例 #22
0
        internal unsafe SignerInfoCollection (SignedCms signedCms) {
            uint dwSigners = 0;
            uint cbCount = (uint) Marshal.SizeOf(typeof(uint));
            SafeCryptMsgHandle safeCryptMsgHandle = signedCms.GetCryptMsgHandle();

            if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                CAPI.CMSG_SIGNER_COUNT_PARAM,
                                                0,
                                                new IntPtr(&dwSigners),
                                                new IntPtr(&cbCount)))
                throw new CryptographicException(Marshal.GetLastWin32Error());

            SignerInfo[] signerInfos = new SignerInfo[dwSigners];
            for (int index = 0; index < dwSigners; index++) {
                uint cbCmsgSignerInfo = 0;
                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                    CAPI.CMSG_SIGNER_INFO_PARAM,
                                                    (uint)index,
                                                    IntPtr.Zero,
                                                    new IntPtr(&cbCmsgSignerInfo)))
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                SafeLocalAllocHandle pbCmsgSignerInfo = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbCmsgSignerInfo));

                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                    CAPI.CMSG_SIGNER_INFO_PARAM,
                                                    (uint)index,
                                                    pbCmsgSignerInfo,
                                                    new IntPtr(&cbCmsgSignerInfo)))
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                signerInfos[index] = new SignerInfo(signedCms, pbCmsgSignerInfo);
            }

            m_signerInfos = signerInfos;
        }
コード例 #23
0
 internal static unsafe int GetSignerIndex(System.Security.Cryptography.SafeCryptMsgHandle safeCrytpMsgHandle, SignerInfo signerInfo, int startIndex)
 {
     uint num = 0;
     uint num2 = (uint) Marshal.SizeOf(typeof(uint));
     if (!System.Security.Cryptography.CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle, 5, 0, new IntPtr((void*) &num), new IntPtr((void*) &num2)))
     {
         checkErr(Marshal.GetLastWin32Error());
     }
     for (int i = startIndex; i < num; i++)
     {
         uint num4 = 0;
         if (!System.Security.Cryptography.CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle, 6, (uint) i, IntPtr.Zero, new IntPtr((void*) &num4)))
         {
             checkErr(Marshal.GetLastWin32Error());
         }
         if (num4 > 0)
         {
             System.Security.Cryptography.SafeLocalAllocHandle pvData = System.Security.Cryptography.CAPI.LocalAlloc(0, new IntPtr((long) num4));
             if (!System.Security.Cryptography.CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle, 6, (uint) i, pvData, new IntPtr((void*) &num4)))
             {
                 checkErr(Marshal.GetLastWin32Error());
             }
             System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO cmsgSignerInfo = signerInfo.GetCmsgSignerInfo();
             System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO cmsg_signer_info2 = (System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pvData.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO));
             if (System.Security.Cryptography.X509Certificates.X509Utils.MemEqual((byte*) cmsgSignerInfo.Issuer.pbData, cmsgSignerInfo.Issuer.cbData, (byte*) cmsg_signer_info2.Issuer.pbData, cmsg_signer_info2.Issuer.cbData) && System.Security.Cryptography.X509Certificates.X509Utils.MemEqual((byte*) cmsgSignerInfo.SerialNumber.pbData, cmsgSignerInfo.SerialNumber.cbData, (byte*) cmsg_signer_info2.SerialNumber.pbData, cmsg_signer_info2.SerialNumber.cbData))
             {
                 return i;
             }
             pvData.Dispose();
         }
     }
     throw new CryptographicException(-2146889714);
 }
コード例 #24
0
        private static List <Pkcs12SafeBag> ReadBags(ReadOnlyMemory <byte> serialized)
        {
            SafeBagAsn[] serializedBags =
                AsnSerializer.Deserialize <SafeBagAsn[]>(serialized, AsnEncodingRules.BER);

            if (serializedBags.Length == 0)
            {
                return(new List <Pkcs12SafeBag>(0));
            }

            List <Pkcs12SafeBag> bags = new List <Pkcs12SafeBag>(serializedBags.Length);

            for (int i = 0; i < serializedBags.Length; i++)
            {
                ReadOnlyMemory <byte> bagValue = serializedBags[i].BagValue;
                Pkcs12SafeBag         bag      = null;

                try
                {
                    switch (serializedBags[i].BagId)
                    {
                    case Oids.Pkcs12KeyBag:
                        bag = new Pkcs12KeyBag(bagValue);
                        break;

                    case Oids.Pkcs12ShroudedKeyBag:
                        bag = new Pkcs12ShroudedKeyBag(bagValue);
                        break;

                    case Oids.Pkcs12CertBag:
                        bag = Pkcs12CertBag.DecodeValue(bagValue);
                        break;

                    case Oids.Pkcs12CrlBag:
                        // Known, but no first-class support currently.
                        break;

                    case Oids.Pkcs12SecretBag:
                        bag = Pkcs12SecretBag.DecodeValue(bagValue);
                        break;

                    case Oids.Pkcs12SafeContentsBag:
                        bag = Pkcs12SafeContentsBag.Decode(bagValue);
                        break;
                    }
                }
                catch (CryptographicException)
                {
                }

                if (bag == null)
                {
                    bag = new Pkcs12SafeBag.UnknownBag(serializedBags[i].BagId, bagValue);
                }

                bag.Attributes = SignerInfo.MakeAttributeCollection(serializedBags[i].BagAttributes);
                bags.Add(bag);
            }

            return(bags);
        }
コード例 #25
0
        internal SignerInfoCollection (SignedCms signedCms, SignerInfo signerInfo) {
            SignerInfo[] signerInfos = new SignerInfo[0];

            int count = 0;
            int index = 0;

            foreach (CryptographicAttributeObject attribute in signerInfo.UnsignedAttributes) {
                if (attribute.Oid.Value == CAPI.szOID_RSA_counterSign) {
                    count += attribute.Values.Count;
                }
            }

            signerInfos = new SignerInfo[count];

            foreach (CryptographicAttributeObject attribute in signerInfo.UnsignedAttributes) {
                if (attribute.Oid.Value == CAPI.szOID_RSA_counterSign) {
                    for (int i = 0; i < attribute.Values.Count; i++) {
                        AsnEncodedData encodedSignerInfo = (AsnEncodedData) attribute.Values[i];
                        signerInfos[index++] = new SignerInfo(signedCms, signerInfo, encodedSignerInfo.RawData);
                    }
                }
            }

            m_signerInfos = signerInfos;
        }
コード例 #26
0
 public static Rfc3161TimestampRequest CreateFromSignerInfo(SignerInfo signerInfo, HashAlgorithmName hashAlgorithm, Oid requestedPolicyId = null, ReadOnlyMemory <byte>?nonce = null, bool requestSignerCertificates = false, X509ExtensionCollection extensions = null) => throw null;
コード例 #27
0
 public void CopyTo(SignerInfo[] array, int index) {
     ((ICollection)this).CopyTo(array, index);
 }
コード例 #28
0
		public void CopyTo_SignerInfoInt_Zero ()
		{
			SignerInfo[] sis = new SignerInfo[1];
			SignerInfoCollection sic = GetCollection ();
			sic.CopyTo (sis, 0);
		}
コード例 #29
0
 /// <param name="signerInfo" />
 /// <param name="hashAlgorithm" />
 /// <param name="requestedPolicyId" />
 /// <param name="nonce" />
 /// <param name="requestSignerCertificates" />
 /// <param name="extensions" />
 public static Rfc3161TimestampRequest CreateFromSignerInfo(SignerInfo signerInfo, HashAlgorithmName hashAlgorithm, Oid requestedPolicyId = null, ReadOnlyMemory <byte>?nonce = default(ReadOnlyMemory <byte>?), bool requestSignerCertificates = false, X509ExtensionCollection extensions = null)
 {
     throw new PlatformNotSupportedException();
 }
コード例 #30
0
		public void CopyTo_SignerInfoInt_MinusOne ()
		{
			SignerInfo[] sis = new SignerInfo[1];
			SignerInfoCollection sic = GetCollection ();
			sic.CopyTo (sis, -1);
		}
コード例 #31
0
        public void RemoveCounterSignature (SignerInfo counterSignerInfo) {
            // We only support one level of counter signing.
            if (m_parentSignerInfo != null)
                throw new CryptographicException(CAPI.E_NOTIMPL);
            if (counterSignerInfo == null)
                throw new ArgumentNullException("counterSignerInfo");

            foreach (CryptographicAttributeObject attribute in UnsignedAttributes) {
                if (String.Compare(attribute.Oid.Value, CAPI.szOID_RSA_counterSign, StringComparison.OrdinalIgnoreCase) == 0) {
                    for (int index = 0; index < attribute.Values.Count; index++) {
                        AsnEncodedData encodedCounterSignature = (AsnEncodedData) attribute.Values[index];
                        SignerInfo counterSignerInfo2 = new SignerInfo(m_signedCms, m_parentSignerInfo, encodedCounterSignature.RawData);

                        if ((counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber) &&
                            (counterSignerInfo2.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)) {
                            X509IssuerSerial issuerSerial1 = (X509IssuerSerial) counterSignerInfo.SignerIdentifier.Value;
                            X509IssuerSerial issuerSerial2 = (X509IssuerSerial) counterSignerInfo2.SignerIdentifier.Value;

                            if ((String.Compare(issuerSerial1.IssuerName, issuerSerial2.IssuerName, StringComparison.OrdinalIgnoreCase) == 0) &&
                                (String.Compare(issuerSerial1.SerialNumber, issuerSerial2.SerialNumber, StringComparison.OrdinalIgnoreCase) == 0)) {
                                RemoveCounterSignature(PkcsUtils.GetSignerIndex(m_signedCms.GetCryptMsgHandle(), this, 0), index);
                                return;
                            }
                        }
                        else if ((counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier) &&
                                 (counterSignerInfo2.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier)) {
                            string keyIdentifier1 = counterSignerInfo.SignerIdentifier.Value as string;
                            string keyIdentifier2 = counterSignerInfo2.SignerIdentifier.Value as string;

                            if (String.Compare(keyIdentifier1, keyIdentifier2, StringComparison.OrdinalIgnoreCase) == 0) {
                                RemoveCounterSignature(PkcsUtils.GetSignerIndex(m_signedCms.GetCryptMsgHandle(), this, 0), index);
                                return;
                            }
                        }
                    }
                }
            }

            throw new CryptographicException(CAPI.CRYPT_E_SIGNER_NOT_FOUND);
        }
コード例 #32
0
		// methods

		internal void Add (SignerInfo signer) 
		{
			_list.Add (signer);
		}
コード例 #33
0
ファイル: PkcsUtils.cs プロジェクト: JianwenSun/cc
        internal static unsafe int GetSignerIndex (SafeCryptMsgHandle safeCrytpMsgHandle, SignerInfo signerInfo, int startIndex) {
            uint dwSigners = 0;
            uint cbCount = (uint) Marshal.SizeOf(typeof(uint));

            if (!CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle,
                                                CAPI.CMSG_SIGNER_COUNT_PARAM,
                                                0,
                                                new IntPtr(&dwSigners),
                                                new IntPtr(&cbCount)))
                checkErr(Marshal.GetLastWin32Error());

            for (int index = startIndex; index < (int) dwSigners; index++) {
                uint cbCmsgSignerInfo = 0;

                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle,
                                                    CAPI.CMSG_SIGNER_INFO_PARAM,
                                                    (uint)index,
                                                    IntPtr.Zero,
                                                    new IntPtr(&cbCmsgSignerInfo)))
                    checkErr(Marshal.GetLastWin32Error());

                if (cbCmsgSignerInfo > 0) {
                    SafeLocalAllocHandle pbCmsgSignerInfo = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbCmsgSignerInfo));

                    if (!CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle,
                                                        CAPI.CMSG_SIGNER_INFO_PARAM,
                                                        (uint)index,
                                                        pbCmsgSignerInfo,
                                                        new IntPtr(&cbCmsgSignerInfo)))
                        checkErr(Marshal.GetLastWin32Error());

                    CAPI.CMSG_SIGNER_INFO cmsgSignerInfo1 = signerInfo.GetCmsgSignerInfo();
                    CAPI.CMSG_SIGNER_INFO cmsgSignerInfo2 = (CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));

                    if (X509Utils.MemEqual((byte *) cmsgSignerInfo1.Issuer.pbData,
                                  cmsgSignerInfo1.Issuer.cbData,
                                  (byte *) cmsgSignerInfo2.Issuer.pbData,
                                  cmsgSignerInfo2.Issuer.cbData) &&
                        X509Utils.MemEqual((byte *) cmsgSignerInfo1.SerialNumber.pbData,
                                  cmsgSignerInfo1.SerialNumber.cbData,
                                  (byte *) cmsgSignerInfo2.SerialNumber.pbData,
                                  cmsgSignerInfo2.SerialNumber.cbData)) {
                        return index; // Signer's index is found.
                    }

                    // Keep alive.
                    pbCmsgSignerInfo.Dispose();
                }
            }

            throw new CryptographicException(CAPI.CRYPT_E_SIGNER_NOT_FOUND);
        }
コード例 #34
0
 public void RemoveSignature(SignerInfo signerInfo)
 {
 }
コード例 #35
0
 /// <param name="signerInfo" />
 /// <param name="signerCertificate" />
 /// <param name="extraCandidates" />
 public bool VerifySignatureForSignerInfo(SignerInfo signerInfo, out X509Certificate2 signerCertificate, X509Certificate2Collection extraCandidates = null)
 {
     throw new PlatformNotSupportedException();
 }
コード例 #36
0
        private static List <Pkcs12SafeBag> ReadBags(ReadOnlyMemory <byte> serialized)
        {
            List <SafeBagAsn> serializedBags = new List <SafeBagAsn>();
            AsnReader         reader         = new AsnReader(serialized, AsnEncodingRules.BER);
            AsnReader         sequenceReader = reader.ReadSequence();

            reader.ThrowIfNotEmpty();
            while (sequenceReader.HasData)
            {
                SafeBagAsn.Decode(sequenceReader, out SafeBagAsn serializedBag);
                serializedBags.Add(serializedBag);
            }

            if (serializedBags.Count == 0)
            {
                return(new List <Pkcs12SafeBag>(0));
            }

            List <Pkcs12SafeBag> bags = new List <Pkcs12SafeBag>(serializedBags.Count);

            for (int i = 0; i < serializedBags.Count; i++)
            {
                ReadOnlyMemory <byte> bagValue = serializedBags[i].BagValue;
                Pkcs12SafeBag         bag      = null;

                try
                {
                    switch (serializedBags[i].BagId)
                    {
                    case Oids.Pkcs12KeyBag:
                        bag = new Pkcs12KeyBag(bagValue);
                        break;

                    case Oids.Pkcs12ShroudedKeyBag:
                        bag = new Pkcs12ShroudedKeyBag(bagValue);
                        break;

                    case Oids.Pkcs12CertBag:
                        bag = Pkcs12CertBag.DecodeValue(bagValue);
                        break;

                    case Oids.Pkcs12CrlBag:
                        // Known, but no first-class support currently.
                        break;

                    case Oids.Pkcs12SecretBag:
                        bag = Pkcs12SecretBag.DecodeValue(bagValue);
                        break;

                    case Oids.Pkcs12SafeContentsBag:
                        bag = Pkcs12SafeContentsBag.Decode(bagValue);
                        break;
                    }
                }
                catch (CryptographicException)
                {
                }

                if (bag == null)
                {
                    bag = new Pkcs12SafeBag.UnknownBag(serializedBags[i].BagId, bagValue);
                }

                bag.Attributes = SignerInfo.MakeAttributeCollection(serializedBags[i].BagAttributes);
                bags.Add(bag);
            }

            return(bags);
        }
コード例 #37
0
        internal static unsafe int GetSignerIndex(System.Security.Cryptography.SafeCryptMsgHandle safeCrytpMsgHandle, SignerInfo signerInfo, int startIndex)
        {
            uint num  = 0;
            uint num2 = (uint)Marshal.SizeOf(typeof(uint));

            if (!System.Security.Cryptography.CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle, 5, 0, new IntPtr((void *)&num), new IntPtr((void *)&num2)))
            {
                checkErr(Marshal.GetLastWin32Error());
            }
            for (int i = startIndex; i < num; i++)
            {
                uint num4 = 0;
                if (!System.Security.Cryptography.CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle, 6, (uint)i, IntPtr.Zero, new IntPtr((void *)&num4)))
                {
                    checkErr(Marshal.GetLastWin32Error());
                }
                if (num4 > 0)
                {
                    System.Security.Cryptography.SafeLocalAllocHandle pvData = System.Security.Cryptography.CAPI.LocalAlloc(0, new IntPtr((long)num4));
                    if (!System.Security.Cryptography.CAPI.CAPISafe.CryptMsgGetParam(safeCrytpMsgHandle, 6, (uint)i, pvData, new IntPtr((void *)&num4)))
                    {
                        checkErr(Marshal.GetLastWin32Error());
                    }
                    System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO cmsgSignerInfo    = signerInfo.GetCmsgSignerInfo();
                    System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO cmsg_signer_info2 = (System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO)Marshal.PtrToStructure(pvData.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO));
                    if (System.Security.Cryptography.X509Certificates.X509Utils.MemEqual((byte *)cmsgSignerInfo.Issuer.pbData, cmsgSignerInfo.Issuer.cbData, (byte *)cmsg_signer_info2.Issuer.pbData, cmsg_signer_info2.Issuer.cbData) && System.Security.Cryptography.X509Certificates.X509Utils.MemEqual((byte *)cmsgSignerInfo.SerialNumber.pbData, cmsgSignerInfo.SerialNumber.cbData, (byte *)cmsg_signer_info2.SerialNumber.pbData, cmsg_signer_info2.SerialNumber.cbData))
                    {
                        return(i);
                    }
                    pvData.Dispose();
                }
            }
            throw new CryptographicException(-2146889714);
        }
コード例 #38
0
        private static bool TryGetCertIds(SignerInfo signer, out EssCertId certId, out EssCertIdV2 certId2)
        {
            // RFC 5035 says that SigningCertificateV2 (contains ESSCertIDv2) is a signed
            // attribute, with OID 1.2.840.113549.1.9.16.2.47, and that it must not be multiply defined.

            // RFC 2634 says that SigningCertificate (contains ESSCertID) is a signed attribute,
            // with OID 1.2.840.113549.1.9.16.2.12, and that it must not be multiply defined.
            certId  = null;
            certId2 = null;

            foreach (CryptographicAttributeObject attrSet in signer.SignedAttributes)
            {
                string setOid = attrSet.Oid?.Value;

                if (setOid != null &&
                    setOid != Oids.SigningCertificate &&
                    setOid != Oids.SigningCertificateV2)
                {
                    continue;
                }

                foreach (AsnEncodedData attr in attrSet.Values)
                {
                    string attrOid = attr.Oid?.Value;

                    if (attrOid == Oids.SigningCertificate)
                    {
                        if (certId != null)
                        {
                            return(false);
                        }

                        try
                        {
                            SigningCertificateAsn signingCert =
                                AsnSerializer.Deserialize <SigningCertificateAsn>(attr.RawData, AsnEncodingRules.BER);

                            if (signingCert.Certs.Length < 1)
                            {
                                return(false);
                            }

                            // The first one is the signing cert, the rest constrain the chain.
                            certId = signingCert.Certs[0];
                        }
                        catch (CryptographicException)
                        {
                            return(false);
                        }
                    }

                    if (attrOid == Oids.SigningCertificateV2)
                    {
                        if (certId2 != null)
                        {
                            return(false);
                        }

                        try
                        {
                            SigningCertificateV2Asn signingCert =
                                AsnSerializer.Deserialize <SigningCertificateV2Asn>(attr.RawData, AsnEncodingRules.BER);

                            if (signingCert.Certs.Length < 1)
                            {
                                return(false);
                            }

                            // The first one is the signing cert, the rest constrain the chain.
                            certId2 = signingCert.Certs[0];
                        }
                        catch (CryptographicException)
                        {
                            return(false);
                        }
                    }
                }
            }

            return(certId2 != null || certId != null);
        }
コード例 #39
0
        // methods

        internal void Add(SignerInfo signer)
        {
            _list.Add(signer);
        }
コード例 #40
0
 public bool VerifySignatureForSignerInfo(SignerInfo signerInfo, out X509Certificate2 signerCertificate, X509Certificate2Collection extraCandidates = null) => throw null;
コード例 #41
0
        public void Decode(byte[] encodedMessage)
        {
            PKCS7.ContentInfo ci = new PKCS7.ContentInfo(encodedMessage);
            if (ci.ContentType != PKCS7.Oid.signedData)
            {
                throw new Exception("");
            }

            PKCS7.SignedData      sd   = new PKCS7.SignedData(ci.Content);
            SubjectIdentifierType type = SubjectIdentifierType.Unknown;
            object o = null;

            X509Certificate2 x509 = null;

            if (sd.SignerInfo.Certificate != null)
            {
                x509 = new X509Certificate2(sd.SignerInfo.Certificate.RawData);
            }
            else if ((sd.SignerInfo.IssuerName != null) && (sd.SignerInfo.SerialNumber != null))
            {
                byte[] serial = sd.SignerInfo.SerialNumber;
                Array.Reverse(serial);                  // ???
                type = SubjectIdentifierType.IssuerAndSerialNumber;
                X509IssuerSerial xis = new X509IssuerSerial();
                xis.IssuerName   = sd.SignerInfo.IssuerName;
                xis.SerialNumber = ToString(serial, true);
                o = xis;
                // TODO: move to a FindCertificate (issuer, serial, collection)
                foreach (Mono.Security.X509.X509Certificate x in sd.Certificates)
                {
                    if (x.IssuerName == sd.SignerInfo.IssuerName)
                    {
                        if (ToString(x.SerialNumber, true) == xis.SerialNumber)
                        {
                            x509 = new X509Certificate2(x.RawData);
                            break;
                        }
                    }
                }
            }
            else if (sd.SignerInfo.SubjectKeyIdentifier != null)
            {
                string ski = ToString(sd.SignerInfo.SubjectKeyIdentifier, false);
                type = SubjectIdentifierType.SubjectKeyIdentifier;
                o    = (object)ski;
                // TODO: move to a FindCertificate (ski, collection)
                foreach (Mono.Security.X509.X509Certificate x in sd.Certificates)
                {
                    if (ToString(GetKeyIdentifier(x), false) == ski)
                    {
                        x509 = new X509Certificate2(x.RawData);
                        break;
                    }
                }
            }

            SignerInfo si = new SignerInfo(sd.SignerInfo.HashName, x509, type, o, sd.SignerInfo.Version);

            // si.AuthenticatedAttributes
            // si.UnauthenticatedAttributes
            _info.Add(si);

            ASN1 content = sd.ContentInfo.Content;
            Oid  oid     = new Oid(sd.ContentInfo.ContentType);

            if (!_detached || _content == null)
            {
                if (content[0] == null)
                {
                    throw new ArgumentException("ContentInfo has no content. Detached signature ?");
                }

                _content = new ContentInfo(oid, content[0].Value);
            }

            foreach (Mono.Security.X509.X509Certificate x in sd.Certificates)
            {
                _certs.Add(new X509Certificate2(x.RawData));
            }

            _version = sd.Version;
        }
コード例 #42
0
        private static bool CheckCertificate(
            X509Certificate2 tsaCertificate,
            SignerInfo signer,
            EssCertId certId,
            EssCertIdV2 certId2,
            Rfc3161TimestampTokenInfo tokenInfo)
        {
            Debug.Assert(tsaCertificate != null);
            Debug.Assert(signer != null);
            Debug.Assert(tokenInfo != null);
            // certId and certId2 are allowed to be null, they get checked in CertMatchesIds.

            if (!CertMatchesIds(tsaCertificate, certId, certId2))
            {
                return(false);
            }

            // Nothing in RFC3161 actually mentions checking the certificate's validity
            // against the TSTInfo timestamp value, but it seems sensible.
            //
            // Accuracy is ignored here, for better replicability in user code.

            if (tsaCertificate.NotAfter < tokenInfo.Timestamp ||
                tsaCertificate.NotBefore > tokenInfo.Timestamp)
            {
                return(false);
            }

            // https://tools.ietf.org/html/rfc3161#section-2.3
            //
            // The TSA MUST sign each time-stamp message with a key reserved
            // specifically for that purpose.  A TSA MAY have distinct private keys,
            // e.g., to accommodate different policies, different algorithms,
            // different private key sizes or to increase the performance. The
            // corresponding certificate MUST contain only one instance of the
            // extended key usage field extension as defined in [RFC2459] Section
            // 4.2.1.13 with KeyPurposeID having value:
            //
            // id-kp-timeStamping. This extension MUST be critical.

            using (var ekuExts = tsaCertificate.Extensions.OfType <X509EnhancedKeyUsageExtension>().GetEnumerator())
            {
                if (!ekuExts.MoveNext())
                {
                    return(false);
                }

                X509EnhancedKeyUsageExtension ekuExt = ekuExts.Current;

                if (!ekuExt.Critical)
                {
                    return(false);
                }

                bool hasPurpose = false;

                foreach (Oid oid in ekuExt.EnhancedKeyUsages)
                {
                    if (oid.Value == Oids.TimeStampingPurpose)
                    {
                        hasPurpose = true;
                        break;
                    }
                }

                if (!hasPurpose)
                {
                    return(false);
                }

                if (ekuExts.MoveNext())
                {
                    return(false);
                }
            }

            try
            {
                signer.CheckSignature(new X509Certificate2Collection(tsaCertificate), true);
                return(true);
            }
            catch (CryptographicException)
            {
                return(false);
            }
        }
コード例 #43
0
 public void RemoveCounterSignature(SignerInfo counterSignerInfo)
 {
 }
コード例 #44
0
        public static bool TryDecode(ReadOnlyMemory <byte> source, out Rfc3161TimestampToken token, out int bytesConsumed)
        {
            bytesConsumed = 0;
            token         = null;

            try
            {
                ContentInfoAsn contentInfo =
                    AsnSerializer.Deserialize <ContentInfoAsn>(source, AsnEncodingRules.BER, out int bytesActuallyRead);

                // https://tools.ietf.org/html/rfc3161#section-2.4.2
                //
                // A TimeStampToken is as follows.  It is defined as a ContentInfo
                // ([CMS]) and SHALL encapsulate a signed data content type.
                //
                // TimeStampToken::= ContentInfo
                //   --contentType is id-signedData([CMS])
                //   --content is SignedData ([CMS])
                if (contentInfo.ContentType != Oids.Pkcs7Signed)
                {
                    return(false);
                }

                SignedCms cms = new SignedCms();
                cms.Decode(source);

                // The fields of type EncapsulatedContentInfo of the SignedData
                // construct have the following meanings:
                //
                // eContentType is an object identifier that uniquely specifies the
                // content type.  For a time-stamp token it is defined as:
                //
                // id-ct-TSTInfo  OBJECT IDENTIFIER ::= { iso(1) member-body(2)
                // us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1) 4}
                //
                // eContent is the content itself, carried as an octet string.
                // The eContent SHALL be the DER-encoded value of TSTInfo.
                if (cms.ContentInfo.ContentType.Value != Oids.TstInfo)
                {
                    return(false);
                }

                // RFC3161:
                // The time-stamp token MUST NOT contain any signatures other than the
                // signature of the TSA.  The certificate identifier (ESSCertID) of the
                // TSA certificate MUST be included as a signerInfo attribute inside a
                // SigningCertificate attribute.

                // RFC5816 says that ESSCertIDv2 should be allowed instead.

                SignerInfoCollection signerInfos = cms.SignerInfos;

                if (signerInfos.Count != 1)
                {
                    return(false);
                }

                SignerInfo  signer = signerInfos[0];
                EssCertId   certId;
                EssCertIdV2 certId2;

                if (!TryGetCertIds(signer, out certId, out certId2))
                {
                    return(false);
                }

                X509Certificate2 signerCert = signer.Certificate;

                if (signerCert == null &&
                    signer.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)
                {
                    // If the cert wasn't provided, but the identifier was IssuerAndSerialNumber,
                    // and the ESSCertId(V2) has specified an issuerSerial value, ensure it's a match.
                    X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value;

                    if (certId?.IssuerSerial != null)
                    {
                        if (!IssuerAndSerialMatch(
                                certId.IssuerSerial.Value,
                                issuerSerial.IssuerName,
                                issuerSerial.SerialNumber))
                        {
                            return(false);
                        }
                    }

                    if (certId2?.IssuerSerial != null)
                    {
                        if (!IssuerAndSerialMatch(
                                certId2.IssuerSerial.Value,
                                issuerSerial.IssuerName,
                                issuerSerial.SerialNumber))
                        {
                            return(false);
                        }
                    }
                }

                Rfc3161TimestampTokenInfo tokenInfo;

                if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out tokenInfo, out _))
                {
                    if (signerCert != null &&
                        !CheckCertificate(signerCert, signer, certId, certId2, tokenInfo))
                    {
                        return(false);
                    }

                    token = new Rfc3161TimestampToken
                    {
                        _parsedDocument = cms,
                        _signerInfo     = signer,
                        _essCertId      = certId,
                        _essCertIdV2    = certId2,
                        TokenInfo       = tokenInfo,
                    };

                    bytesConsumed = bytesActuallyRead;
                    return(true);
                }
            }
            catch (CryptographicException)
            {
            }

            return(false);
        }
コード例 #45
0
 private static bool CheckCertificate(
     X509Certificate2 tsaCertificate,
     SignerInfo signer,
     in EssCertId?certId,
コード例 #46
0
		public void RemoveSignature (SignerInfo counterSsignerInfo)
		{
		}
コード例 #47
0
 public void RemoveSignature(SignerInfo signerInfo)
 {
     _signedCms.RemoveSignature(signerInfo);
 }
コード例 #48
0
ファイル: SignedCms.cs プロジェクト: nlhepler/mono
		public void RemoveSignature (SignerInfo signerInfo)
		{
		}
コード例 #49
0
        internal int FindIndexForSigner(SignerInfo signer)
        {
            Debug.Assert(signer != null);
            SubjectIdentifier id           = signer.SignerIdentifier;
            X509IssuerSerial  issuerSerial = default;

            if (id.Type == SubjectIdentifierType.IssuerAndSerialNumber)
            {
                issuerSerial = (X509IssuerSerial)id.Value;
            }

            for (int i = 0; i < _signerInfos.Length; i++)
            {
                SignerInfo        current   = _signerInfos[i];
                SubjectIdentifier currentId = current.SignerIdentifier;

                if (currentId.Type != id.Type)
                {
                    continue;
                }

                bool equal = false;

                switch (id.Type)
                {
                case SubjectIdentifierType.IssuerAndSerialNumber:
                {
                    X509IssuerSerial currentIssuerSerial = (X509IssuerSerial)currentId.Value;

                    if (currentIssuerSerial.IssuerName == issuerSerial.IssuerName &&
                        currentIssuerSerial.SerialNumber == issuerSerial.SerialNumber)
                    {
                        equal = true;
                    }

                    break;
                }

                case SubjectIdentifierType.SubjectKeyIdentifier:
                    if ((string)id.Value == (string)currentId.Value)
                    {
                        equal = true;
                    }

                    break;

                case SubjectIdentifierType.NoSignature:
                    equal = true;
                    break;

                default:
                    Debug.Fail($"No match logic for SubjectIdentifierType {id.Type}");
                    throw new CryptographicException();
                }

                if (equal)
                {
                    return(i);
                }
            }

            return(-1);
        }
コード例 #50
0
 public void RemoveCounterSignature(SignerInfo counterSignerInfo)
 {
     if (this.m_parentSignerInfo != null)
     {
         throw new CryptographicException(-2147483647);
     }
     if (counterSignerInfo == null)
     {
         throw new ArgumentNullException("counterSignerInfo");
     }
     CryptographicAttributeObjectEnumerator enumerator = this.UnsignedAttributes.GetEnumerator();
     while (enumerator.MoveNext())
     {
         CryptographicAttributeObject current = enumerator.Current;
         if (string.Compare(current.Oid.Value, "1.2.840.113549.1.9.6", StringComparison.OrdinalIgnoreCase) == 0)
         {
             for (int i = 0; i < current.Values.Count; i++)
             {
                 AsnEncodedData data = current.Values[i];
                 SignerInfo info = new SignerInfo(this.m_signedCms, this.m_parentSignerInfo, data.RawData);
                 if ((counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber) && (info.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber))
                 {
                     X509IssuerSerial serial = (X509IssuerSerial) counterSignerInfo.SignerIdentifier.Value;
                     X509IssuerSerial serial2 = (X509IssuerSerial) info.SignerIdentifier.Value;
                     if ((string.Compare(serial.IssuerName, serial2.IssuerName, StringComparison.OrdinalIgnoreCase) != 0) || (string.Compare(serial.SerialNumber, serial2.SerialNumber, StringComparison.OrdinalIgnoreCase) != 0))
                     {
                         continue;
                     }
                     this.RemoveCounterSignature(PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0), i);
                     return;
                 }
                 if ((counterSignerInfo.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier) && (info.SignerIdentifier.Type == SubjectIdentifierType.SubjectKeyIdentifier))
                 {
                     string strA = counterSignerInfo.SignerIdentifier.Value as string;
                     string strB = info.SignerIdentifier.Value as string;
                     if (string.Compare(strA, strB, StringComparison.OrdinalIgnoreCase) == 0)
                     {
                         this.RemoveCounterSignature(PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0), i);
                         return;
                     }
                 }
             }
         }
     }
     throw new CryptographicException(-2146889714);
 }
コード例 #51
-1
		public void Decode (byte[] encodedMessage) 
		{
			PKCS7.ContentInfo ci = new PKCS7.ContentInfo (encodedMessage);
			if (ci.ContentType != PKCS7.Oid.signedData) 
				throw new Exception ("");

			PKCS7.SignedData sd = new PKCS7.SignedData (ci.Content);
			SubjectIdentifierType type = SubjectIdentifierType.Unknown;
			object o = null;

			X509Certificate2 x509 = null;
			if (sd.SignerInfo.Certificate != null) {
				x509 = new X509Certificate2 (sd.SignerInfo.Certificate.RawData);
			}
			else if ((sd.SignerInfo.IssuerName != null) && (sd.SignerInfo.SerialNumber != null)) {
				byte[] serial = sd.SignerInfo.SerialNumber;
				Array.Reverse (serial); // ???
				type = SubjectIdentifierType.IssuerAndSerialNumber;
				X509IssuerSerial xis = new X509IssuerSerial ();
				xis.IssuerName = sd.SignerInfo.IssuerName;
				xis.SerialNumber = ToString (serial, true);
				o = xis;
				// TODO: move to a FindCertificate (issuer, serial, collection)
				foreach (Mono.Security.X509.X509Certificate x in sd.Certificates) {
					if (x.IssuerName == sd.SignerInfo.IssuerName) {
						if (ToString (x.SerialNumber, true) == xis.SerialNumber) {
							x509 = new X509Certificate2 (x.RawData);
							break;
						}
					}
				}
			}
			else if (sd.SignerInfo.SubjectKeyIdentifier != null) {
				string ski = ToString (sd.SignerInfo.SubjectKeyIdentifier, false);
				type = SubjectIdentifierType.SubjectKeyIdentifier;
				o = (object) ski;
				// TODO: move to a FindCertificate (ski, collection)
				foreach (Mono.Security.X509.X509Certificate x in sd.Certificates) {
					if (ToString (GetKeyIdentifier (x), false) == ski) {
						x509 = new X509Certificate2 (x.RawData);
						break;
					}
				}
			}

			SignerInfo si = new SignerInfo (sd.SignerInfo.HashName, x509, type, o, sd.SignerInfo.Version);
			// si.AuthenticatedAttributes
			// si.UnauthenticatedAttributes
			_info.Add (si);

			ASN1 content = sd.ContentInfo.Content;
			Oid oid = new Oid (sd.ContentInfo.ContentType);
			_content = new ContentInfo (oid, content[0].Value);

			foreach (Mono.Security.X509.X509Certificate x in sd.Certificates) {
				_certs.Add (new X509Certificate2 (x.RawData));
			}

			_version = sd.Version;
		}