示例#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>
        /// Wrap ключа Gost28147CryptoServiceProvider на agree
        /// по <see cref="GostKeyWrapMethod.GostKeyWrap"/>.
        /// </summary>
        ///
        /// <param name="prov">Шифруемый ключ.</param>
        ///
        /// <returns>Зашифрованный симметричный ключ.</returns>
        ///
        /// <exception cref="CryptographicException">При ошибках
        /// на managed уровне.</exception>
        private byte[] GostWrap(Gost28147CryptoServiceProvider prov)
        {
            SafeKeyHandle        hSimmKey   = prov.SafeKeyHandle;
            GostWrappedKeyObject wrappedKey = new GostWrappedKeyObject();
            SafeKeyHandle        hExpKey    = SafeKeyHandle.InvalidHandle;

            try
            {
                CapiHelper.ImportAndMakeSharedSecret(_safeProvHandle,
                                                     CspProviderFlags.NoFlags, _publicObject, _safeKeyHandle,
                                                     ref hExpKey, _algType);

                CapiHelper.SetKeyParamDw(hExpKey, GostConstants.KP_ALGID,
                                         GostConstants.CALG_SIMPLE_EXPORT);

                CapiHelper.ExportSessionWrapedKey(hSimmKey,
                                                  hExpKey, wrappedKey);
            }
            finally
            {
                if (!hExpKey.IsClosed)
                {
                    hExpKey.Close();
                }
            }
            return(wrappedKey.GetXmlWrappedKey());
        }
示例#3
0
        /// <summary>
        /// Расшифрование симметричного ключа по
        /// по <see cref="GostKeyWrapMethod.GostKeyWrap"/>.
        /// </summary>
        ///
        /// <param name="wrapped">Зашифрованный секретный ключ.</param>
        ///
        /// <returns>Объект класса <see cref="SymmetricAlgorithm"/>,
        /// содержащий расшифрованный закрытый ключ.</returns>
        ///
        /// <exception cref="CryptographicException">При ошибках
        /// на managed уровне.</exception>
        private SymmetricAlgorithm GostUnwrap(byte[] wrapped)
        {
            GostWrappedKeyObject gwk = new GostWrappedKeyObject();

            gwk.SetByXmlWrappedKey(wrapped);

            SafeKeyHandle simmKey = SafeKeyHandle.InvalidHandle;
            SafeKeyHandle hExpKey = SafeKeyHandle.InvalidHandle;

            try
            {
                CapiHelper.ImportAndMakeSharedSecret(_safeProvHandle,
                                                     CspProviderFlags.NoFlags, _publicObject, _safeKeyHandle,
                                                     ref hExpKey, _algType);

                CapiHelper.SetKeyParamDw(hExpKey, GostConstants.KP_ALGID,
                                         GostConstants.CALG_SIMPLE_EXPORT);

                CapiHelper.ImportSessionWrappedKey(_safeProvHandle,
                                                   CspProviderFlags.NoFlags, gwk, hExpKey, ref simmKey);
            }
            finally
            {
                if (!hExpKey.IsClosed)
                {
                    hExpKey.Close();
                }
            }

            return(new Gost28147CryptoServiceProvider(simmKey, _safeProvHandle));
        }
示例#4
0
        public override SymmetricAlgorithm Unwrap(byte[] wrapped,
                                                  GostKeyWrapMethod method)
        {
            GostWrappedKeyObject gwk = new GostWrappedKeyObject();

            gwk.SetByXmlWrappedKey(wrapped);
            if (method == GostKeyWrapMethod.CryptoProKeyWrap)
            {
                return(CryptoProUnwrap(wrapped, GostConstants.CALG_PRO_EXPORT));
            }
            else if (method == GostKeyWrapMethod.CryptoPro12KeyWrap)
            {
                // В случае с гостом 2012 мы не уверны, был ли экспорт на ProExport или ProExport12
                // из-за обратной совместимости (раньше шифровали на ProExport, теперь только на ProExport12). Попробуем оба варианата
                return(CryptoProUnwrap(wrapped));
            }
            else if (method == GostKeyWrapMethod.GostKeyWrap)
            {
                return(GostUnwrap(wrapped));
            }
            else
            {
                throw new ArgumentOutOfRangeException("method");
            }
        }
示例#5
0
        /// <summary>
        /// Получение структуры зашифрованного ключа на основе
        /// ASN.1 структуру Gost3410-KeyWrap.
        /// </summary>
        /// <param name="data">ASN.1 структура Gost3410-KeyWrap</param>
        public void SetByXmlWrappedKey(byte[] data)
        {
            GostWrappedKeyObject obj = new GostWrappedKeyObject();

            obj.SetByXmlWrappedKey(data);
            this = obj.WrappedKey;
        }
示例#6
0
        /// <summary>
        /// Wrap ключа Gost28147CryptoServiceProvider на agree
        /// по <see cref="GostKeyWrapMethod.CryptoProKeyWrap"/>.
        /// </summary>
        ///
        /// <param name="prov">Шифруемый ключ.</param>
        /// <param name="calgProExport">CALG алгоритма экспорта крипто про</param>
        /// <returns>Зашифрованный симметричный ключ.</returns>
        ///
        /// <exception cref="CryptographicException">При ошибках
        /// на managed уровне.</exception>
        private byte[] CryptoProWrap(Gost28147CryptoServiceProvider prov, int calgProExport = GostConstants.CALG_PRO_EXPORT)
        {
            if (calgProExport != GostConstants.CALG_PRO_EXPORT && calgProExport != GostConstants.CALG_PRO12_EXPORT)
            {
                throw new ArgumentOutOfRangeException("calgProExport");
            }

            SafeKeyHandle        hSimmKey   = prov.SafeKeyHandle;
            GostWrappedKeyObject wrappedKey = new GostWrappedKeyObject();
            SafeKeyHandle        hExpKey    = SafeKeyHandle.InvalidHandle;

            try
            {
                CapiHelper.ImportAndMakeSharedSecret(_safeProvHandle,
                                                     CspProviderFlags.NoFlags, _publicObject, _safeKeyHandle,
                                                     ref hExpKey, _algType);

                CapiHelper.SetKeyParamDw(hExpKey, GostConstants.KP_ALGID,
                                         calgProExport);

                CapiHelper.ExportSessionWrapedKey(hSimmKey,
                                                  hExpKey, wrappedKey);
            }
            finally
            {
                if (!hExpKey.IsClosed)
                {
                    hExpKey.Close();
                }
            }
            return(wrappedKey.GetXmlWrappedKey());
        }
示例#7
0
        /// <summary>
        /// Упаковка в ASN.1 структуру Gost3410-KeyWrap.
        /// </summary>
        /// <returns>Байтовый массив ASN.1 структуры Gost3410-KeyWrap.</returns>
        public byte[] GetXmlWrappedKey()
        {
            GostWrappedKeyObject obj = new GostWrappedKeyObject();

            obj.WrappedKey = this;
            return(obj.GetXmlWrappedKey());
        }
示例#8
0
        /// <summary>
        /// Вспомогательный метод, работающий для всех GOST3410
        /// </summary>
        /// <param name="createAgree"></param>
        /// <param name="exportParameters"></param>
        /// <param name="senderParameters"></param>
        /// <param name="alg"></param>
        /// <param name="keyWrapMethod"></param>
        /// <returns></returns>
        private GostKeyTransport GetGostTransport(
            Func <Gost3410Parameters, GostSharedSecretAlgorithm> createAgree,
            Func <bool, Gost3410Parameters> exportParameters,
            Gost3410Parameters senderParameters,
            SymmetricAlgorithm alg,
            GostKeyWrapMethod keyWrapMethod)
        {
            GostKeyTransportObject transport = new GostKeyTransportObject();

            byte[] wrapped_data;

            using (GostSharedSecretAlgorithm agree = createAgree(
                       senderParameters))
            {
                // Зашифровываем симметричный ключ.
                wrapped_data = agree.Wrap(alg,
                                          keyWrapMethod);
            }

            GostWrappedKeyObject wrapped = new GostWrappedKeyObject();

            wrapped.SetByXmlWrappedKey(wrapped_data);

            transport.sessionEncryptedKey_            = wrapped;
            transport.transportParameters_            = new Gost3410CspObject();
            transport.transportParameters_.Parameters = exportParameters(false);

            return(transport.Transport);
        }
        /// <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);
        }
示例#10
0
        /// <summary>
        /// Упаковка в SIMPLE_BLOB.
        /// </summary>
        /// <returns>Байтовый массив SIMPLE_BLOB.</returns>
        /// <exception cref="System.Security.Cryptography.CryptographicException">При ошибках
        /// кодирования структуры.</exception>
        ///
        /// <cspversions />
        public byte[] GetCryptoServiceProviderBlob()
        {
            GostWrappedKeyObject obj = new GostWrappedKeyObject();

            obj.WrappedKey = this;
            return(AsnHelper.EncodeSimpleBlob(obj,
                                              GostConstants.CALG_G28147));
        }
示例#11
0
        /// <summary>
        /// Распаковка объекта из SIMPLE_BLOB.
        /// </summary>
        /// <param name="data">Данные, закодированный SIMPLE_BLOB.</param>
        /// <exception cref="System.Security.Cryptography.CryptographicException">При ошибках
        /// декодирования структуры.</exception>
        /// <argnull name="data" />
        ///
        /// <cspversions />
        public void SetByCryptoServiceProviderBlob(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            GostWrappedKeyObject obj = new GostWrappedKeyObject();

            AsnHelper.DecodeSimpleBlob(obj, data);
            this = obj.WrappedKey;
        }
示例#12
0
        /// <summary>
        /// Расшифрование симметричного ключа по
        /// по <see cref="GostKeyWrapMethod.CryptoProKeyWrap"/>.
        /// </summary>
        ///
        /// <param name="wrapped">Зашифрованный секретный ключ.</param>
        /// <param name="calgProExport">OID алгоритма экспорта</param>
        /// <returns>Объект класса <see cref="SymmetricAlgorithm"/>,
        /// содержащий расшифрованный закрытый ключ.</returns>
        ///
        /// <exception cref="CryptographicException">При ошибках
        /// на managed уровне.</exception>
        private SymmetricAlgorithm CryptoProUnwrap(byte[] wrapped, int calgProExport)
        {
            if (calgProExport != GostConstants.CALG_PRO_EXPORT && calgProExport != GostConstants.CALG_PRO12_EXPORT)
            {
                throw new ArgumentOutOfRangeException("calgProExport");
            }

            GostWrappedKeyObject gwk = new GostWrappedKeyObject();

            gwk.SetByXmlWrappedKey(wrapped);

            SafeKeyHandle simmKey = SafeKeyHandle.InvalidHandle;
            SafeKeyHandle hExpKey = SafeKeyHandle.InvalidHandle;

            try
            {
                CapiHelper.ImportAndMakeSharedSecret(_safeProvHandle,
                                                     CspProviderFlags.NoFlags, _publicObject, _safeKeyHandle,
                                                     ref hExpKey, _algType);

                CapiHelper.SetKeyParamDw(hExpKey, GostConstants.KP_ALGID,
                                         calgProExport);

                CapiHelper.ImportSessionWrappedKey(_safeProvHandle,
                                                   CspProviderFlags.NoFlags, gwk, hExpKey, ref simmKey);
            }
            finally
            {
                if (!hExpKey.IsClosed)
                {
                    hExpKey.Close();
                }
            }

            return(new Gost28147CryptoServiceProvider(simmKey, _safeProvHandle));
        }