Inheritance: CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
        /// <summary>Creates a permission that is the union of the current permission and the specified permission.</summary>
        /// <returns>A new permission that represents the union of the current permission and the specified permission.</returns>
        /// <param name="target">A permission to combine with the current permission. It must be of the same type as the current permission. </param>
        /// <exception cref="T:System.ArgumentException">
        ///   <paramref name="target" /> is not null and does not specify a permission of the same type as the current permission. </exception>
        public override IPermission Union(IPermission target)
        {
            KeyContainerPermission keyContainerPermission = this.Cast(target);

            if (keyContainerPermission == null)
            {
                return(this.Copy());
            }
            KeyContainerPermissionAccessEntryCollection keyContainerPermissionAccessEntryCollection = new KeyContainerPermissionAccessEntryCollection();

            foreach (KeyContainerPermissionAccessEntry accessEntry in this._accessEntries)
            {
                keyContainerPermissionAccessEntryCollection.Add(accessEntry);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry2 in keyContainerPermission._accessEntries)
            {
                if (this._accessEntries.IndexOf(accessEntry2) == -1)
                {
                    keyContainerPermissionAccessEntryCollection.Add(accessEntry2);
                }
            }
            if (keyContainerPermissionAccessEntryCollection.Count == 0)
            {
                return(new KeyContainerPermission(this._flags | keyContainerPermission._flags));
            }
            KeyContainerPermissionAccessEntry[] array = new KeyContainerPermissionAccessEntry[keyContainerPermissionAccessEntryCollection.Count];
            keyContainerPermissionAccessEntryCollection.CopyTo(array, 0);
            return(new KeyContainerPermission(this._flags | keyContainerPermission._flags, array));
        }
        // Token: 0x060026CD RID: 9933 RVA: 0x0008CBA8 File Offset: 0x0008ADA8
        private void AddAccessEntryAndUnion(KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target)
        {
            KeyContainerPermissionAccessEntry keyContainerPermissionAccessEntry = new KeyContainerPermissionAccessEntry(accessEntry);

            keyContainerPermissionAccessEntry.Flags |= KeyContainerPermission.GetApplicableFlags(accessEntry, target);
            this.AccessEntries.Add(keyContainerPermissionAccessEntry);
        }
        private void AddAccessEntryAndIntersect(KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target)
        {
            KeyContainerPermissionAccessEntry accessEntry1 = new KeyContainerPermissionAccessEntry(accessEntry);

            accessEntry1.Flags &= KeyContainerPermission.GetApplicableFlags(accessEntry, target);
            this.AccessEntries.Add(accessEntry1);
        }
 /// <summary>从 XML 编码重新构造具有指定状态的权限。</summary>
 /// <param name="securityElement">
 /// <see cref="T:System.Security.SecurityElement" />,包含用于重新构造权限的 XML 编码。</param>
 /// <exception cref="T:System.ArgumentNullException">
 /// <paramref name="securityElement" /> 为 null。</exception>
 /// <exception cref="T:System.ArgumentException">
 /// <paramref name="securityElement" /> 不是一个有效的权限元素。- 或 -不支持 <paramref name="securityElement" /> 的版本号。</exception>
 public override void FromXml(SecurityElement securityElement)
 {
     CodeAccessPermission.ValidateElement(securityElement, (IPermission)this);
     if (XMLUtil.IsUnrestricted(securityElement))
     {
         this.m_flags         = KeyContainerPermissionFlags.AllFlags;
         this.m_accessEntries = new KeyContainerPermissionAccessEntryCollection(this.m_flags);
     }
     else
     {
         this.m_flags = KeyContainerPermissionFlags.NoFlags;
         string str = securityElement.Attribute("Flags");
         if (str != null)
         {
             KeyContainerPermissionFlags flags = (KeyContainerPermissionFlags)Enum.Parse(typeof(KeyContainerPermissionFlags), str);
             KeyContainerPermission.VerifyFlags(flags);
             this.m_flags = flags;
         }
         this.m_accessEntries = new KeyContainerPermissionAccessEntryCollection(this.m_flags);
         if (securityElement.InternalChildren == null || securityElement.InternalChildren.Count == 0)
         {
             return;
         }
         foreach (SecurityElement child in securityElement.Children)
         {
             if (child != null && string.Equals(child.Tag, "AccessList"))
             {
                 this.AddAccessEntries(child);
             }
         }
     }
 }
        //
        // IPermission implementation
        //

        public override bool IsSubsetOf (IPermission target) {
            if (target == null) 
                return IsEmpty();

            if (!VerifyType(target))
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));

            KeyContainerPermission operand = (KeyContainerPermission) target;

            // since there are containers that are neither in the access list of the source, nor in the 
            // access list of the target, the source flags must be a subset of the target flags.
            if ((this.m_flags & operand.m_flags) != this.m_flags)
                return false;

            // Any entry in the source should have "applicable" flags in the destination that actually
            // are less restrictive than the flags in the source.

            foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
                KeyContainerPermissionFlags targetFlags = GetApplicableFlags(accessEntry, operand);
                if ((accessEntry.Flags & targetFlags) != accessEntry.Flags)
                    return false;
            }

            // Any entry in the target should have "applicable" flags in the source that actually
            // are more restrictive than the flags in the target.

            foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) {
                KeyContainerPermissionFlags sourceFlags = GetApplicableFlags(accessEntry, this);
                if ((sourceFlags & accessEntry.Flags) != sourceFlags)
                    return false;
            }

            return true;
        }
        /// <summary>创建一个权限,该权限是当前权限与指定权限的并集。</summary>
        /// <returns>一个新权限,它表示当前权限与指定权限的并集。</returns>
        /// <param name="target">将与当前权限合并的权限。它必须与当前权限属于同一类型。</param>
        /// <exception cref="T:System.ArgumentException">
        /// <paramref name="target" /> 不是 null,并且未指定与当前权限属于同一类型的权限。</exception>
        public override IPermission Union(IPermission target)
        {
            if (target == null)
            {
                return(this.Copy());
            }
            if (!this.VerifyType(target))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", (object)this.GetType().FullName));
            }
            KeyContainerPermission target1 = (KeyContainerPermission)target;

            if (this.IsUnrestricted() || target1.IsUnrestricted())
            {
                return((IPermission) new KeyContainerPermission(PermissionState.Unrestricted));
            }
            KeyContainerPermission containerPermission = new KeyContainerPermission(this.m_flags | target1.m_flags);

            foreach (KeyContainerPermissionAccessEntry accessEntry in this.AccessEntries)
            {
                containerPermission.AddAccessEntryAndUnion(accessEntry, target1);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry in target1.AccessEntries)
            {
                containerPermission.AddAccessEntryAndUnion(accessEntry, this);
            }
            if (!containerPermission.IsEmpty())
            {
                return((IPermission)containerPermission);
            }
            return((IPermission)null);
        }
Beispiel #7
0
 public override IPermission Intersect(IPermission target)
 {
     if (target != null)
     {
         if (!base.VerifyType(target))
         {
             throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", new object[] { base.GetType().FullName }));
         }
         KeyContainerPermission permission = (KeyContainerPermission)target;
         if (this.IsEmpty() || permission.IsEmpty())
         {
             return(null);
         }
         KeyContainerPermissionFlags flags       = permission.m_flags & this.m_flags;
         KeyContainerPermission      permission2 = new KeyContainerPermission(flags);
         KeyContainerPermissionAccessEntryEnumerator enumerator = this.AccessEntries.GetEnumerator();
         while (enumerator.MoveNext())
         {
             KeyContainerPermissionAccessEntry current = enumerator.Current;
             permission2.AddAccessEntryAndIntersect(current, permission);
         }
         KeyContainerPermissionAccessEntryEnumerator enumerator2 = permission.AccessEntries.GetEnumerator();
         while (enumerator2.MoveNext())
         {
             KeyContainerPermissionAccessEntry accessEntry = enumerator2.Current;
             permission2.AddAccessEntryAndIntersect(accessEntry, this);
         }
         if (!permission2.IsEmpty())
         {
             return(permission2);
         }
     }
     return(null);
 }
        public override IPermission Intersect(IPermission target)
        {
            if (target == null)
            {
                return(null);
            }

            if (!VerifyType(target))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
            }

            KeyContainerPermission operand = (KeyContainerPermission)target;

            if (this.IsEmpty() || operand.IsEmpty())
            {
                return(null);
            }

            KeyContainerPermissionFlags flags_intersect = operand.m_flags & this.m_flags;
            KeyContainerPermission      cp = new KeyContainerPermission(flags_intersect);

            foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries)
            {
                cp.AddAccessEntryAndIntersect(accessEntry, operand);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries)
            {
                cp.AddAccessEntryAndIntersect(accessEntry, this);
            }
            return(cp.IsEmpty() ? null : cp);
        }
        /// <summary>Reconstructs a permission with a specified state from an XML encoding.</summary>
        /// <param name="securityElement">A <see cref="T:System.Security.SecurityElement" /> that contains the XML encoding used to reconstruct the permission. </param>
        /// <exception cref="T:System.ArgumentNullException">
        ///         <paramref name="securityElement" /> is <see langword="null" />. </exception>
        /// <exception cref="T:System.ArgumentException">
        ///         <paramref name="securityElement" /> is not a valid permission element.-or- The version number of <paramref name="securityElement" /> is not supported. </exception>
        // Token: 0x060026CA RID: 9930 RVA: 0x0008C94C File Offset: 0x0008AB4C
        public override void FromXml(SecurityElement securityElement)
        {
            CodeAccessPermission.ValidateElement(securityElement, this);
            if (XMLUtil.IsUnrestricted(securityElement))
            {
                this.m_flags         = KeyContainerPermissionFlags.AllFlags;
                this.m_accessEntries = new KeyContainerPermissionAccessEntryCollection(this.m_flags);
                return;
            }
            this.m_flags = KeyContainerPermissionFlags.NoFlags;
            string text = securityElement.Attribute("Flags");

            if (text != null)
            {
                KeyContainerPermissionFlags flags = (KeyContainerPermissionFlags)Enum.Parse(typeof(KeyContainerPermissionFlags), text);
                KeyContainerPermission.VerifyFlags(flags);
                this.m_flags = flags;
            }
            this.m_accessEntries = new KeyContainerPermissionAccessEntryCollection(this.m_flags);
            if (securityElement.InternalChildren != null && securityElement.InternalChildren.Count != 0)
            {
                foreach (object obj in securityElement.Children)
                {
                    SecurityElement securityElement2 = (SecurityElement)obj;
                    if (securityElement2 != null && string.Equals(securityElement2.Tag, "AccessList"))
                    {
                        this.AddAccessEntries(securityElement2);
                    }
                }
            }
        }
        /// <summary>确定当前权限是否为指定权限的子集。</summary>
        /// <returns>如果当前权限是指定权限的子集,则为 true;否则为 false。</returns>
        /// <param name="target">要测试子集关系的权限。此权限必须与当前权限属于同一类型。</param>
        /// <exception cref="T:System.ArgumentException">
        /// <paramref name="target" /> 不是 null,并且未指定与当前权限属于同一类型的权限。</exception>
        public override bool IsSubsetOf(IPermission target)
        {
            if (target == null)
            {
                return(this.IsEmpty());
            }
            if (!this.VerifyType(target))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", (object)this.GetType().FullName));
            }
            KeyContainerPermission target1 = (KeyContainerPermission)target;

            if ((this.m_flags & target1.m_flags) != this.m_flags)
            {
                return(false);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry in this.AccessEntries)
            {
                KeyContainerPermissionFlags applicableFlags = KeyContainerPermission.GetApplicableFlags(accessEntry, target1);
                if ((accessEntry.Flags & applicableFlags) != accessEntry.Flags)
                {
                    return(false);
                }
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry in target1.AccessEntries)
            {
                KeyContainerPermissionFlags applicableFlags = KeyContainerPermission.GetApplicableFlags(accessEntry, this);
                if ((applicableFlags & accessEntry.Flags) != applicableFlags)
                {
                    return(false);
                }
            }
            return(true);
        }
        public override IPermission Union(IPermission target)
        {
            if (target == null)
            {
                return(this.Copy());
            }

            if (!VerifyType(target))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
            }

            KeyContainerPermission operand = (KeyContainerPermission)target;

            if (this.IsUnrestricted() || operand.IsUnrestricted())
            {
                return(new KeyContainerPermission(PermissionState.Unrestricted));
            }

            KeyContainerPermissionFlags flags_union = (KeyContainerPermissionFlags)(m_flags | operand.m_flags);
            KeyContainerPermission      cp          = new KeyContainerPermission(flags_union);

            foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries)
            {
                cp.AddAccessEntryAndUnion(accessEntry, operand);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries)
            {
                cp.AddAccessEntryAndUnion(accessEntry, this);
            }
            return(cp.IsEmpty() ? null : cp);
        }
        public override IPermission Union(IPermission target)
        {
            KeyContainerPermission kcp = Cast(target);

            if (kcp == null)
            {
                return(Copy());
            }

            KeyContainerPermissionAccessEntryCollection kcpaec = new KeyContainerPermissionAccessEntryCollection();

            // copy first group
            foreach (KeyContainerPermissionAccessEntry kcpae in _accessEntries)
            {
                kcpaec.Add(kcpae);
            }
            // copy second group...
            foreach (KeyContainerPermissionAccessEntry kcpae in kcp._accessEntries)
            {
                // ... but only if not present in first group
                if (_accessEntries.IndexOf(kcpae) == -1)
                {
                    kcpaec.Add(kcpae);
                }
            }

            if (kcpaec.Count == 0)
            {
                return(new KeyContainerPermission((_flags | kcp._flags)));
            }

            KeyContainerPermissionAccessEntry[] list = new KeyContainerPermissionAccessEntry [kcpaec.Count];
            kcpaec.CopyTo(list, 0);
            return(new KeyContainerPermission((_flags | kcp._flags), list));
        }
 public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters)
 {
     if (algorithm == null)
     {
         throw new ArgumentNullException("algorithm");
     }
     if (creationParameters == null)
     {
         creationParameters = new CngKeyCreationParameters();
     }
     if (!NCryptNative.NCryptSupported)
     {
         throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
     }
     if (keyName != null)
     {
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create) {
             ProviderName = creationParameters.Provider.Provider
         };
         KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         permission.AccessEntries.Add(accessEntry);
         permission.Demand();
     }
     SafeNCryptProviderHandle provider = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider);
     SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(provider, algorithm.Algorithm, keyName, creationParameters.KeyCreationOptions);
     SetKeyProperties(keyHandle, creationParameters);
     NCryptNative.FinalizeKey(keyHandle);
     CngKey key = new CngKey(provider, keyHandle);
     if (keyName == null)
     {
         key.IsEphemeral = true;
     }
     return key;
 }
 internal KeyContainerPermission BuildKeyContainerPermission(KeyContainerPermissionFlags flags)
 {
     KeyContainerPermission permission = null;
     if (this.IsEphemeral)
     {
         return permission;
     }
     string keyContainerName = null;
     string str2 = null;
     try
     {
         keyContainerName = this.KeyName;
         str2 = NCryptNative.GetPropertyAsString(this.m_kspHandle, "Name", CngPropertyOptions.None);
     }
     catch (CryptographicException)
     {
     }
     if (keyContainerName != null)
     {
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyContainerName, flags) {
             ProviderName = str2
         };
         permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         permission.AccessEntries.Add(accessEntry);
         return permission;
     }
     return new KeyContainerPermission(flags);
 }
        public override IPermission Copy () {
            if (this.IsEmpty())
                return null;

            KeyContainerPermission cp = new KeyContainerPermission((KeyContainerPermissionFlags)m_flags);
            foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
                cp.AccessEntries.Add(accessEntry);
            }
            return cp;
        }
        /// <summary>创建并返回当前权限的相同副本。</summary>
        /// <returns>当前权限的副本。</returns>
        public override IPermission Copy()
        {
            if (this.IsEmpty())
            {
                return((IPermission)null);
            }
            KeyContainerPermission containerPermission = new KeyContainerPermission(this.m_flags);

            foreach (KeyContainerPermissionAccessEntry accessEntry in this.AccessEntries)
            {
                containerPermission.AccessEntries.Add(accessEntry);
            }
            return((IPermission)containerPermission);
        }
 /// <summary>用指定的全局访问和特定的密钥容器访问权限来初始化 <see cref="T:System.Security.Permissions.KeyContainerPermission" /> 类的新实例。</summary>
 /// <param name="flags">
 /// <see cref="T:System.Security.Permissions.KeyContainerPermissionFlags" /> 值的按位组合。</param>
 /// <param name="accessList">
 /// <see cref="T:System.Security.Permissions.KeyContainerPermissionAccessEntry" /> 对象数组,标识特定的密钥容器访问权限。</param>
 /// <exception cref="T:System.ArgumentException">
 /// <paramref name="flags" /> 不是 <see cref="T:System.Security.Permissions.KeyContainerPermissionFlags" /> 值的有效组合。</exception>
 /// <exception cref="T:System.ArgumentNullException">
 /// <paramref name="accessList" /> 为 null。</exception>
 public KeyContainerPermission(KeyContainerPermissionFlags flags, KeyContainerPermissionAccessEntry[] accessList)
 {
     if (accessList == null)
     {
         throw new ArgumentNullException("accessList");
     }
     KeyContainerPermission.VerifyFlags(flags);
     this.m_flags         = flags;
     this.m_accessEntries = new KeyContainerPermissionAccessEntryCollection(this.m_flags);
     for (int index = 0; index < accessList.Length; ++index)
     {
         this.m_accessEntries.Add(accessList[index]);
     }
 }
        private KeyContainerPermission Cast(IPermission target)
        {
            if (target == null)
            {
                return(null);
            }
            KeyContainerPermission keyContainerPermission = target as KeyContainerPermission;

            if (keyContainerPermission == null)
            {
                CodeAccessPermission.ThrowInvalidPermission(target, typeof(KeyContainerPermission));
            }
            return(keyContainerPermission);
        }
 public override IPermission CreatePermission()
 {
     if (base.m_unrestricted)
     {
         return new KeyContainerPermission(PermissionState.Unrestricted);
     }
     if (KeyContainerPermissionAccessEntry.IsUnrestrictedEntry(this.m_keyStore, this.m_providerName, this.m_providerType, this.m_keyContainerName, this.m_keySpec))
     {
         return new KeyContainerPermission(this.m_flags);
     }
     KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
     KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this.m_keyStore, this.m_providerName, this.m_providerType, this.m_keyContainerName, this.m_keySpec, this.m_flags);
     permission.AccessEntries.Add(accessEntry);
     return permission;
 }
        [System.Security.SecurityCritical]  // auto-generated
        internal CspKeyContainerInfo (CspParameters parameters, bool randomKeyContainer) {
            KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); 
            KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open);
            kp.AccessEntries.Add(entry); 
            kp.Demand(); 

            m_parameters = new CspParameters(parameters); 
            if (m_parameters.KeyNumber == -1) {
                if (m_parameters.ProviderType == Constants.PROV_RSA_FULL || m_parameters.ProviderType == Constants.PROV_RSA_AES)
                    m_parameters.KeyNumber = Constants.AT_KEYEXCHANGE;
                else if (m_parameters.ProviderType == Constants.PROV_DSS_DH) 
                    m_parameters.KeyNumber = Constants.AT_SIGNATURE;
            } 
            m_randomKeyContainer = randomKeyContainer; 
        }
Beispiel #21
0
        public override IPermission Copy()
        {
            if (this.IsEmpty())
            {
                return(null);
            }
            KeyContainerPermission permission = new KeyContainerPermission(this.m_flags);
            KeyContainerPermissionAccessEntryEnumerator enumerator = this.AccessEntries.GetEnumerator();

            while (enumerator.MoveNext())
            {
                KeyContainerPermissionAccessEntry current = enumerator.Current;
                permission.AccessEntries.Add(current);
            }
            return(permission);
        }
        private KeyContainerPermission Cast(IPermission target)
        {
            if (target == null)
            {
                return(null);
            }

            KeyContainerPermission kcp = (target as KeyContainerPermission);

            if (kcp == null)
            {
                ThrowInvalidPermission(target, typeof(KeyContainerPermission));
            }

            return(kcp);
        }
        /// <summary>创建并返回一个新的 <see cref="T:System.Security.Permissions.KeyContainerPermission" />。</summary>
        /// <returns>与此特性对应的 <see cref="T:System.Security.Permissions.KeyContainerPermission" />。</returns>
        public override IPermission CreatePermission()
        {
            if (this.m_unrestricted)
            {
                return((IPermission) new KeyContainerPermission(PermissionState.Unrestricted));
            }
            if (KeyContainerPermissionAccessEntry.IsUnrestrictedEntry(this.m_keyStore, this.m_providerName, this.m_providerType, this.m_keyContainerName, this.m_keySpec))
            {
                return((IPermission) new KeyContainerPermission(this.m_flags));
            }
            KeyContainerPermission            containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
            KeyContainerPermissionAccessEntry accessEntry         = new KeyContainerPermissionAccessEntry(this.m_keyStore, this.m_providerName, this.m_providerType, this.m_keyContainerName, this.m_keySpec, this.m_flags);

            containerPermission.AccessEntries.Add(accessEntry);
            return((IPermission)containerPermission);
        }
 internal CspKeyContainerInfo(CspParameters parameters, bool randomKeyContainer)
 {
     KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
     KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open);
     permission.AccessEntries.Add(accessEntry);
     permission.Demand();
     this.m_parameters = new CspParameters(parameters);
     if (this.m_parameters.KeyNumber == -1)
     {
         if ((this.m_parameters.ProviderType == 1) || (this.m_parameters.ProviderType == 0x18))
         {
             this.m_parameters.KeyNumber = 1;
         }
         else if (this.m_parameters.ProviderType == 13)
         {
             this.m_parameters.KeyNumber = 2;
         }
     }
     this.m_randomKeyContainer = randomKeyContainer;
 }
Beispiel #25
0
        public override IPermission CreatePermission()
        {
            if (m_unrestricted)
            {
                return(new KeyContainerPermission(PermissionState.Unrestricted));
            }
            else
            {
                if (KeyContainerPermissionAccessEntry.IsUnrestrictedEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec))
                {
                    return(new KeyContainerPermission(m_flags));
                }

                // create a KeyContainerPermission with a single access entry.
                KeyContainerPermission            cp          = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec, m_flags);
                cp.AccessEntries.Add(accessEntry);
                return(cp);
            }
        }
Beispiel #26
0
        public override bool IsSubsetOf(IPermission target)
        {
            if (target == null)
            {
                return(this.IsEmpty());
            }
            if (!base.VerifyType(target))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", new object[] { base.GetType().FullName }));
            }
            KeyContainerPermission permission = (KeyContainerPermission)target;

            if ((this.m_flags & permission.m_flags) != this.m_flags)
            {
                return(false);
            }
            KeyContainerPermissionAccessEntryEnumerator enumerator = this.AccessEntries.GetEnumerator();

            while (enumerator.MoveNext())
            {
                KeyContainerPermissionAccessEntry current         = enumerator.Current;
                KeyContainerPermissionFlags       applicableFlags = GetApplicableFlags(current, permission);
                if ((current.Flags & applicableFlags) != current.Flags)
                {
                    return(false);
                }
            }
            KeyContainerPermissionAccessEntryEnumerator enumerator2 = permission.AccessEntries.GetEnumerator();

            while (enumerator2.MoveNext())
            {
                KeyContainerPermissionAccessEntry accessEntry = enumerator2.Current;
                KeyContainerPermissionFlags       flags2      = GetApplicableFlags(accessEntry, this);
                if ((flags2 & accessEntry.Flags) != flags2)
                {
                    return(false);
                }
            }
            return(true);
        }
 public byte[] Decrypt(byte[] rgb, bool fOAEP)
 {
     if (rgb == null)
     {
         throw new ArgumentNullException("rgb");
     }
     this.GetKeyPair();
     if (rgb.Length > (this.KeySize / 8))
     {
         throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", new object[] { this.KeySize / 8 }));
     }
     if (!this.CspKeyContainerInfo.RandomlyGenerated)
     {
         KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Decrypt);
         permission.AccessEntries.Add(accessEntry);
         permission.Demand();
     }
     byte[] o = null;
     DecryptKey(this._safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack<byte[]>(ref o));
     return o;
 }
        /// <summary>Determines whether the current permission is a subset of the specified permission.</summary>
        /// <param name="target">A permission to test for the subset relationship. This permission must be the same type as the current permission. </param>
        /// <returns>
        ///     <see langword="true" /> if the current permission is a subset of the specified permission; otherwise, <see langword="false" />.</returns>
        /// <exception cref="T:System.ArgumentException">
        ///         <paramref name="target" /> is not <see langword="null" /> and does not specify a permission of the same type as the current permission. </exception>
        // Token: 0x060026C5 RID: 9925 RVA: 0x0008C544 File Offset: 0x0008A744
        public override bool IsSubsetOf(IPermission target)
        {
            if (target == null)
            {
                return(this.IsEmpty());
            }
            if (!base.VerifyType(target))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", new object[]
                {
                    base.GetType().FullName
                }));
            }
            KeyContainerPermission keyContainerPermission = (KeyContainerPermission)target;

            if ((this.m_flags & keyContainerPermission.m_flags) != this.m_flags)
            {
                return(false);
            }
            foreach (KeyContainerPermissionAccessEntry keyContainerPermissionAccessEntry in this.AccessEntries)
            {
                KeyContainerPermissionFlags applicableFlags = KeyContainerPermission.GetApplicableFlags(keyContainerPermissionAccessEntry, keyContainerPermission);
                if ((keyContainerPermissionAccessEntry.Flags & applicableFlags) != keyContainerPermissionAccessEntry.Flags)
                {
                    return(false);
                }
            }
            foreach (KeyContainerPermissionAccessEntry keyContainerPermissionAccessEntry2 in keyContainerPermission.AccessEntries)
            {
                KeyContainerPermissionFlags applicableFlags2 = KeyContainerPermission.GetApplicableFlags(keyContainerPermissionAccessEntry2, this);
                if ((applicableFlags2 & keyContainerPermissionAccessEntry2.Flags) != applicableFlags2)
                {
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>Creates a permission that is the union of the current permission and the specified permission.</summary>
        /// <param name="target">A permission to combine with the current permission. It must be of the same type as the current permission. </param>
        /// <returns>A new permission that represents the union of the current permission and the specified permission.</returns>
        /// <exception cref="T:System.ArgumentException">
        ///         <paramref name="target" /> is not <see langword="null" /> and does not specify a permission of the same type as the current permission. </exception>
        // Token: 0x060026C7 RID: 9927 RVA: 0x0008C6E8 File Offset: 0x0008A8E8
        public override IPermission Union(IPermission target)
        {
            if (target == null)
            {
                return(this.Copy());
            }
            if (!base.VerifyType(target))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", new object[]
                {
                    base.GetType().FullName
                }));
            }
            KeyContainerPermission keyContainerPermission = (KeyContainerPermission)target;

            if (this.IsUnrestricted() || keyContainerPermission.IsUnrestricted())
            {
                return(new KeyContainerPermission(PermissionState.Unrestricted));
            }
            KeyContainerPermissionFlags flags = this.m_flags | keyContainerPermission.m_flags;
            KeyContainerPermission      keyContainerPermission2 = new KeyContainerPermission(flags);

            foreach (KeyContainerPermissionAccessEntry accessEntry in this.AccessEntries)
            {
                keyContainerPermission2.AddAccessEntryAndUnion(accessEntry, keyContainerPermission);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry2 in keyContainerPermission.AccessEntries)
            {
                keyContainerPermission2.AddAccessEntryAndUnion(accessEntry2, this);
            }
            if (!keyContainerPermission2.IsEmpty())
            {
                return(keyContainerPermission2);
            }
            return(null);
        }
Beispiel #30
0
 public void ComputeSignature(CmsSigner signer, bool silent)
 {
     if (signer == null)
         throw new ArgumentNullException("signer");
     if (this.ContentInfo.Content.Length == 0)
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_Empty_Content"));
     if (SubjectIdentifierType.NoSignature == signer.SignerIdentifierType)
     {
         if (this.m_safeCryptMsgHandle != null && !this.m_safeCryptMsgHandle.IsInvalid)
             throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer"));
         this.Sign(signer, silent);
     }
     else
     {
         if (signer.Certificate == null)
         {
             if (silent)
                 throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound"));
             signer.Certificate = PkcsUtils.SelectSignerCertificate();
         }
         if (!signer.Certificate.HasPrivateKey)
             throw new CryptographicException(-2146893811);
         CspParameters parameters = new CspParameters();
         if (!X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters))
             throw new CryptographicException(SignedCms.SafeGetLastWin32Error());
         KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign);
         containerPermission.AccessEntries.Add(accessEntry);
         containerPermission.Demand();
         if (this.m_safeCryptMsgHandle == null || this.m_safeCryptMsgHandle.IsInvalid)
             this.Sign(signer, silent);
         else
             this.CoSign(signer, silent);
     }
 }
        private static KeyContainerPermissionFlags GetApplicableFlags(KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target)
        {
            KeyContainerPermissionFlags flags = KeyContainerPermissionFlags.NoFlags;
            bool applyDefaultFlags            = true;

            // If the entry exists in the target, return the flag of the target entry.
            int index = target.AccessEntries.IndexOf(accessEntry);

            if (index != -1)
            {
                flags = ((KeyContainerPermissionAccessEntry)target.AccessEntries[index]).Flags;
                return(flags);
            }

            // Intersect the flags in all the target entries that apply to the current access entry,
            foreach (KeyContainerPermissionAccessEntry targetAccessEntry in target.AccessEntries)
            {
                if (accessEntry.IsSubsetOf(targetAccessEntry))
                {
                    if (applyDefaultFlags == false)
                    {
                        flags &= targetAccessEntry.Flags;
                    }
                    else
                    {
                        flags             = targetAccessEntry.Flags;
                        applyDefaultFlags = false;
                    }
                }
            }

            // If no target entry applies to the current entry, the default global flag applies.
            if (applyDefaultFlags)
            {
                flags = target.Flags;
            }

            return(flags);
        }
Beispiel #32
0
        bool PFXExportCertStore(
            [In]     SafeCertStoreHandle    hCertStore,
            [In,Out] IntPtr                 pPFX,
            [In]     string                 szPassword,
            [In]     uint                   dwFlags) {

            if (hCertStore == null)
                throw new ArgumentNullException("hCertStore");
            if (hCertStore.IsInvalid)
                throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "hCertStore");

#if !FEATURE_CORESYSTEM
            //
            // Right now, we always demand KeyContainerPermission regardless of whether the PFX contains a private key or not.
            // We could avoid that by looping through the certs in the store and find out whether there are actually private keys.
            //
            if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export);
                kp.Demand();
            }
#endif

            return CAPIMethods.PFXExportCertStore(hCertStore,
                                                  pPFX,
                                                  szPassword,
                                                  dwFlags);
        }
 private void CounterSign(CmsSigner signer)
 {
     CspParameters parameters = new CspParameters();
     if (!System.Security.Cryptography.X509Certificates.X509Utils.GetPrivateKeyInfo(System.Security.Cryptography.X509Certificates.X509Utils.GetCertContext(signer.Certificate), ref parameters))
     {
         throw new CryptographicException(Marshal.GetLastWin32Error());
     }
     KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
     KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Sign | KeyContainerPermissionFlags.Open);
     permission.AccessEntries.Add(accessEntry);
     permission.Demand();
     uint dwIndex = (uint) PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0);
     System.Security.Cryptography.SafeLocalAllocHandle handle = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO))));
     System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO structure = PkcsUtils.CreateSignerEncodeInfo(signer);
     try
     {
         Marshal.StructureToPtr(structure, handle.DangerousGetHandle(), false);
         if (!System.Security.Cryptography.CAPI.CryptMsgCountersign(this.m_signedCms.GetCryptMsgHandle(), dwIndex, 1, handle.DangerousGetHandle()))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
         this.m_signedCms.ReopenToDecode();
     }
     finally
     {
         Marshal.DestroyStructure(handle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO));
         handle.Dispose();
         structure.Dispose();
     }
     PkcsUtils.AddCertsToMessage(this.m_signedCms.GetCryptMsgHandle(), this.m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer));
 }
 private void AddAccessEntryAndIntersect (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) {
     KeyContainerPermissionAccessEntry newAccessEntry = new KeyContainerPermissionAccessEntry(accessEntry);
     newAccessEntry.Flags &= GetApplicableFlags(accessEntry, target);
     AccessEntries.Add(newAccessEntry);
 }
Beispiel #35
0
        bool CryptAcquireContext(
            [In,Out] ref SafeCryptProvHandle                  hCryptProv,
            [In]     [MarshalAs(UnmanagedType.LPStr)] string  pwszContainer,
            [In]     [MarshalAs(UnmanagedType.LPStr)] string  pwszProvider,
            [In]     uint                                     dwProvType,
            [In]     uint                                     dwFlags) {

            CspParameters parameters = new CspParameters();
            parameters.ProviderName = pwszProvider;
            parameters.KeyContainerName = pwszContainer;
            parameters.ProviderType = (int) dwProvType;
            parameters.KeyNumber = -1;
            parameters.Flags = (CspProviderFlags) ((dwFlags & CAPI.CRYPT_MACHINE_KEYSET) == CAPI.CRYPT_MACHINE_KEYSET ? CspProviderFlags.UseMachineKeyStore : 0);

#if !FEATURE_CORESYSTEM
            if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open);
                kp.AccessEntries.Add(entry);
                kp.Demand();
            }
#endif

            bool rc = CAPIMethods.CryptAcquireContext(ref hCryptProv,
                                                      pwszContainer,
                                                      pwszProvider,
                                                      dwProvType,
                                                      dwFlags);

            if (!rc && Marshal.GetLastWin32Error() == CAPI.NTE_BAD_KEYSET) {
                rc = CAPIMethods.CryptAcquireContext(ref hCryptProv,
                                                     pwszContainer,
                                                     pwszProvider,
                                                     dwProvType,
                                                     dwFlags | CAPI.CRYPT_NEWKEYSET);
            }

            return rc;
        }
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override void ImportParameters(RSAParameters parameters) {
            // Free the current key handle
            if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) {
                _safeKeyHandle.Dispose();
                _safeKeyHandle = null;
            }

            RSACspObject rsaCspObject = RSAStructToObject(parameters);
            _safeKeyHandle = SafeKeyHandle.InvalidHandle;

            if (IsPublic(parameters)) {
                // Use our CRYPT_VERIFYCONTEXT handle, CRYPT_EXPORTABLE is not applicable to public only keys, so pass false
                Utils._ImportKey(Utils.StaticProvHandle, Constants.CALG_RSA_KEYX, (CspProviderFlags) 0, rsaCspObject, ref _safeKeyHandle);
            } else {
                if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                    KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                    KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Import);
                    kp.AccessEntries.Add(entry);
                    kp.Demand();
                }
                if (_safeProvHandle == null)
                    _safeProvHandle = Utils.CreateProvHandle(_parameters, _randomKeyContainer);
                // Now, import the key into the CSP; _ImportKey will check for failures.
                Utils._ImportKey(_safeProvHandle, Constants.CALG_RSA_KEYX, _parameters.Flags, rsaCspObject, ref _safeKeyHandle);
            }
        }
        public override IPermission Union (IPermission target) {
            if (target == null)
                return this.Copy();

            if (!VerifyType(target))
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));            

            KeyContainerPermission operand = (KeyContainerPermission) target;    
            if (this.IsUnrestricted() || operand.IsUnrestricted())
                return new KeyContainerPermission(PermissionState.Unrestricted);

            KeyContainerPermissionFlags flags_union = (KeyContainerPermissionFlags) (m_flags | operand.m_flags);
            KeyContainerPermission cp = new KeyContainerPermission(flags_union);
            foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
                cp.AddAccessEntryAndUnion(accessEntry, operand);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) {
                cp.AddAccessEntryAndUnion(accessEntry, this);
            }
            return cp.IsEmpty() ? null : cp;
        }
Beispiel #38
0
        internal static void GetKeyPairHelper (CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) {
            SafeProvHandle TempFetchedProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer);

#if FEATURE_MACL
            // If the user wanted to set the security descriptor on the provider context, apply it now.
            if (parameters.CryptoKeySecurity != null) {
                KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl);
                kp.AccessEntries.Add(entry);
                kp.Demand();
                SetKeySetSecurityInfo(TempFetchedProvHandle, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections);
            }
#endif //FEATURE_MACL

#if FEATURE_X509_SECURESTRINGS
            // If the user wanted to specify a PIN or HWND for a smart card CSP, apply those settings now.
            if (parameters.ParentWindowHandle != IntPtr.Zero)
                SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_CLIENT_HWND, parameters.ParentWindowHandle);
            else if (parameters.KeyPassword != null) {
                IntPtr szPassword = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword);
                try {
                    SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_PIN, szPassword);
                }
                finally {
                    if (szPassword != IntPtr.Zero)
                        Marshal.ZeroFreeCoTaskMemAnsi(szPassword);
                }
            }
#endif //FEATURE_X509_SECURESTRINGS

            safeProvHandle = TempFetchedProvHandle;

            // If the key already exists, use it, else generate a new one
            SafeKeyHandle TempFetchedKeyHandle = SafeKeyHandle.InvalidHandle;
            int hr = Utils._GetUserKey(safeProvHandle, parameters.KeyNumber, ref TempFetchedKeyHandle);
            if (hr != Constants.S_OK) {
                if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || hr != Constants.NTE_NO_KEY)
                    throw new CryptographicException(hr);
                // _GenerateKey will check for failures and throw an exception
                Utils._GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref TempFetchedKeyHandle);
            }

            // check that this is indeed an RSA/DSS key.
            byte[] algid = (byte[]) Utils._GetKeyParameter(TempFetchedKeyHandle, Constants.CLR_ALGID);
            int dwAlgId = (algid[0] | (algid[1] << 8) | (algid[2] << 16) | (algid[3] << 24));
            if ((keyType == CspAlgorithmType.Rsa && dwAlgId != Constants.CALG_RSA_KEYX && dwAlgId != Constants.CALG_RSA_SIGN) ||
                    (keyType == CspAlgorithmType.Dss && dwAlgId != Constants.CALG_DSS_SIGN)) {
                TempFetchedKeyHandle.Dispose();
                throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec"));
            }

            safeKeyHandle = TempFetchedKeyHandle;
        }
 [System.Security.SecuritySafeCritical]  // auto-generated
 public override RSAParameters ExportParameters (bool includePrivateParameters) {
     GetKeyPair();
     if (includePrivateParameters) {
         if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
             KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
             KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Export);
             kp.AccessEntries.Add(entry);
             kp.Demand();
         }
     }
     RSACspObject rsaCspObject = new RSACspObject();
     int blobType = includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB;
     // _ExportKey will check for failures and throw an exception
     Utils._ExportKey(_safeKeyHandle, blobType, rsaCspObject);
     return RSAObjectToStruct(rsaCspObject);
 }
Beispiel #40
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static void ImportCspBlobHelper (CspAlgorithmType keyType, byte[] keyBlob, bool publicOnly, ref CspParameters parameters, bool randomKeyContainer, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) {
            // Free the current key handle
            if (safeKeyHandle != null && !safeKeyHandle.IsClosed)
                safeKeyHandle.Dispose();
            safeKeyHandle = SafeKeyHandle.InvalidHandle;

            if (publicOnly) {
                parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, keyType == CspAlgorithmType.Dss ? Utils.StaticDssProvHandle : Utils.StaticProvHandle, (CspProviderFlags) 0, ref safeKeyHandle);
            } else {
                if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                    KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                    KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Import);
                    kp.AccessEntries.Add(entry);
                    kp.Demand();
                }
                if (safeProvHandle == null)
                    safeProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer);
                parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, safeProvHandle, parameters.Flags, ref safeKeyHandle);
            }
        }
 /// <summary>用指定的访问权限初始化 <see cref="T:System.Security.Permissions.KeyContainerPermission" /> 类的新实例。</summary>
 /// <param name="flags">
 /// <see cref="T:System.Security.Permissions.KeyContainerPermissionFlags" /> 值的按位组合。</param>
 /// <exception cref="T:System.ArgumentException">
 /// <paramref name="flags" /> 不是 <see cref="T:System.Security.Permissions.KeyContainerPermissionFlags" /> 值的有效组合。</exception>
 public KeyContainerPermission(KeyContainerPermissionFlags flags)
 {
     KeyContainerPermission.VerifyFlags(flags);
     this.m_flags         = flags;
     this.m_accessEntries = new KeyContainerPermissionAccessEntryCollection(this.m_flags);
 }
        private static KeyContainerPermissionFlags GetApplicableFlags(KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target)
        {
            KeyContainerPermissionFlags containerPermissionFlags = KeyContainerPermissionFlags.NoFlags;
            bool flag  = true;
            int  index = target.AccessEntries.IndexOf(accessEntry);

            if (index != -1)
            {
                return(target.AccessEntries[index].Flags);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry1 in target.AccessEntries)
            {
                if (accessEntry.IsSubsetOf(accessEntry1))
                {
                    if (!flag)
                    {
                        containerPermissionFlags &= accessEntry1.Flags;
                    }
                    else
                    {
                        containerPermissionFlags = accessEntry1.Flags;
                        flag = false;
                    }
                }
            }
            if (flag)
            {
                containerPermissionFlags = target.Flags;
            }
            return(containerPermissionFlags);
        }
        public override IPermission CreatePermission() {
            if (m_unrestricted) {
                return new KeyContainerPermission(PermissionState.Unrestricted);
            } else {
                if (KeyContainerPermissionAccessEntry.IsUnrestrictedEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec))
                    return new KeyContainerPermission(m_flags);

                // create a KeyContainerPermission with a single access entry.
                KeyContainerPermission cp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec, m_flags);
                cp.AccessEntries.Add(accessEntry);
                return cp;
            }
        }
        internal byte[] SignHash(byte[] rgbHash, int calgHash) {
            Contract.Requires(rgbHash != null);

            GetKeyPair();
            if (!CspKeyContainerInfo.RandomlyGenerated) {
                if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                    KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                    KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Sign);
                    kp.AccessEntries.Add(entry);
                    kp.Demand();
                }
            }
            return Utils.SignValue(_safeKeyHandle, _parameters.KeyNumber, Constants.CALG_RSA_SIGN, calgHash, rgbHash);
        }
        public override IPermission Intersect (IPermission target) {
            if (target == null)
                return null;

            if (!VerifyType(target))
                throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));

            KeyContainerPermission operand = (KeyContainerPermission) target;
            if (this.IsEmpty() || operand.IsEmpty())
                return null;

            KeyContainerPermissionFlags flags_intersect = operand.m_flags & this.m_flags;
            KeyContainerPermission cp = new KeyContainerPermission(flags_intersect);
            foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
                cp.AddAccessEntryAndIntersect(accessEntry, operand);
            }
            foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) {
                cp.AddAccessEntryAndIntersect(accessEntry, this);
            }
            return cp.IsEmpty() ? null : cp;
        }
Beispiel #46
0
 [System.Security.SecurityCritical]  // auto-generated
 internal static byte[] ExportCspBlobHelper (bool includePrivateParameters, CspParameters parameters, SafeKeyHandle safeKeyHandle) {
     if (includePrivateParameters) {
         if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
             KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
             KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Export);
             kp.AccessEntries.Add(entry);
             kp.Demand();
         }
     }
     byte[] blob = null;
     Utils.ExportCspBlob(safeKeyHandle, includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB, JitHelpers.GetObjectHandleOnStack(ref blob));
     return blob;
 }
        public override IPermission Copy () {
            if (this.IsEmpty())
                return null;

            KeyContainerPermission cp = new KeyContainerPermission((KeyContainerPermissionFlags)m_flags);
            foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
                cp.AccessEntries.Add(accessEntry);
            }
            return cp;
        }
Beispiel #48
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        private void LoadCertificateFromBlob (byte[] rawData, object password, X509KeyStorageFlags keyStorageFlags) {
            if (rawData == null || rawData.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullArray"), "rawData");
            Contract.EndContractBlock();

            X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertBlobType(rawData));
#if !FEATURE_CORECLR && !FEATURE_PAL
            if (contentType == X509ContentType.Pkcs12 &&
                (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) {
                KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create);
                kp.Demand();
            }
#endif // !FEATURE_CORECLR && !FEATURE_PAL
            uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
            IntPtr szPassword = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                szPassword = X509Utils.PasswordToHGlobalUni(password);
                X509Utils._LoadCertFromBlob(rawData,
                                            szPassword,
                                            dwFlags,
#if FEATURE_CORECLR
                                            false,
#else // FEATURE_CORECLR
                                            (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true,
#endif // FEATURE_CORECLR else
                                            ref m_safeCertContext);
            }
            finally {
                if (szPassword != IntPtr.Zero)
                    Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
            }
        }
        private static KeyContainerPermissionFlags GetApplicableFlags (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) {
            KeyContainerPermissionFlags flags = KeyContainerPermissionFlags.NoFlags;
            bool applyDefaultFlags = true;

            // If the entry exists in the target, return the flag of the target entry.
            int index = target.AccessEntries.IndexOf(accessEntry);
            if (index != -1) {
                flags = ((KeyContainerPermissionAccessEntry)target.AccessEntries[index]).Flags;
                return flags;
            }

            // Intersect the flags in all the target entries that apply to the current access entry, 
            foreach (KeyContainerPermissionAccessEntry targetAccessEntry in target.AccessEntries) {
                if (accessEntry.IsSubsetOf(targetAccessEntry)) {
                    if (applyDefaultFlags == false) {
                        flags &= targetAccessEntry.Flags;
                    } else {
                        flags = targetAccessEntry.Flags;
                        applyDefaultFlags = false;
                    }
                }
            }

            // If no target entry applies to the current entry, the default global flag applies.
            if (applyDefaultFlags)
                flags = target.Flags;

            return flags;
        }
        [System.Security.SecuritySafeCritical]  // auto-generated
        public byte[] SignHash(byte[] rgbHash, string str) {
            if (rgbHash == null)
                throw new ArgumentNullException("rgbHash");
            Contract.EndContractBlock();
            if (PublicOnly)
                throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NoPrivateKey"));

            int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm);
            if (rgbHash.Length != _sha1.HashSize / 8)
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHashSize", "SHA1", _sha1.HashSize / 8));

            GetKeyPair();
            if (!CspKeyContainerInfo.RandomlyGenerated) {
                KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Sign);
                kp.AccessEntries.Add(entry);
                kp.Demand();
            }
            return Utils.SignValue(_safeKeyHandle, _parameters.KeyNumber, Constants.CALG_DSS_SIGN, calgHash, rgbHash);
        }
Beispiel #51
0
        SafeCertStoreHandle PFXImportCertStore(
            [In]     uint      dwObjectType,
            [In]     object    pvObject,
            [In]     string    szPassword,
            [In]     uint      dwFlags,
            [In]     bool      persistKeyContainers) {

            if (pvObject == null)
                throw new ArgumentNullException("pvObject");

            byte[] pbData = null;
            if (dwObjectType == CERT_QUERY_OBJECT_FILE) {
                pbData = File.ReadAllBytes((string)pvObject);
            } else {
                pbData = (byte[]) pvObject;
            }

#if !FEATURE_CORESYSTEM
            if (persistKeyContainers) {
                //
                // Right now, we always demand KeyContainerPermission regardless of whether the PFX contains a private key or not.
                // We could avoid that by looping through the certs in the store and find out whether there are actually private keys.
                //
                if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                    KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create);
                    kp.Demand();
                }
            }
#endif

            SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle;
            GCHandle handle = GCHandle.Alloc(pbData, GCHandleType.Pinned);
            IntPtr ptr = handle.AddrOfPinnedObject();

            try {
                CRYPTOAPI_BLOB certBlob;
                certBlob.cbData = (uint) pbData.Length;
                certBlob.pbData = ptr;

                safeCertStoreHandle = CAPIMethods.PFXImportCertStore(new IntPtr(&certBlob),
                                                                     szPassword,
                                                                     dwFlags);
            }

            finally {
                if (handle.IsAllocated)
                   handle.Free();
            }

            if (!safeCertStoreHandle.IsInvalid) {
                //
                // If the user did not want us to persist private keys, then we should loop through all
                // the certificates in the collection and set our custom CERT_DELETE_KEYSET_PROP_ID property
                // so the key container will be deleted when the cert contexts will go away.
                //

                if (persistKeyContainers == false) {
                    IntPtr pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, IntPtr.Zero);
                    while (pEnumContext != IntPtr.Zero) {
                        CAPI.CRYPTOAPI_BLOB blob = new CAPI.CRYPTOAPI_BLOB();
                        if (!CAPI.CertSetCertificateContextProperty(pEnumContext,
                                                                    CERT_DELETE_KEYSET_PROP_ID,
                                                                    CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG, // we don't want this property to be persisted.
                                                                    new IntPtr(&blob)))
                            throw new CryptographicException(Marshal.GetLastWin32Error());
                        pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, pEnumContext);
                    }
                }
            }

            return safeCertStoreHandle;
        }
 /// <internalonly/>
 int IBuiltInPermission.GetTokenIndex()
 {
     return(KeyContainerPermission.GetTokenIndex());
 }
Beispiel #53
0
 internal static SafeProvHandle CreateProvHandle (CspParameters parameters, bool randomKeyContainer) {
     SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle;
     int hr = Utils._OpenCSP(parameters, 0, ref safeProvHandle);
     KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
     if (hr != Constants.S_OK) {
         // If UseExistingKey flag is used and the key container does not exist
         // throw an exception without attempting to create the container.
         if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || (hr != Constants.NTE_KEYSET_NOT_DEF && hr != Constants.NTE_BAD_KEYSET && hr != Constants.NTE_FILENOTFOUND))
             throw new CryptographicException(hr);
         if (!randomKeyContainer) {
             if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                 KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Create);
                 kp.AccessEntries.Add(entry);
                 kp.Demand();
             }
         }
         Utils._CreateCSP(parameters, randomKeyContainer, ref safeProvHandle);
     } else {
         if (!randomKeyContainer) {
             if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                 KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open);
                 kp.AccessEntries.Add(entry);
                 kp.Demand();
             }
         }
     }
     return safeProvHandle;
 }
        private void AddAccessEntryAndIntersect(KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target)
        {
            KeyContainerPermissionAccessEntry newAccessEntry = new KeyContainerPermissionAccessEntry(accessEntry);

            newAccessEntry.Flags &= GetApplicableFlags(accessEntry, target);
            AccessEntries.Add(newAccessEntry);
        }
        [System.Security.SecuritySafeCritical]  // auto-generated
        public byte [] Decrypt(byte[] rgb, bool fOAEP) {
            if (rgb == null)
                throw new ArgumentNullException("rgb");
            Contract.EndContractBlock();

            GetKeyPair();

            // size check -- must be at most the modulus size
            if (rgb.Length > (KeySize / 8))
                throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8));

            if (!CspKeyContainerInfo.RandomlyGenerated) {
                if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                    KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                    KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Decrypt);
                    kp.AccessEntries.Add(entry);
                    kp.Demand();
                }
            }

            byte[] decryptedKey = null;
            DecryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack(ref decryptedKey));
            return decryptedKey;
        }
Beispiel #56
0
        private static KeyContainerPermissionFlags GetApplicableFlags(KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target)
        {
            KeyContainerPermissionFlags noFlags = KeyContainerPermissionFlags.NoFlags;
            bool flag  = true;
            int  index = target.AccessEntries.IndexOf(accessEntry);

            if (index != -1)
            {
                return(target.AccessEntries[index].Flags);
            }
            KeyContainerPermissionAccessEntryEnumerator enumerator = target.AccessEntries.GetEnumerator();

            while (enumerator.MoveNext())
            {
                KeyContainerPermissionAccessEntry current = enumerator.Current;
                if (accessEntry.IsSubsetOf(current))
                {
                    if (!flag)
                    {
                        noFlags &= current.Flags;
                    }
                    else
                    {
                        noFlags = current.Flags;
                        flag    = false;
                    }
                }
            }
            if (flag)
            {
                noFlags = target.Flags;
            }
            return(noFlags);
        }
Beispiel #57
0
        [System.Security.SecurityCritical]  // auto-generated
        private byte[] ExportHelper (X509ContentType contentType, object password) {
            switch(contentType) {
            case X509ContentType.Cert:
                break;
#if FEATURE_CORECLR
            case (X509ContentType)0x02 /* X509ContentType.SerializedCert */:
            case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */:
                throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"),
                    new NotSupportedException());
#else // FEATURE_CORECLR
            case X509ContentType.SerializedCert:
                break;
#if !FEATURE_PAL
            case X509ContentType.Pkcs12:
                KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export);
                kp.Demand();
                break;
#endif // !FEATURE_PAL
#endif // FEATURE_CORECLR else
            default:
                throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"));
            }

#if !FEATURE_CORECLR
            IntPtr szPassword = IntPtr.Zero;
            byte[] encodedRawData = null;
            SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this);

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                szPassword = X509Utils.PasswordToHGlobalUni(password);
                encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword);
            }
            finally {
                if (szPassword != IntPtr.Zero)
                    Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
                safeCertStoreHandle.Dispose();
            }
            if (encodedRawData == null)
                throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed"));
            return encodedRawData;
#else // !FEATURE_CORECLR
            return RawData;
#endif // !FEATURE_CORECLR
        }
Beispiel #58
0
        private void AddAccessEntryAndUnion(KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target)
        {
            KeyContainerPermissionAccessEntry entry;

            entry = new KeyContainerPermissionAccessEntry(accessEntry)
            {
                Flags = entry.Flags | GetApplicableFlags(accessEntry, target)
            };
            this.AccessEntries.Add(entry);
        }
Beispiel #59
0
        private void LoadCertificateFromFile (string fileName, object password, X509KeyStorageFlags keyStorageFlags) {
            if (fileName == null)
                throw new ArgumentNullException("fileName");
            Contract.EndContractBlock();

            string fullPath = Path.GetFullPathInternal(fileName);
            new FileIOPermission (FileIOPermissionAccess.Read, fullPath).Demand();
            X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertFileType(fileName));
#if !FEATURE_CORECLR && !FEATURE_PAL
            if (contentType == X509ContentType.Pkcs12 &&
                (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) {
                KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create);
                kp.Demand();
            }
#endif // !FEATURE_CORECLR && !FEATURE_PAL
            uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
            IntPtr szPassword = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                szPassword = X509Utils.PasswordToHGlobalUni(password);
                X509Utils._LoadCertFromFile(fileName,
                                            szPassword,
                                            dwFlags,
#if FEATURE_CORECLR
                                            false,
#else // FEATURE_CORECLR
                                            (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true,
#endif // FEATURE_CORECLR else
                                            ref m_safeCertContext);
            }
            finally {
                if (szPassword != IntPtr.Zero)
                    Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
            }
        }
 [System.Security.SecuritySafeCritical]  // auto-generated
 public override DSAParameters ExportParameters (bool includePrivateParameters) {
     GetKeyPair();
     if (includePrivateParameters) {
         KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Export);
         kp.AccessEntries.Add(entry);
         kp.Demand();
     }
     DSACspObject dsaCspObject = new DSACspObject();
     int blobType = includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB;
     // _ExportKey will check for failures and throw an exception
     Utils._ExportKey(_safeKeyHandle, blobType, dsaCspObject);
     return DSAObjectToStruct(dsaCspObject);
 }