Add migrated to .NET 8.0 variant of Hcs.Client

This commit is contained in:
2025-09-26 19:48:32 +09:00
parent da127df8f6
commit 6cd2fb82e9
503 changed files with 223796 additions and 0 deletions

View File

@ -0,0 +1,54 @@
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для всех асимметричных алгоритмов ГОСТ
/// </summary>
public abstract class GostAsymmetricAlgorithm : AsymmetricAlgorithm, IGostAlgorithm
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
/// <param name="keySize">Размер ключа в битах</param>
protected GostAsymmetricAlgorithm(ProviderType providerType, int keySize)
{
ProviderType = providerType;
KeySizeValue = keySize;
LegalKeySizesValue = new[] { new KeySizes(keySize, keySize, 0) };
}
/// <inheritdoc />
public ProviderType ProviderType { get; }
/// <inheritdoc />
public abstract string AlgorithmName { get; }
/// <summary>
/// Вычисляет цифровую подпись
/// </summary>
public abstract byte[] CreateSignature(byte[] hash);
/// <summary>
/// Проверяет цифровую подпись
/// </summary>
public abstract bool VerifySignature(byte[] hash, byte[] signature);
/// <summary>
/// Создает экземпляр <see cref="GostHashAlgorithm"/>
/// </summary>
public abstract GostHashAlgorithm CreateHashAlgorithm();
/// <summary>
/// Создает экземпляр <see cref="GostKeyExchangeFormatter"/>
/// </summary>
/// <returns></returns>
public abstract GostKeyExchangeFormatter CreateKeyExchangeFormatter();
/// <summary>
/// Создает экземпляр <see cref="GostKeyExchangeDeformatter"/>
/// </summary>
public abstract GostKeyExchangeDeformatter CreateKeyExchangeDeformatter();
}
}

View File

@ -0,0 +1,53 @@
using GostCryptography.Properties;
using System;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// На базе заданного экземпляра <see cref="AsymmetricAlgorithm"/> пытается реализовать <see cref="GostAsymmetricAlgorithm"/>.
/// Данный класс предназначен для интеграции со сторонними библиотеками и предназначен для внутреннего использования.
/// </summary>
sealed class GostExternalAsymmetricAlgorithm : GostAsymmetricAlgorithm
{
private readonly AsymmetricAlgorithm _algorithm;
private readonly Func<byte[], byte[]> _createSignature;
private readonly Func<byte[], byte[], bool> _verifySignature;
public GostExternalAsymmetricAlgorithm(AsymmetricAlgorithm algorithm) : base(default(ProviderType), algorithm.KeySize)
{
var createSignatureMethod = algorithm.GetType().GetMethod(nameof(CreateSignature), new[] { typeof(byte[]) });
var verifySignatureMethod = algorithm.GetType().GetMethod(nameof(VerifySignature), new[] { typeof(byte[]), typeof(byte[]) });
if ((createSignatureMethod == null || createSignatureMethod.ReturnType != typeof(byte[]))
|| (verifySignatureMethod == null || verifySignatureMethod.ReturnType != typeof(bool)))
{
throw ExceptionUtility.Argument(nameof(algorithm), Resources.ShouldSupportGost3410);
}
_algorithm = algorithm;
_createSignature = hash => (byte[])createSignatureMethod.Invoke(algorithm, new object[] { hash });
_verifySignature = (hash, signature) => (bool)verifySignatureMethod.Invoke(algorithm, new object[] { hash, signature });
}
public override string AlgorithmName => _algorithm.SignatureAlgorithm;
public override string SignatureAlgorithm => _algorithm.SignatureAlgorithm;
public override string KeyExchangeAlgorithm => _algorithm.KeyExchangeAlgorithm;
public override string ToXmlString(bool includePrivateKey) => _algorithm.ToXmlString(includePrivateKey);
public override void FromXmlString(string keyParametersXml) => _algorithm.FromXmlString(keyParametersXml);
public override byte[] CreateSignature(byte[] hash) => _createSignature(hash);
public override bool VerifySignature(byte[] hash, byte[] signature) => _verifySignature(hash, signature);
public override GostHashAlgorithm CreateHashAlgorithm() => throw ExceptionUtility.NotSupported();
public override GostKeyExchangeFormatter CreateKeyExchangeFormatter() => throw ExceptionUtility.NotSupported();
public override GostKeyExchangeDeformatter CreateKeyExchangeDeformatter() => throw ExceptionUtility.NotSupported();
}
}

View File

@ -0,0 +1,42 @@
using GostCryptography.Config;
using System.Security;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для всех реализаций Hash-based Message Authentication Code (HMAC) на базе алгоритмов ГОСТ
/// </summary>
public abstract class GostHMAC : HMAC, IGostAlgorithm
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="hashSize">Размер хэш-кода в битах</param>
/// <remarks>
/// По умолчанию использует криптографический провайдер, установленный в <see cref="GostCryptoConfig.ProviderType"/>
/// </remarks>
[SecuritySafeCritical]
protected GostHMAC(int hashSize) : this(GostCryptoConfig.ProviderType, hashSize)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
/// <param name="hashSize">Размер хэш-кода в битах</param>
[SecuritySafeCritical]
protected GostHMAC(ProviderType providerType, int hashSize)
{
ProviderType = providerType;
HashSizeValue = hashSize;
}
/// <inheritdoc />
public ProviderType ProviderType { get; }
/// <inheritdoc />
public abstract string AlgorithmName { get; }
}
}

View File

@ -0,0 +1,42 @@
using GostCryptography.Config;
using System.Security;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для всех алгоритмов хэширования ГОСТ
/// </summary>
public abstract class GostHashAlgorithm : HashAlgorithm, IGostAlgorithm
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="hashSize">Размер хэш-кода в битах</param>
/// <remarks>
/// По умолчанию использует криптографический провайдер, установленный в <see cref="GostCryptoConfig.ProviderType"/>
/// </remarks>
[SecuritySafeCritical]
protected GostHashAlgorithm(int hashSize) : this(GostCryptoConfig.ProviderType, hashSize)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
/// <param name="hashSize">Размер хэш-кода в битах</param>
[SecuritySafeCritical]
protected GostHashAlgorithm(ProviderType providerType, int hashSize)
{
ProviderType = providerType;
HashSizeValue = hashSize;
}
/// <inheritdoc />
public ProviderType ProviderType { get; }
/// <inheritdoc />
public abstract string AlgorithmName { get; }
}
}

View File

@ -0,0 +1,74 @@
using GostCryptography.Config;
using System;
using System.Security;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс всех реализаций общего секретного ключа ГОСТ
/// </summary>
public abstract class GostKeyExchangeAlgorithm : IDisposable, IGostAlgorithm
{
/// <summary>
/// Конструктор
/// </summary>
/// <remarks>
/// По умолчанию использует криптографический провайдер, установленный в <see cref="GostCryptoConfig.ProviderType"/>
/// </remarks>
[SecuritySafeCritical]
protected GostKeyExchangeAlgorithm() : this(GostCryptoConfig.ProviderType)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
[SecuritySafeCritical]
protected GostKeyExchangeAlgorithm(ProviderType providerType)
{
ProviderType = providerType;
}
/// <inheritdoc />
public ProviderType ProviderType { get; }
/// <inheritdoc />
public virtual string AlgorithmName => GetType().Name;
/// <summary>
/// Экспортирует (шифрует) общий секретный ключ
/// </summary>
/// <param name="keyExchangeAlgorithm">Общий секретный ключ</param>
/// <param name="keyExchangeExportMethod">Алгоритм экспорта общего секретного ключа</param>
public abstract byte[] EncodeKeyExchange(SymmetricAlgorithm keyExchangeAlgorithm, GostKeyExchangeExportMethod keyExchangeExportMethod);
/// <summary>
/// Импортирует (дешифрует) общий секретный ключ
/// </summary>
/// <param name="encodedKeyExchangeData">Общий секретный ключ</param>
/// <param name="keyExchangeExportMethod">Алгоритм экспорта общего секретного ключа</param>
public abstract SymmetricAlgorithm DecodeKeyExchange(byte[] encodedKeyExchangeData, GostKeyExchangeExportMethod keyExchangeExportMethod);
/// <summary>
/// Освобождает неуправляемые ресурсы
/// </summary>
protected virtual void Dispose(bool disposing)
{
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <inheritdoc />
~GostKeyExchangeAlgorithm()
{
Dispose(false);
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для дешифрования общего секретного ключа по ГОСТ
/// </summary>
public abstract class GostKeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter
{
/// <summary>
/// Дешифрует общий секретный ключ
/// </summary>
/// <param name="encryptedKeyExchangeData">Зашифрованный общий секретный ключ</param>
/// <exception cref="ArgumentNullException"></exception>
public abstract SymmetricAlgorithm DecryptKeyExchangeAlgorithm(byte[] encryptedKeyExchangeData);
}
}

View File

@ -0,0 +1,18 @@
namespace GostCryptography.Base
{
/// <summary>
/// Алгоритм экспорта общего секретного ключа ГОСТ
/// </summary>
public enum GostKeyExchangeExportMethod
{
/// <summary>
/// Простой экспорт ключа по ГОСТ 28147-89
/// </summary>
GostKeyExport,
/// <summary>
/// Защищённый экспорт ключа по алгоритму КриптоПро
/// </summary>
CryptoProKeyExport
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для шифрования общего секретного ключа по ГОСТ
/// </summary>
public abstract class GostKeyExchangeFormatter : AsymmetricKeyExchangeFormatter
{
/// <summary>
/// Шифрует общий секретный ключ
/// </summary>
/// <param name="keyExchangeAlgorithm">Алгоритм шифрования общего секретного ключа</param>
/// <exception cref="ArgumentNullException"></exception>
public abstract byte[] CreateKeyExchangeData(SymmetricAlgorithm keyExchangeAlgorithm);
}
}

View File

@ -0,0 +1,42 @@
using GostCryptography.Config;
using System.Security;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для всех алгоритмов хэширования ГОСТ на основе ключей
/// </summary>
public abstract class GostKeyedHashAlgorithm : KeyedHashAlgorithm, IGostAlgorithm
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="hashSize">Размер хэш-кода в битах</param>
/// <remarks>
/// По умолчанию использует криптографический провайдер, установленный в <see cref="GostCryptoConfig.ProviderType"/>
/// </remarks>
[SecuritySafeCritical]
protected GostKeyedHashAlgorithm(int hashSize) : this(GostCryptoConfig.ProviderType, hashSize)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
/// <param name="hashSize">Размер хэш-кода в битах</param>
[SecuritySafeCritical]
protected GostKeyedHashAlgorithm(ProviderType providerType, int hashSize)
{
ProviderType = providerType;
HashSizeValue = hashSize;
}
/// <inheritdoc />
public ProviderType ProviderType { get; }
/// <inheritdoc />
public abstract string AlgorithmName { get; }
}
}

View File

@ -0,0 +1,47 @@
using System;
using System.Security;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для всех алгоритмов генерации псевдослучайной последовательности (Pseudorandom Function, PRF) ГОСТ
/// </summary>
public abstract class GostPRF : IDisposable, IGostAlgorithm
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
[SecuritySafeCritical]
protected GostPRF(ProviderType providerType)
{
ProviderType = providerType;
}
/// <inheritdoc />
public ProviderType ProviderType { get; }
/// <inheritdoc />
public abstract string AlgorithmName { get; }
/// <summary>
/// Освобождает неуправляемые ресурсы
/// </summary>
protected virtual void Dispose(bool disposing)
{
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <inheritdoc />
~GostPRF()
{
Dispose(false);
}
}
}

View File

@ -0,0 +1,77 @@
using GostCryptography.Properties;
using System;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Класс проверки цифровой подписи ГОСТ
/// </summary>
public class GostSignatureDeformatter : AsymmetricSignatureDeformatter
{
/// <summary>
/// Конструктор
/// </summary>
public GostSignatureDeformatter()
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="publicKey">Открытый ключ для проверки цифровой подписи</param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="ArgumentNullException"></exception>
public GostSignatureDeformatter(AsymmetricAlgorithm publicKey) : this()
{
SetKey(publicKey);
}
private GostAsymmetricAlgorithm _publicKey;
/// <inheritdoc />
public override void SetKey(AsymmetricAlgorithm publicKey)
{
if (publicKey == null)
{
throw ExceptionUtility.ArgumentNull(nameof(publicKey));
}
if (!(publicKey is GostAsymmetricAlgorithm gostPublicKey))
{
if (publicKey.SignatureAlgorithm.IndexOf("gost", StringComparison.OrdinalIgnoreCase) < 0)
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(publicKey), Resources.ShouldSupportGost3410);
}
gostPublicKey = new GostExternalAsymmetricAlgorithm(publicKey);
}
_publicKey = gostPublicKey;
}
/// <inheritdoc />
public override void SetHashAlgorithm(string hashAlgorithmName)
{
}
/// <inheritdoc />
public override bool VerifySignature(byte[] hash, byte[] signature)
{
if (hash == null)
{
throw ExceptionUtility.ArgumentNull(nameof(hash));
}
if (signature == null)
{
throw ExceptionUtility.ArgumentNull(nameof(signature));
}
var reverseSignature = (byte[])signature.Clone();
Array.Reverse(reverseSignature);
return _publicKey.VerifySignature(hash, reverseSignature);
}
}
}

View File

@ -0,0 +1,11 @@
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Информация о свойствах цифровой подписи ГОСТ
/// </summary>
public abstract class GostSignatureDescription : SignatureDescription
{
}
}

View File

@ -0,0 +1,72 @@
using GostCryptography.Properties;
using System;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Класс вычисления цифровой подписи ГОСТ
/// </summary>
public class GostSignatureFormatter : AsymmetricSignatureFormatter
{
/// <summary>
/// Конструктор
/// </summary>
public GostSignatureFormatter()
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="privateKey">Закрытый ключ для вычисления цифровой подписи</param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="ArgumentNullException"></exception>
public GostSignatureFormatter(AsymmetricAlgorithm privateKey) : this()
{
SetKey(privateKey);
}
private GostAsymmetricAlgorithm _privateKey;
/// <inheritdoc />
public override void SetKey(AsymmetricAlgorithm privateKey)
{
if (privateKey == null)
{
throw ExceptionUtility.ArgumentNull(nameof(privateKey));
}
if (!(privateKey is GostAsymmetricAlgorithm gostPrivateKey))
{
if (privateKey.SignatureAlgorithm.IndexOf("gost", StringComparison.OrdinalIgnoreCase) < 0)
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(privateKey), Resources.ShouldSupportGost3410);
}
gostPrivateKey = new GostExternalAsymmetricAlgorithm(privateKey);
}
_privateKey = gostPrivateKey;
}
/// <inheritdoc />
public override void SetHashAlgorithm(string hashAlgorithmName)
{
}
/// <inheritdoc />
public override byte[] CreateSignature(byte[] hash)
{
if (hash == null)
{
throw ExceptionUtility.ArgumentNull(nameof(hash));
}
var reverseSignature = _privateKey.CreateSignature(hash);
Array.Reverse(reverseSignature);
return reverseSignature;
}
}
}

View File

@ -0,0 +1,39 @@
using GostCryptography.Config;
using System.Security;
using System.Security.Cryptography;
namespace GostCryptography.Base
{
/// <summary>
/// Базовый класс для всех алгоритмов симметричного шифрования ГОСТ
/// </summary>
public abstract class GostSymmetricAlgorithm : SymmetricAlgorithm, IGostAlgorithm
{
/// <summary>
/// Конструктор
/// </summary>
/// <remarks>
/// По умолчанию использует криптографический провайдер, установленный в <see cref="GostCryptoConfig.ProviderType"/>
/// </remarks>
[SecuritySafeCritical]
protected GostSymmetricAlgorithm() : this(GostCryptoConfig.ProviderType)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
[SecuritySafeCritical]
protected GostSymmetricAlgorithm(ProviderType providerType)
{
ProviderType = providerType;
}
/// <inheritdoc />
public ProviderType ProviderType { get; }
/// <inheritdoc />
public abstract string AlgorithmName { get; }
}
}

View File

@ -0,0 +1,18 @@
namespace GostCryptography.Base
{
/// <summary>
/// Алгоритм ГОСТ
/// </summary>
public interface IGostAlgorithm
{
/// <summary>
/// Тип криптографического провайдера
/// </summary>
ProviderType ProviderType { get; }
/// <summary>
/// Наименование криптографического алгоритма
/// </summary>
string AlgorithmName { get; }
}
}

View File

@ -0,0 +1,81 @@
using System.Collections.Generic;
namespace GostCryptography.Base
{
/// <summary>
/// Типы криптографических провайдеров
/// </summary>
public enum ProviderType
{
/// <summary>
/// Infotecs Cryptographic Service Provider
/// </summary>
VipNet = 2,
/// <summary>
/// Infotecs GOST 2012/512 Cryptographic Service Provider
/// </summary>
VipNet_2012_512 = 77,
/// <summary>
/// Infotecs GOST 2012/1024 Cryptographic Service Provider
/// </summary>
VipNet_2012_1024 = 78,
/// <summary>
/// Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider
/// </summary>
CryptoPro = 75,
/// <summary>
/// Crypto-Pro GOST R 34.10-2012 Cryptographic Service Provider
/// </summary>
CryptoPro_2012_512 = 80,
/// <summary>
/// Crypto-Pro GOST R 34.10-2012 Strong Cryptographic Service Provider
/// </summary>
CryptoPro_2012_1024 = 81
}
/// <summary>
/// Методы расширения <see cref="ProviderType"/>
/// </summary>
public static class ProviderTypesExtensions
{
/// <summary>
/// Набор провайдеров VipNet
/// </summary>
public static readonly HashSet<ProviderType> VipNetProviders = new HashSet<ProviderType>
{
ProviderType.VipNet,
ProviderType.VipNet_2012_512,
ProviderType.VipNet_2012_1024
};
/// <summary>
/// Набор провайдеров CryptoPro
/// </summary>
public static readonly HashSet<ProviderType> CryptoProProviders = new HashSet<ProviderType>
{
ProviderType.CryptoPro,
ProviderType.CryptoPro_2012_512,
ProviderType.CryptoPro_2012_1024
};
/// <summary>
/// Возвращает <see langword="true"/> для VipNet
/// </summary>
public static bool IsVipNet(this ProviderType providerType) => VipNetProviders.Contains(providerType);
/// <summary>
/// Возвращает <see langword="true"/> для CryptoPro
/// </summary>
public static bool IsCryptoPro(this ProviderType providerType) => CryptoProProviders.Contains(providerType);
/// <summary>
/// Преобразует значение в <see cref="int"/>
/// </summary>
public static int ToInt(this ProviderType providerType) => (int)providerType;
}
}