コード例 #1
0
        /// <summary>
        /// Экспортирует (шифрует) секретный ключ.
        /// </summary>
        /// <param name="prov">Шифруемый ключ.</param>
        /// <param name="method">Алгоритм экспорта ключа.</param>
        /// <returns>Зашифрованный симметричный ключ</returns>
        public override byte[] Wrap(Gost28147 prov, GostKeyWrapMethod method)
        {
            SafeKeyHandle hSimmKey = ((Gost28147CryptoServiceProvider)prov).SafeKeyHandle;
            int           calg     = GostConstants.CALG_SIMPLE_EXPORT;

            if (method == GostKeyWrapMethod.CryptoProKeyWrap)
            {
                calg = GostConstants.CALG_PRO_EXPORT;
            }
            else if (method == GostKeyWrapMethod.CryptoPro12KeyWrap)
            {
                calg = GostConstants.CALG_PRO12_EXPORT;
            }
            else if (method != GostKeyWrapMethod.GostKeyWrap)
            {
                throw new ArgumentOutOfRangeException("method");
            }
            byte[] ret = null;
            // Сохраняем состояние algid GOST12147
            using (SafeKeyHandle hExpKey = CapiHelper.DuplicateKey(
                       SafeKeyHandle.DangerousGetHandle(),
                       SafeProvHandle))
            {
                CapiHelper.SetKeyParameter(hExpKey, GostConstants.KP_ALGID, calg);
                CapiHelper.SetKeyParameter(hExpKey, GostConstants.KP_IV, IV);

                GostWrappedKeyObject wrappedKey = new GostWrappedKeyObject();
                CapiHelper.ExportSessionWrapedKey(hSimmKey,
                                                  hExpKey, wrappedKey);

                ret = wrappedKey.GetXmlWrappedKey();
            }
            return(ret);
        }
コード例 #2
0
        /// <summary>
        /// Создание объекта симметричного шифрования по HANDLE ключа.
        /// </summary>
        ///
        /// <remarks><para>При создании объекта симметричного шифрования
        /// параметры ключа устанавливаются в свои значения по умолчанию:</para>
        ///
        /// <table>
        /// <tr><th>Параметр</th><th>Значение</th></tr>
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.IV"/></td>
        /// <td><see langword="null"/></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.Mode"/></td>
        /// <td><see cref="System.Security.Cryptography.CipherMode.CFB"/></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.Padding"/></td>
        /// <td><see cref="System.Security.Cryptography.PaddingMode.None"/></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.KeySize"/></td>
        /// <td><c>256</c></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.FeedbackSize"/></td>
        /// <td><c>64</c></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.BlockSize"/></td>
        /// <td><c>64</c></td></tr>
        ///
        /// </table>
        ///
        /// <para>Класс становится владельцем ДУБЛЯ ключа и закрывает
        /// HANDLE при закрытии класса, HANDLE провайдера не дублируется,
        /// но увеличивается счетчик его использования (DangerousAddRef).
        /// </para>
        /// </remarks>
        ///
        /// <param name="keyHandle">HANDLE симметричного ключа.</param>
        /// <param name="provHandle">HANDLE провайдера.</param>
        ///
        /// <argnull name="keyHandle" />
        /// <exception cref="ArgumentException">Параметр <c>keyHandle</c>
        /// содержит ключ не алгоритма ГОСТ 28147.
        /// </exception>
        ///
        /// <unmanagedperm action="LinkDemand" />
        internal Gost28147CryptoServiceProvider(SafeKeyHandle keyHandle,
                                                SafeProvHandle provHandle) : this()
        {
            // корректность параметров CSP проверяется
            // при создании ecnryptor
            if (keyHandle == null)
            {
                throw new ArgumentNullException("keyHandle");
            }
            // Проверяем наличие провайдера поддерживающего ГОСТ 28147.
            // А куда CSP денется?
            //if (!CPUtils.HasAlgorithm(Constants.CALG_G28147, 0))
            //{
            //    throw new CryptographicException(
            //        Resources.Cryptography_CSP_AlgorithmNotAvailable);
            //}
            _safeKeyHandle = CapiHelper.DuplicateKey(
                keyHandle.DangerousGetHandle(),
                provHandle);

            bool succeded = false;

            provHandle.DangerousAddRef(ref succeded);
            _safeProvHandle = provHandle;

            int algid = CapiHelper.GetKeyParamDw(_safeKeyHandle, Constants.CLR_ALGID);

            if (algid != GostConstants.CALG_G28147)
            {
                throw new ArgumentException("keyHandle");
            }
            // KeySizeValue устанавливается в базовом классе.
            // FeedbackSizeValue устанавливается в базовом классе.
            // BlockSizeValue устанавливается в базовом классе.
        }
コード例 #3
0
        /// <summary>
        /// Импортирует (дешифрует) секретный ключ.
        /// </summary>
        /// <param name="wrapped">Зашифрованный секретный ключ.</param>
        /// <param name="method">Алгоритм экспорта ключа.</param>
        public override SymmetricAlgorithm Unwrap(byte[] wrapped, GostKeyWrapMethod method)
        {
            GostWrappedKeyObject gwk = new GostWrappedKeyObject();

            gwk.SetByXmlWrappedKey(wrapped);
            int calg = GostConstants.CALG_SIMPLE_EXPORT;

            if (method == GostKeyWrapMethod.CryptoProKeyWrap)
            {
                calg = GostConstants.CALG_PRO_EXPORT;
            }
            else if (method == GostKeyWrapMethod.CryptoPro12KeyWrap)
            {
                calg = GostConstants.CALG_PRO12_EXPORT;
            }
            else if (method != GostKeyWrapMethod.GostKeyWrap)
            {
                throw new ArgumentOutOfRangeException("method");
            }
            SymmetricAlgorithm ret = null;

            // Сохраняем состояние algid GOST12147
            using (SafeKeyHandle hExpKey = CapiHelper.DuplicateKey(SafeKeyHandle.DangerousGetHandle()))
            {
                CapiHelper.SetKeyParamDw(hExpKey, GostConstants.KP_ALGID, calg);
                SafeKeyHandle simmKey = SafeKeyHandle.InvalidHandle;
                CapiHelper.AcquireCsp(_parameters, out SafeProvHandle hProv);

                CapiHelper.ImportSessionWrappedKey(
                    hProv, CspProviderFlags.NoFlags,
                    gwk, hExpKey, ref simmKey);
                ret = new Gost28147CryptoServiceProvider(simmKey, hProv);
            }
            return(ret);
        }
コード例 #4
0
        public override ICryptoTransform CreateDecryptor()
        {
            // При обращении к KeyHandle возможна генерация ключа.
            SafeKeyHandle hDupKey = CapiHelper.DuplicateKey(SafeKeyHandle.DangerousGetHandle());

            // При обращении к IV возможна генерация синхропосылки.
            return(CreateTransform(false));
        }
コード例 #5
0
        /// <summary>
        /// Создание объекта симметричного шифрования по HANDLE ключа.
        /// </summary>
        ///
        /// <remarks><para>При создании объекта симметричного шифрования
        /// параметры ключа устанавливаются в свои значения по умолчанию:</para>
        ///
        /// <table>
        /// <tr><th>Параметр</th><th>Значение</th></tr>
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.IV"/></td>
        /// <td><see langword="null"/></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.Mode"/></td>
        /// <td><see cref="System.Security.Cryptography.CipherMode.CFB"/></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.Padding"/></td>
        /// <td><see cref="System.Security.Cryptography.PaddingMode.None"/></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.KeySize"/></td>
        /// <td><c>256</c></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.FeedbackSize"/></td>
        /// <td><c>64</c></td></tr>
        ///
        /// <tr><td><see cref="System.Security.Cryptography.SymmetricAlgorithm.BlockSize"/></td>
        /// <td><c>64</c></td></tr>
        ///
        /// </table>
        ///
        /// <para>Класс становится владельцем ДУБЛЯ ключа и закрывает
        /// HANDLE при закрытии класса, HANDLE провайдера не дублируется,
        /// но увеличивается счетчик его использования (DangerousAddRef).
        /// </para>
        /// </remarks>
        ///
        /// <param name="keyHandle">HANDLE симметричного ключа.</param>
        /// <param name="providerHandle">HANDLE провайдера.</param>
        ///
        /// <argnull name="keyHandle" />
        /// <exception cref="ArgumentException">Параметр <c>keyHandle</c>
        /// содержит ключ не алгоритма ГОСТ 28147.
        /// </exception>
        ///
        /// <unmanagedperm action="Demand" />
        public Gost28147CryptoServiceProvider(IntPtr keyHandle, IntPtr providerHandle)
            : this()
        {
            _safeProvHandle = new SafeProvHandle(providerHandle, true);
            _safeKeyHandle  = CapiHelper.DuplicateKey(keyHandle);
            int algid = CapiHelper.GetKeyParamDw(_safeKeyHandle, Constants.CLR_ALGID);

            if (algid != GostConstants.CALG_G28147)
            {
                throw new ArgumentException("algid");
            }
        }
コード例 #6
0
        private ICryptoTransform CreateTransform(bool encrypting)
        {
            // При обращении к KeyHandle возможна генерация ключа.
            SafeKeyHandle hDupKey = CapiHelper.DuplicateKey(
                SafeKeyHandle.DangerousGetHandle(),
                SafeProvHandle);

            // Добавляем ссылку на провайдер
            bool success = false;

            SafeProvHandle.DangerousAddRef(ref success);

            // При обращении к IV возможна генерация синхропосылки.

            return(CreateTransformCore(
                       SafeProvHandle,
                       hDupKey,
                       base.ModeValue,
                       base.PaddingValue,
                       IV,
                       base.BlockSizeValue,
                       base.FeedbackSizeValue,
                       encrypting));
        }