Exemplo n.º 1
0
        internal static SafeNCryptProviderHandle OpenStorageProvider(this CngProvider provider)
        {
            string providerName = provider.Provider;
            SafeNCryptProviderHandle providerHandle;
            ErrorCode errorCode = Interop.NCrypt.NCryptOpenStorageProvider(out providerHandle, providerName, 0);

            if (errorCode != ErrorCode.ERROR_SUCCESS)
            {
                throw errorCode.ToCryptographicException();
            }

            return(providerHandle);
        }
Exemplo n.º 2
0
        internal static CngKey Import(
            byte[] keyBlob,
            string?curveName,
            CngKeyBlobFormat format,
            CngProvider provider)
        {
            if (keyBlob == null)
            {
                throw new ArgumentNullException(nameof(keyBlob));
            }

            return(Import(new ReadOnlySpan <byte>(keyBlob), curveName, format, provider));
        }
Exemplo n.º 3
0
        internal static CngKey Import(
            ReadOnlySpan <byte> keyBlob,
            string?curveName,
            CngKeyBlobFormat format,
            CngProvider provider)
        {
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider();
            SafeNCryptKeyHandle?     keyHandle;
            ErrorCode errorCode;

            if (curveName == null)
            {
                errorCode = Interop.NCrypt.NCryptImportKey(
                    providerHandle,
                    IntPtr.Zero,
                    format.Format,
                    IntPtr.Zero,
                    out keyHandle,
                    ref MemoryMarshal.GetReference(keyBlob),
                    keyBlob.Length,
                    0);

                if (errorCode != ErrorCode.ERROR_SUCCESS)
                {
                    throw errorCode.ToCryptographicException();
                }
            }
            else
            {
                keyHandle = ECCng.ImportKeyBlob(format.Format, keyBlob, curveName, providerHandle);
            }

            CngKey key = new CngKey(providerHandle, 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.º 4
0
        internal static unsafe CngKey ImportEncryptedPkcs8(
            ReadOnlySpan <byte> keyBlob,
            ReadOnlySpan <char> password,
            CngProvider provider)
        {
            SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider();
            SafeNCryptKeyHandle      keyHandle;

            using (SafeUnicodeStringHandle passwordHandle = new SafeUnicodeStringHandle(password))
            {
                Interop.NCrypt.NCryptBuffer *buffers = stackalloc Interop.NCrypt.NCryptBuffer[1];

                buffers[0] = new Interop.NCrypt.NCryptBuffer
                {
                    BufferType = Interop.NCrypt.BufferType.PkcsSecret,
                    cbBuffer   = checked (2 * (password.Length + 1)),
                    pvBuffer   = passwordHandle.DangerousGetHandle(),
                };

                Interop.NCrypt.NCryptBufferDesc desc = new Interop.NCrypt.NCryptBufferDesc
                {
                    cBuffers  = 1,
                    pBuffers  = (IntPtr)buffers,
                    ulVersion = 0,
                };

                ErrorCode errorCode = Interop.NCrypt.NCryptImportKey(
                    providerHandle,
                    IntPtr.Zero,
                    Interop.NCrypt.NCRYPT_PKCS8_PRIVATE_KEY_BLOB,
                    ref desc,
                    out keyHandle,
                    ref MemoryMarshal.GetReference(keyBlob),
                    keyBlob.Length,
                    0);

                if (errorCode != ErrorCode.ERROR_SUCCESS)
                {
                    keyHandle.Dispose();
                    throw errorCode.ToCryptographicException();
                }
            }

            CngKey key = new CngKey(providerHandle, keyHandle);

            key.IsEphemeral = true;
            return(key);
        }
Exemplo n.º 5
0
        public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
        {
            ArgumentNullException.ThrowIfNull(keyName);
            ArgumentNullException.ThrowIfNull(provider);

            SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider();
            SafeNCryptKeyHandle      keyHandle;
            ErrorCode errorCode = Interop.NCrypt.NCryptOpenKey(providerHandle, out keyHandle, keyName, 0, openOptions);

            if (errorCode != ErrorCode.ERROR_SUCCESS)
            {
                throw errorCode.ToCryptographicException();
            }

            return(new CngKey(providerHandle, keyHandle));
        }
Exemplo n.º 6
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();
                    }
                }
            }
        }
Exemplo n.º 7
0
        public static CngKey Import(byte[] keyBlob, 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.GenericPublicBlob;

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

            // Import the key into the KSP
            SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);
            SafeNCryptKeyHandle      keyHandle = NCryptNative.ImportKey(kspHandle, keyBlob, format.Format);

            // 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);
        }
        public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options)
        {
            if (keyName == null)
            {
                throw new ArgumentNullException(nameof(keyName));
            }

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

            using (SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider())
            {
                SafeNCryptKeyHandle?keyHandle = null;
                try
                {
                    ErrorCode errorCode = Interop.NCrypt.NCryptOpenKey(providerHandle, out keyHandle, keyName, 0, options);
                    if (errorCode == ErrorCode.NTE_BAD_KEYSET)
                    {
                        return(false);
                    }
                    if (errorCode != ErrorCode.ERROR_SUCCESS)
                    {
                        throw errorCode.ToCryptographicException();
                    }
                    return(true);
                }
                finally
                {
                    if (keyHandle != null)
                    {
                        keyHandle.Dispose();
                    }
                }
            }
        }
        /// <summary>
        /// Constructs the core to use a stored CNG key.
        /// </summary>
        public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
        {
            ArgumentNullException.ThrowIfNull(keyName);
            ArgumentNullException.ThrowIfNull(provider);

            _outer = outer;

            _keyName       = keyName;
            _provider      = provider;
            _optionOptions = openOptions;

            using (CngKey cngKey = ProduceCngKey())
            {
                CngAlgorithm actualAlgorithm = cngKey.Algorithm;
                string       algorithm       = _outer.GetNCryptAlgorithmIdentifier();

                if (algorithm != actualAlgorithm.Algorithm)
                {
                    throw new CryptographicException(SR.Format(SR.Cryptography_CngKeyWrongAlgorithm, actualAlgorithm.Algorithm, algorithm));
                }

                _outer.BaseKeySize = cngKey.KeySize;
            }
        }
Exemplo n.º 10
0
 public CngKeyCreationParameters()
 {
     parameters = new CngPropertyCollection();
     provider   = CngProvider.MicrosoftSoftwareKeyStorageProvider;
 }
Exemplo n.º 11
0
 public TripleDESCng(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
 {
     SetLegalKeySizesValue();
     _core = new CngSymmetricAlgorithmCore(AlgorithmName, this, keyName, provider, openOptions);
 }
 public AesCng(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions openOptions)
 {
 }
 public AesCng(string keyName, System.Security.Cryptography.CngProvider provider)
 {
 }
Exemplo n.º 14
0
 public TripleDESCng(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
 {
     _core = new CngSymmetricAlgorithmCore(this, keyName, provider, openOptions);
 }
Exemplo n.º 15
0
 public static CngKey Open(string keyName, CngProvider provider)
 {
     return(Open(keyName, provider, openOptions: CngKeyOpenOptions.None));
 }
Exemplo n.º 16
0
 public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 17
0
 public static bool Exists(string keyName, CngProvider provider)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 18
0
 public static CngKey Open(string keyName, CngProvider provider)
 {
     Contract.Ensures(Contract.Result <CngKey>() != null);
     return(Open(keyName, provider, CngKeyOpenOptions.None));
 }
Exemplo n.º 19
0
 public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
 {
     Contract.Ensures(Contract.Result <CngKey>() != null);
     return(Import(keyBlob, null, format, provider));
 }
Exemplo n.º 20
0
        internal static CngKey Import(byte[] keyBlob, ECCurve?curve, CngKeyBlobFormat format, CngProvider provider)
        {
#endif //!NETNATIVE
            if (keyBlob == null)
            {
                throw new ArgumentNullException(nameof(keyBlob));
            }
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider();
            SafeNCryptKeyHandle      keyHandle;
            ErrorCode errorCode;

#if !NETNATIVE
            if (curve == null)
#endif //!NETNATIVE
            {
                errorCode = Interop.NCrypt.NCryptImportKey(providerHandle, IntPtr.Zero, format.Format, IntPtr.Zero, out keyHandle, keyBlob, keyBlob.Length, 0);
                if (errorCode != ErrorCode.ERROR_SUCCESS)
                {
                    throw errorCode.ToCryptographicException();
                }
            }
#if !NETNATIVE
            else
            {
                // Call with Oid.FriendlyName because .Value will result in an invalid parameter error
                Debug.Assert(curve.Value.IsNamed);
                string curveName = curve.Value.Oid.FriendlyName;
                using (SafeUnicodeStringHandle safeCurveName = new SafeUnicodeStringHandle(curveName))
                {
                    var desc = new Interop.BCrypt.BCryptBufferDesc();
                    var buff = new Interop.BCrypt.BCryptBuffer();

                    IntPtr descPtr = IntPtr.Zero;
                    IntPtr buffPtr = IntPtr.Zero;
                    try
                    {
                        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   = safeCurveName.DangerousGetHandle();
                        Marshal.StructureToPtr(buff, buffPtr, false);

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

                        errorCode = Interop.NCrypt.NCryptImportKey(providerHandle, IntPtr.Zero, format.Format, descPtr, out keyHandle, keyBlob, keyBlob.Length, 0);
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(descPtr);
                        Marshal.FreeHGlobal(buffPtr);
                    }
                }

                if (errorCode != ErrorCode.ERROR_SUCCESS)
                {
                    Exception e = errorCode.ToCryptographicException();
                    if (errorCode == ErrorCode.NTE_INVALID_PARAMETER)
                    {
                        throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curveName), e);
                    }
                    throw e;
                }
            }
#endif //!NETNATIVE

            CngKey key = new CngKey(providerHandle, 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.º 21
0
 public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 22
0
        public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
        {
            Contract.Ensures(Contract.Result <System.Security.Cryptography.CngKey>() != null);

            return(default(CngKey));
        }
 public static bool Exists(string keyName, CngProvider provider)
 {
     return(Exists(keyName, provider, options: CngKeyOpenOptions.None));
 }
Exemplo n.º 24
0
        public static CngKey Open(string keyName, CngProvider provider)
        {
            Contract.Ensures(Contract.Result <System.Security.Cryptography.CngKey>() != null);

            return(default(CngKey));
        }
Exemplo n.º 25
0
 public AesCng(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
 {
     throw new PlatformNotSupportedException(SR.PlatformNotSupported_CryptographyCng);
 }
Exemplo n.º 26
0
 public static bool Exists(string keyName, CngProvider provider)
 {
     return(default(bool));
 }
Exemplo n.º 27
0
 public TripleDESCng(string keyName, CngProvider provider)
     : this(keyName, provider, CngKeyOpenOptions.None)
 {
 }
Exemplo n.º 28
0
 public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options)
 {
     return(default(bool));
 }
Exemplo n.º 29
0
 public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
 {
     return(Import(keyBlob, null, format, provider));
 }
Exemplo n.º 30
0
 public AesCng(string keyName, CngProvider provider)
     : this(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.None)
 {
 }