Example #1
0
 public static void SetKeyParameter(SafeKeyHandleImpl keyHandle, int keyParamId, byte[] keyParamValue)
 {
     if (!CryptoApi.CryptSetKeyParam(keyHandle, (uint)keyParamId, keyParamValue, 0))
     {
         throw CreateWin32Error();
     }
 }
Example #2
0
 public static bool VerifySign(SafeProvHandleImpl providerHandle, SafeKeyHandleImpl keyHandle, byte[] hashValue, byte[] signatureValue, GostAlgorithmType alg)
 {
     using (var hashHandle = SetupHashAlgorithm(providerHandle, hashValue, alg))
     {
         return(CryptoApi.CryptVerifySignature(hashHandle, signatureValue, (uint)signatureValue.Length, keyHandle, null, 0));
     }
 }
Example #3
0
 public static void HashKeyExchange(SafeHashHandleImpl hashHandle, SafeKeyHandleImpl keyExchangeHandle)
 {
     if (!CryptoApi.CryptHashSessionKey(hashHandle, keyExchangeHandle, 0))
     {
         throw CreateWin32Error();
     }
 }
        public Gost28147SymmetricAlgorithm()
        {
            Mode = CipherMode.CFB;
            Padding = PaddingMode.None;

            _provHandle = SafeProvHandleImpl.InvalidHandle;
            _keyHandle = SafeKeyHandleImpl.InvalidHandle;
        }
Example #5
0
        public static void SetKeyParameterInt32(SafeKeyHandleImpl keyHandle, int keyParamId, int keyParamValue)
        {
            var dwDataBytes = BitConverter.GetBytes(keyParamValue);

            if (!CryptoApi.CryptSetKeyParam(keyHandle, (uint)keyParamId, dwDataBytes, 0))
            {
                throw CreateWin32Error();
            }
        }
Example #6
0
        private static void SetKeyParameterString(SafeKeyHandleImpl keyHandle, int keyParamId, string keyParamValue)
        {
            var stringDataBytes = Encoding.GetEncoding(0).GetBytes(keyParamValue);

            if (!CryptoApi.CryptSetKeyParam(keyHandle, (uint)keyParamId, stringDataBytes, 0))
            {
                throw CreateWin32Error();
            }
        }
        public Gost3410EphemeralAsymmetricAlgorithm(GostKeyExchangeParameters keyParameters)
        {
            if (keyParameters == null)
            {
                throw ExceptionUtility.ArgumentNull("keyParameters");
            }

            _provHandle = CryptoApiHelper.ProviderHandle.DangerousAddRef();
            _keyHandle = CryptoApiHelper.GenerateDhEphemeralKey(_provHandle, keyParameters.DigestParamSet, keyParameters.PublicKeyParamSet);
        }
Example #8
0
        public static void EndDecrypt(ProviderType providerType, SafeKeyHandleImpl symKeyHandle)
        {
            uint dataLength = 0;
            var  data       = new byte[0];
            var  success    = CryptoApi.CryptDecrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, true, 0, data, ref dataLength) || providerType.IsVipNet();

            if (!success)
            {
                throw CreateWin32Error();
            }
        }
        internal Gost28147SymmetricAlgorithm(SafeProvHandleImpl provHandle, SafeKeyHandleImpl keyHandle)
            : this()
        {
            _provHandle = provHandle.DangerousAddRef();
            _keyHandle = CryptoApiHelper.DuplicateKey(keyHandle);

            if (CryptoApiHelper.GetKeyParameterInt32(_keyHandle, Constants.KP_ALGID) != Constants.CALG_G28147)
            {
                throw ExceptionUtility.Argument("keyHandle", Resources.RequiredGost28147);
            }
        }
        public Gost28147SymmetricAlgorithm(IntPtr provHandle, IntPtr keyHandle)
            : this()
        {
            _provHandle = new SafeProvHandleImpl(provHandle, true);
            _keyHandle = CryptoApiHelper.DuplicateKey(keyHandle);

            if (CryptoApiHelper.GetKeyParameterInt32(_keyHandle, Constants.KP_ALGID) != Constants.CALG_G28147)
            {
                throw ExceptionUtility.Argument("keyHandle", Resources.RequiredGost28147);
            }
        }
Example #11
0
        public static byte[] GetKeyParameter(SafeKeyHandleImpl keyHandle, uint keyParamId)
        {
            uint dataLength = 0;

            if (!CryptoApi.CryptGetKeyParam(keyHandle, keyParamId, null, ref dataLength, 0))
            {
                throw CreateWin32Error();
            }

            var dataBytes = new byte[dataLength];

            if (!CryptoApi.CryptGetKeyParam(keyHandle, keyParamId, dataBytes, ref dataLength, 0))
            {
                throw CreateWin32Error();
            }

            return(dataBytes);
        }
Example #12
0
        public static byte[] ExportCspBlob(SafeKeyHandleImpl symKeyHandle, SafeKeyHandleImpl keyExchangeHandle, int blobType)
        {
            uint exportedKeyLength = 0;

            if (!CryptoApi.CryptExportKey(symKeyHandle, keyExchangeHandle, (uint)blobType, 0, null, ref exportedKeyLength))
            {
                throw CreateWin32Error();
            }

            var exportedKeyBytes = new byte[exportedKeyLength];

            if (!CryptoApi.CryptExportKey(symKeyHandle, keyExchangeHandle, (uint)blobType, 0, exportedKeyBytes, ref exportedKeyLength))
            {
                throw CreateWin32Error();
            }

            return(exportedKeyBytes);
        }
Example #13
0
        public static int GetKeyParameterInt32(SafeKeyHandleImpl keyHandle, uint keyParamId)
        {
            const int doubleWordSize = 4;

            uint dwDataLength = doubleWordSize;
            var  dwDataBytes  = new byte[doubleWordSize];

            if (!CryptoApi.CryptGetKeyParam(keyHandle, keyParamId, dwDataBytes, ref dwDataLength, 0))
            {
                throw CreateWin32Error();
            }

            if (dwDataLength != doubleWordSize)
            {
                throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA);
            }

            return(BitConverter.ToInt32(dwDataBytes, 0));
        }
Example #14
0
        public static void EndCrypt(SafeKeyHandleImpl symKeyHandle, Gost28147CryptoTransformMode transformMode)
        {
            bool success;
            uint dataLength = 0;

            if (transformMode == Gost28147CryptoTransformMode.Encrypt)
            {
                var data = new byte[32];
                success = CryptoApi.CryptEncrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, true, 0, data, ref dataLength, (uint)data.Length);
            }
            else
            {
                var data = new byte[0];
                success = CryptoApi.CryptDecrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, true, 0, data, ref dataLength) || (GostCryptoConfig.ProviderType == ProviderTypes.VipNet);
            }

            if (!success)
            {
                throw CreateWin32Error();
            }
        }
Example #15
0
        /// <summary>
        /// Возвращает сертификат X.509 для указанного ключа.
        /// </summary>
        /// <param name="keyHandle">Дескриптор ключа сертификата.</param>
        public static X509Certificate2 GetKeyCertificate(SafeKeyHandleImpl keyHandle)
        {
            uint certDataLength = 0;

            if (!CryptoApi.CryptGetKeyParam(keyHandle, Constants.KP_CERTIFICATE, null, ref certDataLength, 0))
            {
                if (Marshal.GetLastWin32Error() != Constants.ERROR_NO_SUCH_CERTIFICATE)
                {
                    throw CreateWin32Error();
                }

                return(null);
            }

            var certData = new byte[certDataLength];

            if (!CryptoApi.CryptGetKeyParam(keyHandle, Constants.KP_CERTIFICATE, certData, ref certDataLength, 0))
            {
                throw CreateWin32Error();
            }

            return(new X509Certificate2(certData));
        }
        public override void ImportParameters(GostKeyExchangeParameters keyParameters)
        {
            if (keyParameters.PrivateKey != null)
            {
                throw ExceptionUtility.NotSupported(Resources.UserImportBulkKeyNotSupported);
            }

            _keyHandle.TryDispose();

            _providerHandle = CryptoApiHelper.ProviderHandle;
            _keyHandle = CryptoApiHelper.ImportPublicKey(_providerHandle, new GostKeyExchangeParameters(keyParameters));

            _isPublicKeyOnly = true;
        }
        private static void GetKeyPairValue(CspParameters providerParams, bool randomKeyContainer, out SafeProvHandleImpl providerHandle, out SafeKeyHandleImpl keyHandle)
        {
            SafeProvHandleImpl resultProviderHandle = null;

            SafeKeyHandleImpl resultKeyHandle = null;

            try
            {
                resultProviderHandle = CreateProviderHandle(providerParams, randomKeyContainer);

                if (providerParams.ParentWindowHandle != IntPtr.Zero)
                {
                    CryptoApiHelper.SetProviderParameter(resultProviderHandle, providerParams.KeyNumber, Constants.PP_CLIENT_HWND, providerParams.ParentWindowHandle);
                }
                else if (providerParams.KeyPassword != null)
                {
                    SetSignatureKeyPassword(resultProviderHandle, providerParams.KeyPassword, providerParams.KeyNumber);
                }

                try
                {
                    resultKeyHandle = CryptoApiHelper.GetUserKey(resultProviderHandle, providerParams.KeyNumber);
                }
                catch (Exception exception)
                {
                    var errorCode = Marshal.GetHRForException(exception);

                    if (errorCode != 0)
                    {
                        if (((providerParams.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags) || (errorCode != Constants.NTE_NO_KEY))
                        {
                            throw;
                        }

                        resultKeyHandle = CryptoApiHelper.GenerateKey(resultProviderHandle, providerParams.KeyNumber, providerParams.Flags);
                    }
                }

                var keyAlgIdInverted = CryptoApiHelper.GetKeyParameter(resultKeyHandle, Constants.KP_ALGID);
                var keyAlgId = keyAlgIdInverted[0] | (keyAlgIdInverted[1] << 8) | (keyAlgIdInverted[2] << 16) | (keyAlgIdInverted[3] << 24);

                if ((keyAlgId != Constants.CALG_DH_EL_SF) && (keyAlgId != Constants.CALG_GR3410EL))
                {
                    throw ExceptionUtility.NotSupported(Resources.KeyAlgorithmNotSupported);
                }
            }
            catch (Exception)
            {
                if (resultProviderHandle != null)
                {
                    resultProviderHandle.Close();
                }

                if (resultKeyHandle != null)
                {
                    resultKeyHandle.Close();
                }

                throw;
            }

            providerHandle = resultProviderHandle;
            keyHandle = resultKeyHandle;
        }
Example #18
0
        public static void SetKeyExchangeExportAlgId(ProviderType providerType, SafeKeyHandleImpl keyHandle, int keyExchangeExportAlgId)
        {
            var keyExchangeExportAlgParamId = providerType.IsVipNet() ? Constants.KP_EXPORTID : Constants.KP_ALGID;

            SetKeyParameterInt32(keyHandle, keyExchangeExportAlgParamId, keyExchangeExportAlgId);
        }
        public void DeriveFromPassword(byte[] password)
        {
            var provider = CreateFromPassword(password);

            _keyHandle.TryDispose();
            _provHandle.TryDispose();

            _keyHandle = provider._keyHandle;
            _provHandle = provider._provHandle;

            provider._keyHandle = SafeKeyHandleImpl.InvalidHandle;
            provider._provHandle = SafeProvHandleImpl.InvalidHandle;
        }
Example #20
0
        private static string GetKeyParameterString(SafeKeyHandleImpl keyHandle, uint keyParamId)
        {
            var paramValue = GetKeyParameter(keyHandle, keyParamId);

            return(BytesToString(paramValue));
        }
        public override void GenerateKey()
        {
            _provHandle = CryptoApiHelper.ProviderHandle.DangerousAddRef();
            _keyHandle = CryptoApiHelper.GenerateKey(_provHandle, Constants.CALG_G28147, CspProviderFlags.NoFlags);

            KeyValue = null;
            KeySizeValue = DefaultKeySize;
        }
Example #22
0
 public static extern bool CryptGetKeyParam([In] SafeKeyHandleImpl hKey, [In] uint dwParam, [In][Out] byte[] pbData, ref uint pdwDataLen, [In] uint dwFlags);
Example #23
0
 public static extern bool CryptGenKey([In] SafeProvHandleImpl hProv, [In] uint Algid, [In] uint dwFlags, [In][Out] ref SafeKeyHandleImpl phKey);
Example #24
0
 public static extern bool CryptDeriveKey([In] SafeProvHandleImpl hProv, [In] uint Algid, [In] SafeHashHandleImpl hBaseData, [In] uint dwFlags, [In][Out] ref SafeKeyHandleImpl phKey);
Example #25
0
 public static extern bool CryptExportKey([In] SafeKeyHandleImpl hKey, [In] SafeKeyHandleImpl hExpKey, [In] uint dwBlobType, [In] uint dwFlags, [Out] byte[] pbData, ref uint pdwDataLen);
Example #26
0
        private static SafeHashHandleImpl CreateHashHMAC(SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle, int hmacAlgId)
        {
            var hashHmacHandle = SafeHashHandleImpl.InvalidHandle;

            if (!CryptoApi.CryptCreateHash(providerHandle, (uint)hmacAlgId, symKeyHandle, 0, ref hashHmacHandle))
            {
                var errorCode = Marshal.GetLastWin32Error();

                if (errorCode == Constants.NTE_BAD_ALGID)
                {
                    throw ExceptionUtility.CryptographicException(Resources.AlgorithmNotAvailable);
                }

                throw ExceptionUtility.CryptographicException(errorCode);
            }

            return(hashHmacHandle);
        }
Example #27
0
        public static SafeHashHandleImpl CreateHashHMAC_2012_512(ProviderType providerType, SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle)
        {
            var hmacAlgId = providerType.IsVipNet() ? Constants.CALG_GR3411_2012_512 : Constants.CALG_GR3411_2012_512_HMAC;

            return(CreateHashHMAC(providerHandle, symKeyHandle, hmacAlgId));
        }
        public void ImportCspBlob(byte[] importedKeyBytes)
        {
            if (importedKeyBytes == null)
            {
                throw ExceptionUtility.ArgumentNull("importedKeyBytes");
            }

            if (!IsPublicKeyBlob(importedKeyBytes))
            {
                throw ExceptionUtility.Argument("importedKeyBytes", Resources.UserImportBulkBlob);
            }

            var hProv = CryptoApiHelper.ProviderHandle;
            SafeKeyHandleImpl hKey;

            _providerParameters.KeyNumber = CryptoApiHelper.ImportCspBlob(importedKeyBytes, hProv, SafeKeyHandleImpl.InvalidHandle, out hKey);
            _providerHandle = hProv;
            _keyHandle = hKey;

            _isPublicKeyOnly = true;
        }
        public Gost28147CryptoTransform(SafeKeyHandleImpl hKey, Dictionary<int, object> keyParameters, PaddingMode paddingValue, CipherMode modeValue, int blockSizeValue, Gost28147CryptoTransformMode transformMode)
        {
            _keyHandle = hKey;
            _paddingValue = paddingValue;
            _isStreamModeValue = (modeValue == CipherMode.OFB) || (modeValue == CipherMode.CFB);
            _blockSizeValue = blockSizeValue;
            _transformMode = transformMode;

            // Установка параметров ключа

            foreach (var keyParameter in keyParameters)
            {
                var keyParameterId = keyParameter.Key;
                var keyParameterValue = keyParameter.Value;

                // Копирование значения параметра

                if (keyParameterValue is byte[])
                {
                    var keyParamValueBytes = (byte[])keyParameterValue;
                    var copyKeyParamValueBytes = new byte[keyParamValueBytes.Length];
                    Array.Copy(keyParamValueBytes, copyKeyParamValueBytes, keyParamValueBytes.Length);

                    keyParameterValue = copyKeyParamValueBytes;
                }
                else if (keyParameterValue is int)
                {
                    keyParameterValue = (int)keyParameterValue;
                }
                else if (keyParameterValue is CipherMode)
                {
                    keyParameterValue = Convert.ToInt32(keyParameterValue);
                }
                else if (keyParameterValue is PaddingMode)
                {
                    keyParameterValue = Convert.ToInt32(keyParameterValue);
                }

                // Установка значения параметра

                switch (keyParameterId)
                {
                    case Constants.KP_IV:
                        {
                            _ivValue = (byte[])keyParameterValue;

                            var iv = _ivValue;
                            CryptoApiHelper.SetKeyParameter(_keyHandle, keyParameterId, iv);
                        }
                        break;
                    case Constants.KP_PADDING:
                        {
                            if (GostCryptoConfig.ProviderType != ProviderTypes.VipNet)
                            {
                                CryptoApiHelper.SetKeyParameterInt32(_keyHandle, keyParameterId, (int)keyParameterValue);
                            }
                        }
                        break;
                    case Constants.KP_MODE:
                        {
                            CryptoApiHelper.SetKeyParameterInt32(_keyHandle, keyParameterId, (int)keyParameterValue);
                        }
                        break;
                }
            }
        }
Example #30
0
 public static extern bool CryptVerifySignature([In] SafeHashHandleImpl hHash, [In][Out] byte[] pbSignature, uint pdwSigLen, [In] SafeKeyHandleImpl hPubKey, [MarshalAs(UnmanagedType.LPStr)] StringBuilder sDescription, [In] uint dwFlags);
        private ICryptoTransform CreateCryptoTransform(SafeKeyHandleImpl hKey, byte[] iv, Gost28147CryptoTransformMode transformMode)
        {
            if (hKey == null)
            {
                hKey = CryptoApiHelper.GenerateKey(CryptoApiHelper.ProviderHandle, Constants.CALG_G28147, CspProviderFlags.NoFlags);
            }

            var keyParameters = new Dictionary<int, object>();

            if (ModeValue == CipherMode.CTS)
            {
                throw ExceptionUtility.CryptographicException(Resources.CipherTextSteamingNotSupported);
            }

            if ((Padding != PaddingMode.None) && ((ModeValue == CipherMode.OFB) || (ModeValue == CipherMode.CFB)))
            {
                throw ExceptionUtility.CryptographicException(Resources.InvalidPaddingMode);
            }

            // Установка KP_PADDING
            keyParameters.Add(Constants.KP_PADDING, Constants.ZERO_PADDING);

            if ((ModeValue == CipherMode.CFB) && (FeedbackSizeValue != DefaultFeedbackSize))
            {
                throw ExceptionUtility.CryptographicException(Resources.IncorrectFeedbackSize);
            }

            // Установка KP_MODE
            keyParameters.Add(Constants.KP_MODE, ModeValue);

            // Установка KP_IV
            if (ModeValue != CipherMode.ECB)
            {
                if (iv == null)
                {
                    iv = new byte[DefaultIvSize];
                    CryptoApiHelper.RandomNumberGenerator.GetBytes(iv);
                }

                if (iv.Length < DefaultIvSize)
                {
                    throw ExceptionUtility.CryptographicException(Resources.InvalidIvSize);
                }

                keyParameters.Add(Constants.KP_IV, iv);
            }

            return new Gost28147CryptoTransform(hKey, keyParameters, PaddingValue, ModeValue, BlockSizeValue, transformMode);
        }
Example #32
0
 public static extern bool CryptGetUserKey([In] SafeProvHandleImpl hProv, [In] uint dwKeySpec, [In][Out] ref SafeKeyHandleImpl phUserKey);
Example #33
0
 public static extern bool CryptHashSessionKey([In] SafeHashHandleImpl hHash, [In] SafeKeyHandleImpl hKey, [In] uint dwFlags);
Example #34
0
 public static extern bool CryptDuplicateKey([In] IntPtr hKey, [In] byte[] pdwReserved, [In] uint dwFlags, [In][Out] ref SafeKeyHandleImpl phKey);
        private void GetKeyPair()
        {
            if (_keyHandle == null)
            {
                lock (this)
                {
                    if (_keyHandle == null)
                    {
                        SafeProvHandleImpl providerHandle;
                        SafeKeyHandleImpl keyHandle;

                        GetKeyPairValue(_providerParameters, _isRandomKeyContainer, out providerHandle, out keyHandle);

                        _providerHandle = providerHandle;
                        _keyHandle = keyHandle;

                        _isPersistentKey = true;
                    }
                }
            }
        }
Example #36
0
 public static extern bool CryptSetKeyParam([In] SafeKeyHandleImpl hKey, [In] uint dwParam, [In] byte[] pbData, [In] uint dwFlags);
Example #37
0
 public static SafeKeyHandleImpl DuplicateKey(SafeKeyHandleImpl sourceKeyHandle)
 {
     return(DuplicateKey(sourceKeyHandle.DangerousGetHandle()));
 }
Example #38
0
 public static extern bool CryptImportKey([In] SafeProvHandleImpl hCryptProv, [In] byte[] pbData, [In] uint dwDataLen, [In] SafeKeyHandleImpl hPubKey, [In] uint dwFlags, [In][Out] ref SafeKeyHandleImpl phKey);
Example #39
0
        public static int EncryptData(ProviderType providerType, SafeKeyHandleImpl symKeyHandle, byte[] data, int dataOffset, int dataLength, ref byte[] encryptedData, int encryptedDataOffset, PaddingMode paddingMode, bool isDone, bool isStream)
        {
            if (dataOffset < 0)
            {
                throw ExceptionUtility.ArgumentOutOfRange(nameof(dataOffset));
            }

            if (dataLength < 0)
            {
                throw ExceptionUtility.ArgumentOutOfRange(nameof(dataLength));
            }

            if (dataOffset > data.Length)
            {
                throw ExceptionUtility.ArgumentOutOfRange(nameof(dataOffset), Resources.InvalidDataOffset);
            }

            var length = dataLength;

            if (isDone)
            {
                length += 8;
            }

            // Выровненные данные
            var dataAlignLength = (uint)dataLength;
            var dataAlignArray  = new byte[length];

            Array.Clear(dataAlignArray, 0, length);
            Array.Copy(data, dataOffset, dataAlignArray, 0, dataLength);

            if (isDone)
            {
                var dataPadding     = dataLength & 7;
                var dataPaddingSize = (byte)(8 - dataPadding);

                // Добпаление дополнения данных в зависимости от настроек
                switch (paddingMode)
                {
                case PaddingMode.None:
                    if ((dataPadding != 0) && !isStream)
                    {
                        throw ExceptionUtility.CryptographicException(Resources.EncryptInvalidDataSize);
                    }

                    break;

                case PaddingMode.Zeros:
                    if (dataPadding != 0)
                    {
                        dataAlignLength += dataPaddingSize;

                        // Дополнение заполняется нулевыми байтами
                    }

                    break;

                case PaddingMode.PKCS7:
                {
                    dataAlignLength += dataPaddingSize;

                    var paddingIndex = dataLength;

                    // Дополнение заполняется байтами, в каждый из которых записывается размер дополнения
                    while (paddingIndex < dataAlignLength)
                    {
                        dataAlignArray[paddingIndex++] = dataPaddingSize;
                    }
                }
                break;

                case PaddingMode.ANSIX923:
                {
                    dataAlignLength += dataPaddingSize;

                    // Дополнение заполняется нулевыми, кроме последнего - в него записывается размер дополнения
                    dataAlignArray[(int)((IntPtr)(dataAlignLength - 1))] = dataPaddingSize;
                }
                break;

                case PaddingMode.ISO10126:
                {
                    dataAlignLength += dataPaddingSize;

                    // Дополнение заполняется случайными байтами, кроме последнего - в него записывается размер дополнения
                    var randomPadding = new byte[dataPaddingSize - 1];
                    GetRandomNumberGenerator(providerType).GetBytes(randomPadding);
                    randomPadding.CopyTo(dataAlignArray, dataLength);
                    dataAlignArray[(int)((IntPtr)(dataAlignLength - 1))] = dataPaddingSize;
                }
                break;

                default:
                    throw ExceptionUtility.Argument(nameof(paddingMode), Resources.InvalidPaddingMode);
                }
            }

            // Шифрование данных
            if (!CryptoApi.CryptEncrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, false, 0, dataAlignArray, ref dataAlignLength, (uint)length))
            {
                throw CreateWin32Error();
            }

            // Копирование результата шифрования данных

            if (encryptedData == null)
            {
                encryptedData = new byte[dataAlignLength];

                Array.Copy(dataAlignArray, 0L, encryptedData, 0L, dataAlignLength);
            }
            else
            {
                if (encryptedDataOffset < 0)
                {
                    throw ExceptionUtility.ArgumentOutOfRange(nameof(encryptedDataOffset));
                }

                if ((encryptedData.Length < dataAlignLength) || ((encryptedData.Length - dataAlignLength) < encryptedDataOffset))
                {
                    throw ExceptionUtility.ArgumentOutOfRange(nameof(encryptedDataOffset), Resources.InvalidDataOffset);
                }

                Array.Copy(dataAlignArray, 0L, encryptedData, encryptedDataOffset, dataAlignLength);
            }

            return((int)dataAlignLength);
        }
Example #40
0
 public static extern bool CryptCreateHash([In] SafeProvHandleImpl hProv, [In] uint Algid, [In] SafeKeyHandleImpl hKey, [In] uint dwFlags, [In][Out] ref SafeHashHandleImpl phHash);
Example #41
0
        public static int DecryptData(SafeKeyHandleImpl symKeyHandle, byte[] data, int dataOffset, int dataLength, ref byte[] decryptedData, int decryptedDataOffset, PaddingMode paddingMode, bool isDone)
        {
            if (dataOffset < 0)
            {
                throw ExceptionUtility.ArgumentOutOfRange(nameof(dataOffset));
            }

            if (dataLength < 0)
            {
                throw ExceptionUtility.ArgumentOutOfRange(nameof(dataLength));
            }

            if ((dataOffset > data.Length) || ((dataOffset + dataLength) > data.Length))
            {
                throw ExceptionUtility.ArgumentOutOfRange(nameof(dataOffset), Resources.InvalidDataOffset);
            }

            // Выровненные данные
            var dataAlignLength = (uint)dataLength;
            var dataAlign       = new byte[dataAlignLength];

            Array.Copy(data, dataOffset, dataAlign, 0L, dataAlignLength);

            // Расшифровка данных
            if (!CryptoApi.CryptDecrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, false, 0, dataAlign, ref dataAlignLength))
            {
                throw CreateWin32Error();
            }

            var length = (int)dataAlignLength;

            if (isDone)
            {
                byte dataPaddingSize = 0;

                // Удаление дополнения данных в зависимости от настроек
                if (((paddingMode == PaddingMode.PKCS7) || (paddingMode == PaddingMode.ANSIX923)) || (paddingMode == PaddingMode.ISO10126))
                {
                    if (dataAlignLength < 8)
                    {
                        throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA);
                    }

                    // Размер дополнения находится в последнем байте
                    dataPaddingSize = dataAlign[(int)((IntPtr)(dataAlignLength - 1))];

                    if (dataPaddingSize > 8)
                    {
                        throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA);
                    }

                    // Проверка корректности дополнения данных
                    if (paddingMode == PaddingMode.PKCS7)
                    {
                        for (var paddingIndex = dataAlignLength - dataPaddingSize; paddingIndex < (dataAlignLength - 1); paddingIndex++)
                        {
                            if (dataAlign[paddingIndex] != dataPaddingSize)
                            {
                                throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA);
                            }
                        }
                    }
                    else if (paddingMode == PaddingMode.ANSIX923)
                    {
                        for (var paddingIndex = dataAlignLength - dataPaddingSize; paddingIndex < (dataAlignLength - 1); paddingIndex++)
                        {
                            if (dataAlign[paddingIndex] != 0)
                            {
                                throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA);
                            }
                        }
                    }
                }
                else if ((paddingMode != PaddingMode.None) && (paddingMode != PaddingMode.Zeros))
                {
                    throw ExceptionUtility.Argument(nameof(paddingMode), Resources.InvalidPaddingMode);
                }

                length -= dataPaddingSize;
            }

            if (decryptedData == null)
            {
                decryptedData = new byte[length];

                Array.Copy(dataAlign, 0, decryptedData, 0, length);
            }
            else
            {
                if (decryptedDataOffset < 0)
                {
                    throw ExceptionUtility.ArgumentOutOfRange(nameof(decryptedDataOffset));
                }

                if ((decryptedData.Length < length) || ((decryptedData.Length - length) < decryptedDataOffset))
                {
                    throw ExceptionUtility.ArgumentOutOfRange(nameof(decryptedData), Resources.InvalidDataOffset);
                }

                Array.Copy(dataAlign, 0, decryptedData, decryptedDataOffset, length);
            }

            return(length);
        }
Example #42
0
 public static extern bool CryptEncrypt([In] SafeKeyHandleImpl hKey, [In] SafeHashHandleImpl hHash, [In][MarshalAs(UnmanagedType.Bool)] bool Final, [In] uint dwFlags, [In][Out] byte[] pbData, ref uint pdwDataLen, [In] uint dwBufLen);
 public Gost3410EphemeralAsymmetricAlgorithm()
 {
     _provHandle = CryptoApiHelper.ProviderHandle.DangerousAddRef();
     _keyHandle = CryptoApiHelper.GenerateKey(_provHandle, Constants.CALG_DH_EL_EPHEM, CspProviderFlags.NoFlags);
 }