Exemple #1
0
 /// <summary>
 /// Импорт параметров алгоритма.
 /// </summary>
 ///
 /// <param name="parameters">Параметры алгоритма.</param>
 ///
 /// <exception cref="CryptographicException">Всегда.
 /// </exception>
 public override void ImportParameters(Gost3410Parameters parameters)
 {
     // Импорт открытого ключа - это создание agree,
     // Переустановка параметров не поддерживается.
     // Имеет смысл реализовывать только импорт private
     throw new NotSupportedException();
 }
        /// <summary>
        ///     <para>
        ///         ImportParameters will replace the existing key that Gost3410Cng is working with by creating a
        ///         new CngKey for the parameters structure.
        ///     </para>
        /// </summary>
        /// <exception cref="ArgumentException">
        ///     if <paramref name="parameters" /> contains neither an exponent nor a modulus.
        /// </exception>
        /// <exception cref="CryptographicException">
        ///     if <paramref name="parameters" /> is not a valid RSA key or if <paramref name="parameters"
        ///     /> is a full key pair and the default KSP is used.
        /// </exception>
        public override void ImportParameters(Gost3410Parameters parameters) ///!!!!!!
        {
            unsafe
            {
                bool includePrivate = true;
                int  blobSize       = sizeof(BCRYPT_GOSTKEY_BLOB);

                byte[] gostBlob = new byte[blobSize];
                fixed(byte *pgostBlob = &gostBlob[0])
                {
                    // Build the header
                    BCRYPT_GOSTKEY_BLOB *pBcryptBlob = (BCRYPT_GOSTKEY_BLOB *)pgostBlob;

                    pBcryptBlob->PublicKeyParamSet  = parameters.PublicKeyParamSet.Length;
                    pBcryptBlob->DigestParamSet     = parameters.DigestParamSet.Length;
                    pBcryptBlob->EncryptionParamSet = parameters.EncryptionParamSet.Length;
                    pBcryptBlob->PublicKey          = parameters.PublicKey.Length * 8;
                    pBcryptBlob->PrivateKey         = parameters.PrivateKey.Length * 8;

                    int offset = sizeof(BCRYPT_GOSTKEY_BLOB);

                    Interop.BCrypt.Emit(gostBlob, ref offset, parameters.PublicKeyParamSet);
                    Interop.BCrypt.Emit(gostBlob, ref offset, parameters.DigestParamSet);
                    Interop.BCrypt.Emit(gostBlob, ref offset, parameters.EncryptionParamSet);
                    Interop.BCrypt.Emit(gostBlob, ref offset, parameters.PublicKey);
                    Interop.BCrypt.Emit(gostBlob, ref offset, parameters.PrivateKey);

                    // We better have computed the right allocation size above!
                    Debug.Assert(offset == blobSize, "offset == blobSize");
                }

                ImportKeyBlob(gostBlob, includePrivate);
            }
        }
        /// <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);
        }
        public override Gost3410Parameters ExportParameters(bool includePrivateParameters) ///!!!!!!
        {
            byte[]             gostBlob   = ExportKeyBlob(includePrivateParameters);
            Gost3410Parameters gostParams = new Gost3410Parameters();

            ExportParameters(ref gostParams, gostBlob, includePrivateParameters);
            return(gostParams);
        }
Exemple #5
0
        /// <summary>
        /// Создание ключа согласования.
        /// </summary>
        ///
        /// <param name="alg">Параметры открытого ключа.</param>
        ///
        /// <returns>Распределенный секрет.</returns>
        ///
        /// <intdoc>Не проверяем возможность SharedSecret,
        /// мы используем из контейнера только открытый ключ.</intdoc>
        public override GostSharedSecretAlgorithm CreateAgree(
            Gost3410Parameters alg)
        {
            // Превращаем его в объект для экспорта.
            Gost3410CspObject obj1 = new Gost3410CspObject(alg);

            return(new GostSharedSecretCryptoServiceProvider(_safeKeyHandle,
                                                             _safeProvHandle, obj1, CspAlgorithmType.Gost2001));
        }
Exemple #6
0
        /// <summary>
        /// Инициализация алгоритма с заданными параметрами.
        /// </summary>
        /// <param name="basedOn">Параметры алгоритма, на основе которого
        /// будет сформирована секретная ключевая пара. Используется
        /// OID хэширования и открытого ключа, остальные параметры не
        /// используются.</param>
        public Gost3410EphemeralCryptoServiceProvider(Gost3410Parameters basedOn)
        {
            _safeKeyHandle  = SafeKeyHandle.InvalidHandle;
            _safeProvHandle = AcquireSafeProviderHandle();

            // Генерация эфимерного ключа без возможности экспорта бессмысленна.
            // Остальные флаги не тащим.
            CapiHelper.GenerateKey(_safeProvHandle,
                                   GostConstants.CALG_DH_EL_EPHEM, CspProviderFlags.NoFlags,
                                   GostConstants.GOST_3410EL_SIZE, basedOn.DigestParamSet,
                                   basedOn.PublicKeyParamSet, out _safeKeyHandle);
        }
Exemple #7
0
        public static Gost3410 Create(Gost3410Parameters parameters)
        {
            Gost3410 gost = Create();

            try
            {
                gost.ImportParameters(parameters);
                return(gost);
            }
            catch
            {
                gost.Dispose();
                throw;
            }
        }
        private static void ExportParameters(ref Gost3410Parameters gostParams, byte[] gostBlob, bool includePrivateParameters)
        {
            unsafe
            {
                // Fail-fast if a rogue provider gave us a blob that isn't even the size of the blob header.
                if (gostBlob.Length < sizeof(BCRYPT_GOSTKEY_BLOB))
                    throw new CryptographicException(ErrorCode.E_FAIL.ToString());

                fixed(byte *pGostBlob = &gostBlob[0])
                {
                    BCRYPT_GOSTKEY_BLOB *pBcryptBlob = (BCRYPT_GOSTKEY_BLOB *)pGostBlob;

                    int offset = sizeof(BCRYPT_GOSTKEY_BLOB);

                    gostParams.PublicKeyParamSet  = Interop.BCrypt.Consume(gostBlob, ref offset, pBcryptBlob->PublicKeyParamSet);
                    gostParams.DigestParamSet     = Interop.BCrypt.Consume(gostBlob, ref offset, pBcryptBlob->DigestParamSet);
                    gostParams.EncryptionParamSet = Interop.BCrypt.Consume(gostBlob, ref offset, pBcryptBlob->EncryptionParamSet);
                    gostParams.PublicKey          = Interop.BCrypt.Consume(gostBlob, ref offset, pBcryptBlob->PublicKey);
                    gostParams.PrivateKey         = Interop.BCrypt.Consume(gostBlob, ref offset, pBcryptBlob->PrivateKey);
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Импорт параметров <see cref="Gost3410Parameters"/>
        /// алгоритма ГОСТ Р 34.10-2012 256.
        /// </summary>
        ///
        /// <param name="parameters">Параметры алгоритма
        /// ГОСТ Р 34.10-2012 256</param>
        ///
        /// <doc-sample path="Simple\DocBlock" name="ImportParameters"
        /// region="ImportParameters" />
        ///
        /// <exception cref="CryptographicException">При импорте секретного
        /// ключа.</exception>
        ///
        /// <remarks>
        /// <if notdefined="userimp"><para>В данной сборке при импорте
        /// секретного ключа всегда возбуждает исключение
        /// <see cref="CryptographicException"/>.</para></if>
        /// </remarks>
        ///
        /// <containerperm flag="Open">Для открытия существующего
        /// контейнера.</containerperm>
        /// <containerperm flag="Create">Для создания контейнера с заданным
        /// (не случайным именем).</containerperm>
        /// <containerperm flag="Import">Для импорта секретного ключа.
        /// </containerperm>
        public override void ImportParameters(Gost3410Parameters parameters)
        {
            Gost3410CspObject pubKey = new Gost3410CspObject(parameters);

            if ((_safeKeyHandle != null) && !_safeKeyHandle.IsClosed)
            {
                _safeKeyHandle.Dispose();
            }

            _safeKeyHandle = SafeKeyHandle.InvalidHandle;
            if (Gost3410_2012_256CryptoServiceProvider.IsPublic(parameters))
            {
                SafeKeyHandle safeKeyHandle;
                // Это открытый ключ, поэтому можно его export
                // в verify context.
                // Нет обращения к секретному ключу, поэтому
                // не создаем контейнер без надобности.
                var safeProvHandleTemp = AcquireSafeProviderHandle();
                if (pubKey == null)
                {
                    throw new ArgumentNullException(nameof(pubKey));
                }

                byte[] keyBlob = AsnHelper.EncodePublicBlob(pubKey, CspAlgorithmType.Gost2012_256);
                CapiHelper.ImportKeyBlob(
                    safeProvHandleTemp,
                    CspProviderFlags.NoFlags,
                    false,
                    keyBlob,
                    out safeKeyHandle);

                _safeKeyHandle = safeKeyHandle;
                _publicOnly    = true;
                return;
            }

            throw new CryptographicException(SR.CspParameter_invalid, "Cryptography_UserExportBulkBlob");
            //throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspKeyContainerInfo)));
        }
Exemple #10
0
 public override void ImportParameters(Gost3410Parameters parameters)
 {
     throw null;
 }
Exemple #11
0
 /// <summary>
 /// Проверка, что переданные параметры, являются параметрами
 /// только открытого ключа.
 /// </summary>
 ///
 /// <param name="gostParams">Проверяемые параметры.</param>
 ///
 /// <returns><see langword="true"/>, если параметры не содержат, секретного
 /// ключа</returns>
 private static bool IsPublic(Gost3410Parameters gostParams)
 {
     return(gostParams.PrivateKey == null);
 }
Exemple #12
0
 public abstract bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm); // => throw DerivedClassMustOverride();
 public abstract GostSharedSecretAlgorithm CreateAgree(Gost3410Parameters alg);
Exemple #13
0
 public abstract void ImportParameters(Gost3410Parameters parameters);