private void Reset()
 {
     if (IV != null)
     {
         CngProperty prop = new CngProperty(KeyPropertyName.InitializationVector, IV, CngPropertyOptions.None);
         _cngKey !.SetProperty(prop);
     }
 }
Exemple #2
0
        public CngKey GetOrGenerateKey(ECCurve?curve)
        {
            ThrowIfDisposed();

            if (_lazyKey != null)
            {
                return(_lazyKey);
            }

            // We don't have a key yet so generate
            Debug.Assert(curve.HasValue);

            CngKeyCreationParameters creationParameters = new CngKeyCreationParameters()
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
            };

            if (curve.Value.IsNamed)
            {
                creationParameters.Parameters.Add(CngKey.GetPropertyFromNamedCurve(curve.Value));
            }
            else if (curve.Value.IsPrime)
            {
                ECCurve     eccurve        = curve.Value;
                byte[]      parametersBlob = ECCng.GetPrimeCurveParameterBlob(ref eccurve);
                CngProperty prop           = new CngProperty(
                    Interop.BCrypt.BCryptPropertyStrings.BCRYPT_ECC_PARAMETERS,
                    parametersBlob,
                    CngPropertyOptions.None);
                creationParameters.Parameters.Add(prop);
            }
            else
            {
                throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.Value.CurveType.ToString()));
            }

            try
            {
                _lazyKey = CngKey.Create(DefaultKeyType ?? CngAlgorithm.ECDsa, null, creationParameters);
            }
            catch (CryptographicException e)
            {
                // Map to PlatformNotSupportedException if appropriate
                ErrorCode errorCode = (ErrorCode)e.HResult;

                if (curve.Value.IsNamed &&
                    errorCode == ErrorCode.NTE_INVALID_PARAMETER || errorCode == ErrorCode.NTE_NOT_SUPPORTED)
                {
                    throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.Value.Oid.FriendlyName), e);
                }
                throw;
            }

            return(_lazyKey);
        }
        //
        // The first parameter is a delegate that instantiates a CngKey rather than a CngKey itself. That's because CngKeys are stateful objects
        // and concurrent encryptions on the same CngKey will corrupt each other.
        //
        // The delegate must instantiate a new CngKey, based on a new underlying NCryptKeyHandle, each time is called.
        //
        public BasicSymmetricCipherNCrypt(Func <CngKey> cngKeyFactory, CipherMode cipherMode, int blockSizeInBytes, byte[]?iv, bool encrypting, int paddingSize)
            : base(iv, blockSizeInBytes, paddingSize)
        {
            _encrypting = encrypting;
            _cngKey     = cngKeyFactory();
            CngProperty chainingModeProperty = cipherMode switch
            {
                CipherMode.ECB => s_ECBMode,
                CipherMode.CBC => s_CBCMode,
                CipherMode.CFB => s_CFBMode,
                _ => throw new CryptographicException(SR.Cryptography_InvalidCipherMode),
            };

            _cngKey.SetProperty(chainingModeProperty);

            Reset();
        }
        /// <summary>
        ///     Set an arbitrary property on the key
        /// </summary>
        public void SetProperty(CngProperty property)
        {
            unsafe
            {
                byte[] propertyValue = property.GetValueWithoutCopying();

                // .NET Framework compat. It would have nicer to throw an ArgumentNull exception or something...
                if (propertyValue == null)
                    throw ErrorCode.NTE_INVALID_PARAMETER.ToCryptographicException();

                fixed(byte *pinnedPropertyValue = propertyValue.MapZeroLengthArrayToNonNullPointer())
                {
                    ErrorCode errorCode = Interop.NCrypt.NCryptSetProperty(_keyHandle, property.Name, pinnedPropertyValue, propertyValue.Length, property.Options);

                    if (errorCode != ErrorCode.ERROR_SUCCESS)
                    {
                        throw errorCode.ToCryptographicException();
                    }
                }
            }
        }
        public BasicSymmetricCipherLiteNCrypt(
            Func <CngKey> cngKeyFactory,
            CipherMode cipherMode,
            int blockSizeInBytes,
            ReadOnlySpan <byte> iv,
            bool encrypting,
            int paddingSizeInBytes)
        {
            BlockSizeInBytes   = blockSizeInBytes;
            PaddingSizeInBytes = paddingSizeInBytes;
            _encrypting        = encrypting;
            _key = cngKeyFactory();
            CngProperty chainingModeProperty = cipherMode switch
            {
                CipherMode.ECB => s_ECBMode,
                CipherMode.CBC => s_CBCMode,
                CipherMode.CFB => s_CFBMode,
                _ => throw new CryptographicException(SR.Cryptography_InvalidCipherMode),
            };

            _key.SetProperty(chainingModeProperty);

            Reset(iv);
        }
Exemple #6
0
 public void SetProperty(CngProperty property)
 {
     throw new NotImplementedException();
 }
Exemple #7
0
 public void SetProperty(CngProperty property)
 {
     NCryptNative.SetProperty(this.m_keyHandle, property.Name, property.Value, property.Options);
 }
Exemple #8
0
        internal static CngKey Create(ECCurve curve, Func <string, CngAlgorithm> algorithmResolver)
        {
            System.Diagnostics.Debug.Assert(algorithmResolver != null);

            curve.Validate();

            CngKeyCreationParameters creationParameters = new CngKeyCreationParameters
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
            };

            CngAlgorithm alg;

            if (curve.IsNamed)
            {
                if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
                {
                    throw new PlatformNotSupportedException(string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
                }

                // Map curve name to algorithm to support pre-Win10 curves
                alg = algorithmResolver(curve.Oid.FriendlyName);

                if (CngKey.IsECNamedCurve(alg.Algorithm))
                {
                    creationParameters.Parameters.Add(GetPropertyFromNamedCurve(curve));
                }
                else
                {
                    if (alg == CngAlgorithm.ECDsaP256 || alg == CngAlgorithm.ECDiffieHellmanP256 ||
                        alg == CngAlgorithm.ECDsaP384 || alg == CngAlgorithm.ECDiffieHellmanP384 ||
                        alg == CngAlgorithm.ECDsaP521 || alg == CngAlgorithm.ECDiffieHellmanP521)
                    {
                        // No parameters required, the algorithm ID has everything built-in.
                    }
                    else
                    {
                        Debug.Fail(string.Format("Unknown algorithm {0}", alg.ToString()));
                        throw new ArgumentException(SR.Cryptography_InvalidKeySize);
                    }
                }
            }
            else if (curve.IsPrime)
            {
                byte[] parametersBlob = ECCng.GetPrimeCurveParameterBlob(ref curve);

                CngProperty prop = new CngProperty(
                    KeyPropertyName.ECCParameters,
                    parametersBlob,
                    CngPropertyOptions.None);

                creationParameters.Parameters.Add(prop);
                alg = algorithmResolver(null);
            }
            else
            {
                throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
            }

            try
            {
                return(Create(alg, null, creationParameters));
            }
            catch (CryptographicException e)
            {
                Interop.NCrypt.ErrorCode errorCode = (Interop.NCrypt.ErrorCode)e.HResult;

                if (errorCode == Interop.NCrypt.ErrorCode.NTE_INVALID_PARAMETER ||
                    errorCode == Interop.NCrypt.ErrorCode.NTE_NOT_SUPPORTED)
                {
                    string target = curve.IsNamed ? curve.Oid.FriendlyName : curve.CurveType.ToString();
                    throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, target), e);
                }

                throw;
            }
        }
Exemple #9
0
 public void SetProperty(CngProperty property)
 {
 }
Exemple #10
0
 public void SetProperty(CngProperty property)
 {
     Contract.Assert(m_keyHandle != null);
     NCryptNative.SetProperty(m_keyHandle, property.Name, property.Value, property.Options);
 }