internal static CngKey FromXml(string xml)
        {
            CngKey key;

            using (TextReader reader = new StringReader(xml))
            {
                using (XmlTextReader reader2 = new XmlTextReader(reader))
                {
                    BigInteger     integer;
                    BigInteger     integer2;
                    XPathNavigator navigator = new XPathDocument(reader2).CreateNavigator();
                    if (!navigator.MoveToFirstChild())
                    {
                        throw new ArgumentException(System.SR.GetString("Cryptography_MissingDomainParameters"));
                    }
                    CngAlgorithm algorithm = ReadAlgorithm(navigator);
                    if (!navigator.MoveToNext(XPathNodeType.Element))
                    {
                        throw new ArgumentException(System.SR.GetString("Cryptography_MissingPublicKey"));
                    }
                    ReadPublicKey(navigator, out integer, out integer2);
                    key = CngKey.Import(NCryptNative.BuildEccPublicBlob(algorithm.Algorithm, integer, integer2), CngKeyBlobFormat.EccPublicBlob);
                }
            }
            return(key);
        }
Exemplo n.º 2
0
        public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed)
        {
            Contract.Ensures(Contract.Result <byte[]>() != null);

            if (otherPartyPublicKey == null)
            {
                throw new ArgumentNullException("otherPartyPublicKey");
            }
            if (prfLabel == null)
            {
                throw new ArgumentNullException("prfLabel");
            }
            if (prfSeed == null)
            {
                throw new ArgumentNullException("prfSeed");
            }

            using (SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey))
            {
                return(NCryptNative.DeriveKeyMaterialTls(
                           secretAgreement,
                           prfLabel,
                           prfSeed,
                           NCryptNative.SecretAgreementFlags.None));
            }
        }
Exemplo n.º 3
0
        public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
        {
            if (keyBlob == null)
            {
                throw new ArgumentNullException("keyBlob");
            }
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (!NCryptNative.NCryptSupported)
            {
                throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
            }
            if ((format != CngKeyBlobFormat.EccPublicBlob) && (format != CngKeyBlobFormat.GenericPublicBlob))
            {
                new KeyContainerPermission(KeyContainerPermissionFlags.Import).Demand();
            }
            SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);

            return(new CngKey(kspHandle, NCryptNative.ImportKey(kspHandle, keyBlob, format.Format))
            {
                IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob
            });
        }
Exemplo n.º 4
0
        public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
        {
            if (keyName == null)
            {
                throw new ArgumentNullException("keyName");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (!NCryptNative.NCryptSupported)
            {
                throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
            }
            KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Open)
            {
                ProviderName = provider.Provider
            };
            KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);

            permission.AccessEntries.Add(accessEntry);
            permission.Demand();
            SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);

            return(new CngKey(kspHandle, NCryptNative.OpenKey(kspHandle, keyName, openOptions)));
        }
Exemplo n.º 5
0
        public override byte[] DeriveKeyFromHmac(
            ECDiffieHellmanPublicKey otherPartyPublicKey,
            HashAlgorithmName hashAlgorithm,
            byte[] hmacKey,
            byte[] secretPrepend,
            byte[] secretAppend)
        {
            Contract.Ensures(Contract.Result <byte[]>() != null);

            if (otherPartyPublicKey == null)
            {
                throw new ArgumentNullException("otherPartyPublicKey");
            }
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_HashAlgorithmNameNullOrEmpty), "hashAlgorithm");
            }

            using (SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey))
            {
                NCryptNative.SecretAgreementFlags flags = hmacKey == null ?
                                                          NCryptNative.SecretAgreementFlags.UseSecretAsHmacKey :
                                                          NCryptNative.SecretAgreementFlags.None;

                return(NCryptNative.DeriveKeyMaterialHmac(
                           secretAgreement,
                           hashAlgorithm.Name,
                           hmacKey,
                           secretPrepend,
                           secretAppend,
                           flags));
            }
        }
Exemplo n.º 6
0
 private static void SetKeyProperties(SafeNCryptKeyHandle keyHandle, CngKeyCreationParameters creationParameters)
 {
     if (creationParameters.ExportPolicy.HasValue)
     {
         NCryptNative.SetProperty(keyHandle, "Export Policy", creationParameters.ExportPolicy.Value, CngPropertyOptions.None | CngPropertyOptions.Persist);
     }
     if (creationParameters.KeyUsage.HasValue)
     {
         NCryptNative.SetProperty(keyHandle, "Key Usage", creationParameters.KeyUsage.Value, CngPropertyOptions.None | CngPropertyOptions.Persist);
     }
     if (creationParameters.ParentWindowHandle != IntPtr.Zero)
     {
         NCryptNative.SetProperty <IntPtr>(keyHandle, "HWND Handle", creationParameters.ParentWindowHandle, CngPropertyOptions.None);
     }
     if (creationParameters.UIPolicy != null)
     {
         NCryptNative.NCRYPT_UI_POLICY ncrypt_ui_policy = new NCryptNative.NCRYPT_UI_POLICY {
             dwVersion        = 1,
             dwFlags          = creationParameters.UIPolicy.ProtectionLevel,
             pszCreationTitle = creationParameters.UIPolicy.CreationTitle,
             pszFriendlyName  = creationParameters.UIPolicy.FriendlyName,
             pszDescription   = creationParameters.UIPolicy.Description
         };
         NCryptNative.SetProperty <NCryptNative.NCRYPT_UI_POLICY>(keyHandle, "UI Policy", ncrypt_ui_policy, CngPropertyOptions.None | CngPropertyOptions.Persist);
         if (creationParameters.UIPolicy.UseContext != null)
         {
             NCryptNative.SetProperty(keyHandle, "Use Context", creationParameters.UIPolicy.UseContext, CngPropertyOptions.None | CngPropertyOptions.Persist);
         }
     }
     foreach (CngProperty property in creationParameters.ParametersNoDemand)
     {
         NCryptNative.SetProperty(keyHandle, property.Name, property.Value, property.Options);
     }
 }
Exemplo n.º 7
0
        public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
        {
            Contract.Ensures(Contract.Result <CngKey>() != null);

            if (keyName == null)
            {
                throw new ArgumentNullException("keyName");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            // Make sure that NCrypt is supported on this platform
            if (!NCryptNative.NCryptSupported)
            {
                throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
            }

            // Ensure the user has access to the key name
            KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Open);

            access.ProviderName = provider.Provider;

            KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);

            permission.AccessEntries.Add(access);
            permission.Demand();

            // Open the key
            SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);
            SafeNCryptKeyHandle      keyHandle = NCryptNative.OpenKey(kspHandle, keyName, openOptions);

            return(new CngKey(kspHandle, keyHandle));
        }
Exemplo n.º 8
0
        public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (padding == null)
            {
                throw new ArgumentNullException("padding");
            }

            if (padding == RSAEncryptionPadding.Pkcs1)
            {
                return(NCryptNative.EncryptDataPkcs1(KeyHandle, data));
            }
            else if (padding.Mode == RSAEncryptionPaddingMode.Oaep)
            {
                return(NCryptNative.EncryptDataOaep(KeyHandle, data, padding.OaepHashAlgorithm.Name));
            }
            else
            {
                // no other padding possibilities at present, but we might version independently from more being added.
                throw new CryptographicException(SR.GetString(SR.Cryptography_UnsupportedPaddingMode));
            };
        }
Exemplo n.º 9
0
        private static void WritePublicKeyValue(XmlWriter writer, CngKey key)
        {
            Contract.Requires(writer != null);
            Contract.Requires(key != null && (key.AlgorithmGroup == CngAlgorithmGroup.ECDsa || key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman));

            writer.WriteStartElement(PublicKeyRoot);

            byte[]     exportedKey = key.Export(CngKeyBlobFormat.EccPublicBlob);
            BigInteger x;
            BigInteger y;

            NCryptNative.UnpackEccPublicBlob(exportedKey, out x, out y);

            writer.WriteStartElement(XElement);
            writer.WriteAttributeString(ValueAttribute, x.ToString("R", CultureInfo.InvariantCulture));
            writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue);
            writer.WriteEndElement();   // </X>

            writer.WriteStartElement(YElement);
            writer.WriteAttributeString(ValueAttribute, y.ToString("R", CultureInfo.InvariantCulture));
            writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue);
            writer.WriteEndElement();   // </Y>

            writer.WriteEndElement();   // </PublicKey>
        }
Exemplo n.º 10
0
        public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }
            if (String.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_HashAlgorithmNameNullOrEmpty), "hashAlgorithm");
            }
            if (padding == null)
            {
                throw new ArgumentNullException("padding");
            }

            // Keep a local copy of the key.
            CngKey key = Key;
            SafeNCryptKeyHandle keyHandle = key.Handle;

            if (padding == RSASignaturePadding.Pkcs1)
            {
                return(NCryptNative.SignHashPkcs1(keyHandle, hash, hashAlgorithm.Name));
            }
            else if (padding == RSASignaturePadding.Pss)
            {
                return(NCryptNative.SignHashPss(keyHandle, hash, hashAlgorithm.Name, hash.Length));
            }
            else
            {
                // no other padding possibilities at present, but we might version independently from more being added.
                throw new CryptographicException(SR.GetString(SR.Cryptography_UnsupportedPaddingMode));
            }
        }
Exemplo n.º 11
0
        public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }
            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }
            if (String.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_HashAlgorithmNameNullOrEmpty), "hashAlgorithm");
            }
            if (padding == null)
            {
                throw new ArgumentNullException("padding");
            }

            if (padding == RSASignaturePadding.Pkcs1)
            {
                return(NCryptNative.VerifySignaturePkcs1(KeyHandle, hash, hashAlgorithm.Name, signature));
            }
            else if (padding == RSASignaturePadding.Pss)
            {
                return(NCryptNative.VerifySignaturePss(KeyHandle, hash, hashAlgorithm.Name, hash.Length, signature));
            }
            else
            {
                // no other padding possibilities at present, but we might version independently from more being added.
                throw new CryptographicException(SR.GetString(SR.Cryptography_UnsupportedPaddingMode));
            }
        }
Exemplo n.º 12
0
        public override byte[] SignHash(byte[] hash)
        {
            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }

            // Make sure we're allowed to sign using this key
            KeyContainerPermission permission = Key.BuildKeyContainerPermission(KeyContainerPermissionFlags.Sign);

            if (permission != null)
            {
                permission.Demand();
            }

            // Now that know we have permission to use this key for signing, pull the key value out, which
            // will require unmanaged code permission
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();

            // This looks odd, but the key handle is actually a duplicate so we need to dispose it
            using (SafeNCryptKeyHandle keyHandle = Key.Handle) {
                CodeAccessPermission.RevertAssert();

                return(NCryptNative.SignHash(keyHandle, hash));
            }
        }
Exemplo n.º 13
0
        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));
        }
Exemplo n.º 14
0
        public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options)
        {
            bool flag2;

            if (keyName == null)
            {
                throw new ArgumentNullException("keyName");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (!NCryptNative.NCryptSupported)
            {
                throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
            }
            using (SafeNCryptProviderHandle handle = NCryptNative.OpenStorageProvider(provider.Provider))
            {
                using (SafeNCryptKeyHandle handle2 = null)
                {
                    NCryptNative.ErrorCode code = NCryptNative.UnsafeNativeMethods.NCryptOpenKey(handle, out handle2, keyName, 0, options);
                    bool flag = (code == NCryptNative.ErrorCode.KeyDoesNotExist) || (code == NCryptNative.ErrorCode.NotFound);
                    if ((code != NCryptNative.ErrorCode.Success) && !flag)
                    {
                        throw new CryptographicException((int)code);
                    }
                    flag2 = code == NCryptNative.ErrorCode.Success;
                }
            }
            return(flag2);
        }
Exemplo n.º 15
0
        internal static SafeNCryptKeyHandle ImportKeyBlob(
            string blobType,
            byte[] keyBlob,
            string curveName,
            SafeNCryptProviderHandle provider)
        {
            SafeNCryptKeyHandle keyHandle;

            var desc = new Interop.BCrypt.BCryptBufferDesc();
            var buff = new Interop.BCrypt.BCryptBuffer();

            IntPtr descPtr      = IntPtr.Zero;
            IntPtr buffPtr      = IntPtr.Zero;
            IntPtr curveNamePtr = IntPtr.Zero;

            try
            {
                curveNamePtr    = Marshal.StringToHGlobalUni(curveName);
                descPtr         = Marshal.AllocHGlobal(Marshal.SizeOf(desc));
                buffPtr         = Marshal.AllocHGlobal(Marshal.SizeOf(buff));
                buff.cbBuffer   = (curveName.Length + 1) * 2; // Add 1 for null terminator
                buff.BufferType = Interop.BCrypt.NCryptBufferDescriptors.NCRYPTBUFFER_ECC_CURVE_NAME;
                buff.pvBuffer   = curveNamePtr;
                Marshal.StructureToPtr(buff, buffPtr, false);

                desc.cBuffers  = 1;
                desc.pBuffers  = buffPtr;
                desc.ulVersion = Interop.BCrypt.BCRYPTBUFFER_VERSION;
                Marshal.StructureToPtr(desc, descPtr, false);

                keyHandle = NCryptNative.ImportKey(
                    provider,
                    keyBlob,
                    blobType,
                    descPtr);
            }
            catch (CryptographicException e)
            {
                if (e.HResult == (int)ErrorCode.NTE_INVALID_PARAMETER)
                {
                    throw new PlatformNotSupportedException(
                              SR.GetString(SR.Cryptography_CurveNotSupported, curveName),
                              e);
                }

                throw;
            }
            finally
            {
                Marshal.FreeHGlobal(descPtr);
                Marshal.FreeHGlobal(buffPtr);
                Marshal.FreeHGlobal(curveNamePtr);
            }

            return(keyHandle);
        }
Exemplo n.º 16
0
        public override byte[] CreateSignature(byte[] rgbHash)
        {
            if (rgbHash == null)
            {
                throw new ArgumentNullException("rgbHash");
            }

            rgbHash = AdjustHashSizeIfNecessary(rgbHash);
            return(NCryptNative.SignHash(KeyHandle, rgbHash, rgbHash.Length * 2));
        }
Exemplo n.º 17
0
        internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format, CngProvider provider)
        {
            Contract.Ensures(Contract.Result <CngKey>() != null);
            if (keyBlob == null)
            {
                throw new ArgumentNullException("keyBlob");
            }
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            // Make sure that NCrypt is supported on this platform
            if (!NCryptNative.NCryptSupported)
            {
                throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
            }

            // If we don't know for sure that the key will be ephemeral, then we need to demand Import
            // permission.  Since we won't know the name of the key until it's too late, we demand a full Import
            // rather than one scoped to the key.
            bool safeKeyImport = format == CngKeyBlobFormat.EccPublicBlob ||
                                 format == CngKeyBlobFormat.EccFullPublicBlob ||
                                 format == CngKeyBlobFormat.GenericPublicBlob;

            if (!safeKeyImport)
            {
                new KeyContainerPermission(KeyContainerPermissionFlags.Import).Demand();
            }

            // Import the key into the KSP
            SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);
            SafeNCryptKeyHandle      keyHandle;

            if (curveName == null)
            {
                keyHandle = NCryptNative.ImportKey(kspHandle, keyBlob, format.Format);
            }
            else
            {
                keyHandle = ECCng.ImportKeyBlob(format.Format, keyBlob, curveName, kspHandle);
            }

            // Prepare the key for use
            CngKey key = new CngKey(kspHandle, keyHandle);

            // We can't tell directly if an OpaqueTransport blob imported as an ephemeral key or not
            key.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob;

            return(key);
        }
Exemplo n.º 18
0
        public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters)
        {
            Contract.Ensures(Contract.Result <CngKey>() != null);

            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            if (creationParameters == null)
            {
                creationParameters = new CngKeyCreationParameters();
            }

            // Make sure that NCrypt is supported on this platform
            if (!NCryptNative.NCryptSupported)
            {
                throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
            }

            // If we're not creating an ephemeral key, then we need to ensure the user has access to the key name
            if (keyName != null)
            {
                KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create);
                access.ProviderName = creationParameters.Provider.Provider;

                KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                permission.AccessEntries.Add(access);
                permission.Demand();
            }

            //
            // Create the native handles representing the new key, setup the creation parameters on it, and
            // finalize it for use.
            //

            SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider);
            SafeNCryptKeyHandle      keyHandle = NCryptNative.CreatePersistedKey(kspHandle,
                                                                                 algorithm.Algorithm,
                                                                                 keyName,
                                                                                 creationParameters.KeyCreationOptions);

            SetKeyProperties(keyHandle, creationParameters);
            NCryptNative.FinalizeKey(keyHandle);

            CngKey key = new CngKey(kspHandle, keyHandle);

            // No name translates to an ephemeral key
            if (keyName == null)
            {
                key.IsEphemeral = true;
            }

            return(key);
        }
Exemplo n.º 19
0
        public void Delete()
        {
            KeyContainerPermission permission = this.BuildKeyContainerPermission(KeyContainerPermissionFlags.Delete);

            if (permission != null)
            {
                permission.Demand();
            }
            NCryptNative.DeleteKey(this.m_keyHandle);
            this.Dispose();
        }
Exemplo n.º 20
0
        public bool HasProperty(string name, CngPropertyOptions options)
        {
            bool flag;

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            NCryptNative.GetProperty(this.m_keyHandle, name, options, out flag);
            return(flag);
        }
Exemplo n.º 21
0
        internal string GetCurveName()
        {
            if (IsECNamedCurve())
            {
                return(NCryptNative.GetPropertyAsString(
                           m_keyHandle,
                           KeyPropertyName.ECCCurveName,
                           CngPropertyOptions.None));
            }

            // Use hard-coded values (for use with pre-Win10 APIs)
            return(GetECSpecificCurveName());
        }
Exemplo n.º 22
0
        public byte[] Export(CngKeyBlobFormat format)
        {
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }
            KeyContainerPermission permission = this.BuildKeyContainerPermission(KeyContainerPermissionFlags.Export);

            if (permission != null)
            {
                permission.Demand();
            }
            return(NCryptNative.ExportKey(this.m_keyHandle, format.Format));
        }
Exemplo n.º 23
0
        public bool HasProperty(string name, CngPropertyOptions options)
        {
            Contract.Assert(m_keyHandle != null);

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            bool foundProperty;

            NCryptNative.GetProperty(m_keyHandle, name, options, out foundProperty);

            return(foundProperty);
        }
Exemplo n.º 24
0
        public CngProperty GetProperty(string name, CngPropertyOptions options)
        {
            bool flag;

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            byte[] buffer = NCryptNative.GetProperty(this.m_keyHandle, name, options, out flag);
            if (!flag)
            {
                throw new CryptographicException(-2146893807);
            }
            return(new CngProperty(name, buffer, options));
        }
Exemplo n.º 25
0
        public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions)
        {
            if (keyHandle == null)
            {
                throw new ArgumentNullException("keyHandle");
            }
            if (keyHandle.IsClosed || keyHandle.IsInvalid)
            {
                throw new ArgumentException(System.SR.GetString("Cryptography_OpenInvalidHandle"), "keyHandle");
            }
            SafeNCryptKeyHandle      handle    = keyHandle.Duplicate();
            SafeNCryptProviderHandle kspHandle = new SafeNCryptProviderHandle();

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
            }
            finally
            {
                IntPtr newHandleValue = NCryptNative.GetPropertyAsIntPtr(keyHandle, "Provider Handle", CngPropertyOptions.None);
                kspHandle.SetHandleValue(newHandleValue);
            }
            CngKey key  = null;
            bool   flag = false;

            try
            {
                key = new CngKey(kspHandle, handle);
                bool flag2 = (keyHandleOpenOptions & CngKeyHandleOpenOptions.EphemeralKey) == CngKeyHandleOpenOptions.EphemeralKey;
                if (!key.IsEphemeral && flag2)
                {
                    key.IsEphemeral = true;
                }
                else if (key.IsEphemeral && !flag2)
                {
                    throw new ArgumentException(System.SR.GetString("Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag"), "keyHandleOpenOptions");
                }
                flag = true;
            }
            finally
            {
                if (!flag && (key != null))
                {
                    key.Dispose();
                }
            }
            return(key);
        }
Exemplo n.º 26
0
        public override bool VerifyHash(byte[] hash, byte[] signature)
        {
            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }
            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
            SafeNCryptKeyHandle key = this.Key.Handle;

            CodeAccessPermission.RevertAssert();
            return(NCryptNative.VerifySignature(key, hash, signature));
        }
Exemplo n.º 27
0
        public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
        {
            if (rgbHash == null)
            {
                throw new ArgumentNullException("rgbHash");
            }

            if (rgbSignature == null)
            {
                throw new ArgumentNullException("rgbSignature");
            }

            rgbHash = AdjustHashSizeIfNecessary(rgbHash);

            return(NCryptNative.VerifySignature(KeyHandle, rgbHash, rgbSignature));
        }
Exemplo n.º 28
0
 public SafeNCryptSecretHandle DeriveSecretAgreementHandle(CngKey otherPartyPublicKey)
 {
     if (otherPartyPublicKey == null)
     {
         throw new ArgumentNullException("otherPartyPublicKey");
     }
     if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman)
     {
         throw new ArgumentException(System.SR.GetString("Cryptography_ArgECDHRequiresECDHKey"), "otherPartyPublicKey");
     }
     if (otherPartyPublicKey.KeySize != this.KeySize)
     {
         throw new ArgumentException(System.SR.GetString("Cryptography_ArgECDHKeySizeMismatch"), "otherPartyPublicKey");
     }
     return(NCryptNative.DeriveSecretAgreement(this.Key.Handle, otherPartyPublicKey.Handle));
 }
Exemplo n.º 29
0
        public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options)
        {
            if (keyName == null)
            {
                throw new ArgumentNullException("keyName");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            // Make sure that NCrypt is supported on this platform
            if (!NCryptNative.NCryptSupported)
            {
                throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
            }

            using (SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider)) {
                SafeNCryptKeyHandle keyHandle = null;

                try {
                    NCryptNative.ErrorCode error = NCryptNative.UnsafeNativeMethods.NCryptOpenKey(kspHandle,
                                                                                                  out keyHandle,
                                                                                                  keyName,
                                                                                                  0,
                                                                                                  options);

                    // CNG will return either NTE_NOT_FOUND or NTE_BAD_KEYSET for the case where the key does
                    // not exist, so we need to check for both return codes.
                    bool keyNotFound = error == NCryptNative.ErrorCode.KeyDoesNotExist ||
                                       error == NCryptNative.ErrorCode.NotFound;

                    if (error != NCryptNative.ErrorCode.Success && !keyNotFound)
                    {
                        throw new CryptographicException((int)error);
                    }

                    return(error == NCryptNative.ErrorCode.Success);
                }
                finally {
                    if (keyHandle != null)
                    {
                        keyHandle.Dispose();
                    }
                }
            }
        }
        private static void WritePublicKeyValue(XmlWriter writer, CngKey key)
        {
            BigInteger integer;
            BigInteger integer2;

            writer.WriteStartElement("PublicKey");
            NCryptNative.UnpackEccPublicBlob(key.Export(CngKeyBlobFormat.EccPublicBlob), out integer, out integer2);
            writer.WriteStartElement("X");
            writer.WriteAttributeString("Value", integer.ToString("R", CultureInfo.InvariantCulture));
            writer.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", "PrimeFieldElemType");
            writer.WriteEndElement();
            writer.WriteStartElement("Y");
            writer.WriteAttributeString("Value", integer2.ToString("R", CultureInfo.InvariantCulture));
            writer.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", "PrimeFieldElemType");
            writer.WriteEndElement();
            writer.WriteEndElement();
        }