Add project

Basic formatting applied. Unnecessary comments have been removed. Suspicious code is covered by TODO.
This commit is contained in:
2025-08-12 11:21:10 +09:00
parent bbcbe841a7
commit 33ab055b43
546 changed files with 176950 additions and 0 deletions

View File

@ -0,0 +1,51 @@
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
using GostCryptography.Native;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация HMAC на базе алгоритма хэширования ГОСТ Р 34.11-2012/256
/// </summary>
public sealed class Gost_R3411_2012_256_HMAC : Gost_R3411_HMAC<Gost_R3411_2012_256_HashAlgorithm>
{
/// <summary>
/// Наименование алгоритма HMAC на базе ГОСТ Р 34.11-2012/256
/// </summary>
public const string AlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:hmac-gostr34112012-256";
/// <summary>
/// Известные наименования алгоритма HMAC на базе ГОСТ Р 34.11-2012/256
/// </summary>
public static readonly string[] KnownAlgorithmNames = { AlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_256_HMAC() : base(Gost_R3411_2012_256_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_256_HMAC(ProviderType providerType) : base(providerType, Gost_R3411_2012_256_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_256_HMAC(Gost_28147_89_SymmetricAlgorithmBase keyAlgorithm) : base(keyAlgorithm, Gost_R3411_2012_256_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
public override string AlgorithmName => AlgorithmNameValue;
/// <inheritdoc />
[SecuritySafeCritical]
protected override SafeHashHandleImpl CreateHashHMAC(ProviderType providerType, SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle)
{
return CryptoApiHelper.CreateHashHMAC_2012_256(providerType, providerHandle, symKeyHandle);
}
}
}

View File

@ -0,0 +1,54 @@
using GostCryptography.Base;
using GostCryptography.Native;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация алгоритма хэширования ГОСТ Р 34.11-2012/256
/// </summary>
public sealed class Gost_R3411_2012_256_HashAlgorithm : Gost_R3411_HashAlgorithm
{
/// <summary>
/// Размер хэша ГОСТ Р 34.11-2012/256
/// </summary>
public const int DefaultHashSizeValue = 256;
/// <summary>
/// Наименование алгоритма хэширования ГОСТ Р 34.11-2012/256
/// </summary>
public const string AlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34112012-256";
/// <summary>
/// Известные наименования алгоритма хэширования ГОСТ Р 34.11-2012/256
/// </summary>
public static readonly string[] KnownAlgorithmNames = { AlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_256_HashAlgorithm() : base(DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_256_HashAlgorithm(ProviderType providerType) : base(providerType, DefaultHashSizeValue)
{
}
[SecurityCritical]
internal Gost_R3411_2012_256_HashAlgorithm(ProviderType providerType, SafeProvHandleImpl providerHandle) : base(providerType, providerHandle, DefaultHashSizeValue)
{
}
/// <inheritdoc />
public override string AlgorithmName => AlgorithmNameValue;
/// <inheritdoc />
[SecurityCritical]
protected override SafeHashHandleImpl CreateHashHandle(SafeProvHandleImpl providerHandle)
{
return CryptoApiHelper.CreateHash_3411_2012_256(providerHandle);
}
}
}

View File

@ -0,0 +1,50 @@
using System.Security;
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация PRF на базе алгоритма хэширования ГОСТ Р 34.11-2012/256
/// </summary>
public sealed class Gost_R3411_2012_256_PRF : Gost_R3411_PRF<Gost_R3411_2012_256_HMAC>
{
/// <summary>
/// Наименование алгоритма PRF на базе ГОСТ Р 34.11-2012/256 для использования в протоколе WS-Trust
/// </summary>
public const string WsTrustAlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:ck-p-gostr3411-2012-256";
/// <summary>
/// Наименование алгоритма PRF на базе ГОСТ Р 34.11-2012/256 для использования в протоколах на базе WS-SecureConversation
/// </summary>
public const string WsSecureConversationAlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:dk-p-gostr3411-2012-256";
/// <summary>
/// Известные наименования алгоритма PRF на базе ГОСТ Р 34.11-2012/256
/// </summary>
public static readonly string[] KnownAlgorithmNames = { WsTrustAlgorithmNameValue, WsSecureConversationAlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_256_PRF(Gost_28147_89_SymmetricAlgorithmBase key, byte[] label, byte[] seed) : base(key, label, seed)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_256_PRF(ProviderType providerType, byte[] key, byte[] label, byte[] seed) : base(providerType, key, label, seed)
{
}
/// <inheritdoc />
public override string AlgorithmName => WsTrustAlgorithmNameValue;
/// <inheritdoc />
[SecuritySafeCritical]
protected override Gost_R3411_2012_256_HMAC CreateHMAC(Gost_28147_89_SymmetricAlgorithm key)
{
return new Gost_R3411_2012_256_HMAC(key);
}
}
}

View File

@ -0,0 +1,51 @@
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
using GostCryptography.Native;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация HMAC на базе алгоритма хэширования ГОСТ Р 34.11-2012/512
/// </summary>
public sealed class Gost_R3411_2012_512_HMAC : Gost_R3411_HMAC<Gost_R3411_2012_512_HashAlgorithm>
{
/// <summary>
/// Наименование алгоритма HMAC на базе ГОСТ Р 34.11-2012/512
/// </summary>
public const string AlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:hmac-gostr34112012-512";
/// <summary>
/// Известные наименования алгоритма HMAC на базе ГОСТ Р 34.11-2012/512
/// </summary>
public static readonly string[] KnownAlgorithmNames = { AlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_512_HMAC() : base(Gost_R3411_2012_512_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_512_HMAC(ProviderType providerType) : base(providerType, Gost_R3411_2012_512_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_512_HMAC(Gost_28147_89_SymmetricAlgorithmBase keyAlgorithm) : base(keyAlgorithm, Gost_R3411_2012_512_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
public override string AlgorithmName => AlgorithmNameValue;
/// <inheritdoc />
[SecuritySafeCritical]
protected override SafeHashHandleImpl CreateHashHMAC(ProviderType providerType, SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle)
{
return CryptoApiHelper.CreateHashHMAC_2012_512(providerType, providerHandle, symKeyHandle);
}
}
}

View File

@ -0,0 +1,54 @@
using GostCryptography.Base;
using GostCryptography.Native;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация алгоритма хэширования ГОСТ Р 34.11-2012/512
/// </summary>
public sealed class Gost_R3411_2012_512_HashAlgorithm : Gost_R3411_HashAlgorithm
{
/// <summary>
/// Размер хэша ГОСТ Р 34.11-2012/512
/// </summary>
public const int DefaultHashSizeValue = 512;
/// <summary>
/// Наименование алгоритма хэширования ГОСТ Р 34.11-2012/512
/// </summary>
public const string AlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34112012-512";
/// <summary>
/// Известные наименования алгоритма хэширования ГОСТ Р 34.11-2012/512
/// </summary>
public static readonly string[] KnownAlgorithmNames = { AlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_512_HashAlgorithm() : base(DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_512_HashAlgorithm(ProviderType providerType) : base(providerType, DefaultHashSizeValue)
{
}
[SecurityCritical]
internal Gost_R3411_2012_512_HashAlgorithm(ProviderType providerType, SafeProvHandleImpl providerHandle) : base(providerType, providerHandle, DefaultHashSizeValue)
{
}
/// <inheritdoc />
public override string AlgorithmName => AlgorithmNameValue;
/// <inheritdoc />
[SecurityCritical]
protected override SafeHashHandleImpl CreateHashHandle(SafeProvHandleImpl providerHandle)
{
return CryptoApiHelper.CreateHash_3411_2012_512(providerHandle);
}
}
}

View File

@ -0,0 +1,49 @@
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация PRF на базе алгоритма хэширования ГОСТ Р 34.11-2012/512
/// </summary>
public sealed class Gost_R3411_2012_512_PRF : Gost_R3411_PRF<Gost_R3411_2012_512_HMAC>
{
/// <summary>
/// Наименование алгоритма PRF на базе ГОСТ Р 34.11-2012/512 для использования в протоколе WS-Trust
/// </summary>
public const string WsTrustAlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:ck-p-gostr3411-2012-512";
/// <summary>
/// Наименование алгоритма PRF на базе ГОСТ Р 34.11-2012/512 для использования в протоколах на базе WS-SecureConversation
/// </summary>
public const string WsSecureConversationAlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:dk-p-gostr3411-2012-512";
/// <summary>
/// Известные наименования алгоритма PRF на базе ГОСТ Р 34.11-2012/512
/// </summary>
public static readonly string[] KnownAlgorithmNames = { WsTrustAlgorithmNameValue, WsSecureConversationAlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_512_PRF(Gost_28147_89_SymmetricAlgorithmBase key, byte[] label, byte[] seed) : base(key, label, seed)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_2012_512_PRF(ProviderType providerType, byte[] key, byte[] label, byte[] seed) : base(providerType, key, label, seed)
{
}
/// <inheritdoc />
public override string AlgorithmName => WsTrustAlgorithmNameValue;
/// <inheritdoc />
[SecuritySafeCritical]
protected override Gost_R3411_2012_512_HMAC CreateHMAC(Gost_28147_89_SymmetricAlgorithm key)
{
return new Gost_R3411_2012_512_HMAC(key);
}
}
}

View File

@ -0,0 +1,56 @@
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
using GostCryptography.Native;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация HMAC на базе алгоритма хэширования ГОСТ Р 34.11-94
/// </summary>
public sealed class Gost_R3411_94_HMAC : Gost_R3411_HMAC<Gost_R3411_94_HashAlgorithm>
{
/// <summary>
/// Наименование алгоритма HMAC на базе ГОСТ Р 34.11-94
/// </summary>
public const string AlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:hmac-gostr3411";
/// <summary>
/// Устаревшее наименование алгоритма HMAC на базе ГОСТ Р 34.11-94
/// </summary>
public const string ObsoleteAlgorithmNameValue = "http://www.w3.org/2001/04/xmldsig-more#hmac-gostr3411";
/// <summary>
/// Известные наименования алгоритма HMAC на базе ГОСТ Р 34.11-94
/// </summary>
public static readonly string[] KnownAlgorithmNames = { AlgorithmNameValue, ObsoleteAlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_94_HMAC() : base(Gost_R3411_94_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_94_HMAC(ProviderType providerType) : base(providerType, Gost_R3411_94_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_94_HMAC(Gost_28147_89_SymmetricAlgorithmBase keyAlgorithm) : base(keyAlgorithm, Gost_R3411_94_HashAlgorithm.DefaultHashSizeValue)
{
}
/// <inheritdoc />
public override string AlgorithmName => AlgorithmNameValue;
/// <inheritdoc />
[SecuritySafeCritical]
protected override SafeHashHandleImpl CreateHashHMAC(ProviderType providerType, SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle)
{
return CryptoApiHelper.CreateHashHMAC_94(providerType, providerHandle, symKeyHandle);
}
}
}

View File

@ -0,0 +1,59 @@
using GostCryptography.Base;
using GostCryptography.Native;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация алгоритма хэширования ГОСТ Р 34.11-94
/// </summary>
public sealed class Gost_R3411_94_HashAlgorithm : Gost_R3411_HashAlgorithm
{
/// <summary>
/// Размер хэша ГОСТ Р 34.11-94
/// </summary>
public const int DefaultHashSizeValue = 256;
/// <summary>
/// Наименование алгоритма хэширования ГОСТ Р 34.11-94
/// </summary>
public const string AlgorithmNameValue = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411";
/// <summary>
/// Устаревшее наименование алгоритма хэширования ГОСТ Р 34.11-94
/// </summary>
public const string ObsoleteAlgorithmNameValue = "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
/// <summary>
/// Известные наименования алгоритма хэширования ГОСТ Р 34.11-94
/// </summary>
public static readonly string[] KnownAlgorithmNames = { AlgorithmNameValue, ObsoleteAlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_94_HashAlgorithm() : base(DefaultHashSizeValue)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_94_HashAlgorithm(ProviderType providerType) : base(providerType, DefaultHashSizeValue)
{
}
[SecurityCritical]
internal Gost_R3411_94_HashAlgorithm(ProviderType providerType, SafeProvHandleImpl providerHandle) : base(providerType, providerHandle, DefaultHashSizeValue)
{
}
/// <inheritdoc />
public override string AlgorithmName => AlgorithmNameValue;
/// <inheritdoc />
[SecurityCritical]
protected override SafeHashHandleImpl CreateHashHandle(SafeProvHandleImpl providerHandle)
{
return CryptoApiHelper.CreateHash_3411_94(providerHandle);
}
}
}

View File

@ -0,0 +1,49 @@
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Реализация PRF на базе алгоритма хэширования ГОСТ Р 34.11-94
/// </summary>
public sealed class Gost_R3411_94_PRF : Gost_R3411_PRF<Gost_R3411_94_HMAC>
{
/// <summary>
/// Наименование алгоритма PRF на базе ГОСТ Р 34.11-94 для использования в протоколе WS-Trust
/// </summary>
public const string WsTrustAlgorithmNameValue = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/CK/PGOSTR3411";
/// <summary>
/// Наименование алгоритма PRF на базе ГОСТ Р 34.11-94 для использования в протоколах на базе WS-SecureConversation
/// </summary>
public const string WsSecureConversationAlgorithmNameValue = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk/p_gostr3411";
/// <summary>
/// Известные наименования алгоритма PRF на базе ГОСТ Р 34.11-94
/// </summary>
public static readonly string[] KnownAlgorithmNames = { WsTrustAlgorithmNameValue, WsSecureConversationAlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_94_PRF(Gost_28147_89_SymmetricAlgorithmBase key, byte[] label, byte[] seed) : base(key, label, seed)
{
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_R3411_94_PRF(ProviderType providerType, byte[] key, byte[] label, byte[] seed) : base(providerType, key, label, seed)
{
}
/// <inheritdoc />
public override string AlgorithmName => WsTrustAlgorithmNameValue;
/// <inheritdoc />
[SecuritySafeCritical]
protected override Gost_R3411_94_HMAC CreateHMAC(Gost_28147_89_SymmetricAlgorithm key)
{
return new Gost_R3411_94_HMAC(key);
}
}
}

View File

@ -0,0 +1,138 @@
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
using GostCryptography.Native;
using System;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Базовый класс для всех реализаций Hash-based Message Authentication Code (HMAC) на базе алгоритма хэширования ГОСТ Р 34.11
/// </summary>
public abstract class Gost_R3411_HMAC<THash> : GostHMAC, ISafeHandleProvider<SafeHashHandleImpl> where THash : GostHashAlgorithm
{
/// <inheritdoc />
[SecuritySafeCritical]
protected Gost_R3411_HMAC(int hashSize) : base(hashSize)
{
InitDefaults(new Gost_28147_89_SymmetricAlgorithm(ProviderType));
}
/// <inheritdoc />
[SecuritySafeCritical]
protected Gost_R3411_HMAC(ProviderType providerType, int hashSize) : base(providerType, hashSize)
{
InitDefaults(new Gost_28147_89_SymmetricAlgorithm(ProviderType));
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="keyAlgorithm">Алгоритм для вычисления HMAC</param>
/// <param name="hashSize">Размер хэш-кода в битах</param>
/// <exception cref="ArgumentNullException"></exception>
[SecuritySafeCritical]
protected Gost_R3411_HMAC(Gost_28147_89_SymmetricAlgorithmBase keyAlgorithm, int hashSize) : base(keyAlgorithm.ProviderType, hashSize)
{
if (keyAlgorithm == null)
{
throw ExceptionUtility.ArgumentNull(nameof(keyAlgorithm));
}
InitDefaults(Gost_28147_89_SymmetricAlgorithm.CreateFromKey(keyAlgorithm));
}
[SecuritySafeCritical]
private void InitDefaults(Gost_28147_89_SymmetricAlgorithm keyAlgorithm)
{
HashName = typeof(THash).Name;
_keyAlgorithm = keyAlgorithm;
_hmacHandle = CreateHashHMAC(keyAlgorithm.ProviderType, CryptoApiHelper.GetProviderHandle(keyAlgorithm.ProviderType), keyAlgorithm.GetSafeHandle());
}
/// <summary>
/// Создает дескриптор функции хэширования HMAC криптографического провайдера
/// </summary>
[SecuritySafeCritical]
protected abstract SafeHashHandleImpl CreateHashHMAC(ProviderType providerType, SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle);
[SecurityCritical]
private SafeHashHandleImpl _hmacHandle;
private Gost_28147_89_SymmetricAlgorithm _keyAlgorithm;
/// <inheritdoc />
SafeHashHandleImpl ISafeHandleProvider<SafeHashHandleImpl>.SafeHandle
{
[SecurityCritical]
get { return _hmacHandle; }
}
/// <summary>
/// Алгоритм для вычисления HMAC
/// </summary>
public Gost_28147_89_SymmetricAlgorithmBase KeyAlgorithm
{
get
{
return _keyAlgorithm;
}
[SecuritySafeCritical]
set
{
_keyAlgorithm = Gost_28147_89_SymmetricAlgorithm.CreateFromKey(value);
}
}
/// <inheritdoc />
public override byte[] Key
{
get
{
return _keyAlgorithm.Key;
}
set
{
_keyAlgorithm = new Gost_28147_89_SymmetricAlgorithm(ProviderType) { Key = value };
Initialize();
}
}
/// <inheritdoc />
[SecuritySafeCritical]
public override void Initialize()
{
var hmacHandle = CreateHashHMAC(ProviderType, CryptoApiHelper.GetProviderHandle(ProviderType), _keyAlgorithm.GetSafeHandle());
_hmacHandle.TryDispose();
_hmacHandle = hmacHandle;
}
/// <inheritdoc />
[SecuritySafeCritical]
protected override void HashCore(byte[] data, int dataOffset, int dataLength)
{
CryptoApiHelper.HashData(_hmacHandle, data, dataOffset, dataLength);
}
/// <inheritdoc />
[SecuritySafeCritical]
protected override byte[] HashFinal()
{
return CryptoApiHelper.EndHashData(_hmacHandle);
}
/// <inheritdoc />
[SecuritySafeCritical]
protected override void Dispose(bool disposing)
{
if (disposing)
{
_keyAlgorithm?.Clear();
_hmacHandle.TryDispose();
}
base.Dispose(disposing);
}
}
}

View File

@ -0,0 +1,89 @@
using System.Security;
using GostCryptography.Base;
using GostCryptography.Native;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Базовый класс для всех реализаций алгоритма хэширования ГОСТ Р 34.11
/// </summary>
public abstract class Gost_R3411_HashAlgorithm : GostHashAlgorithm, ISafeHandleProvider<SafeHashHandleImpl>
{
/// <inheritdoc />
[SecuritySafeCritical]
protected Gost_R3411_HashAlgorithm(int hashSize) : base(hashSize)
{
_hashHandle = CreateHashHandle();
}
/// <inheritdoc />
[SecuritySafeCritical]
protected Gost_R3411_HashAlgorithm(ProviderType providerType, int hashSize) : base(providerType, hashSize)
{
_hashHandle = CreateHashHandle();
}
[SecurityCritical]
internal Gost_R3411_HashAlgorithm(ProviderType providerType, SafeProvHandleImpl providerHandle, int hashSize) : base(providerType, hashSize)
{
_hashHandle = CreateHashHandle(providerHandle);
}
/// <summary>
/// Создает дескриптор функции хэширования криптографического провайдера
/// </summary>
[SecurityCritical]
protected SafeHashHandleImpl CreateHashHandle()
{
return CreateHashHandle(CryptoApiHelper.GetProviderHandle(ProviderType));
}
/// <summary>
/// Создает дескриптор функции хэширования криптографического провайдера
/// </summary>
[SecurityCritical]
protected abstract SafeHashHandleImpl CreateHashHandle(SafeProvHandleImpl providerHandle);
[SecurityCritical]
private SafeHashHandleImpl _hashHandle;
/// <inheritdoc />
SafeHashHandleImpl ISafeHandleProvider<SafeHashHandleImpl>.SafeHandle
{
[SecurityCritical]
get => _hashHandle;
}
/// <inheritdoc />
[SecuritySafeCritical]
public override void Initialize()
{
_hashHandle.TryDispose();
_hashHandle = CreateHashHandle();
}
/// <inheritdoc />
[SecuritySafeCritical]
protected override void HashCore(byte[] data, int dataOffset, int dataLength)
{
CryptoApiHelper.HashData(_hashHandle, data, dataOffset, dataLength);
}
/// <inheritdoc />
[SecuritySafeCritical]
protected override byte[] HashFinal()
{
return CryptoApiHelper.EndHashData(_hashHandle);
}
/// <inheritdoc />
[SecuritySafeCritical]
protected override void Dispose(bool disposing)
{
_hashHandle.TryDispose();
base.Dispose(disposing);
}
}
}

View File

@ -0,0 +1,167 @@
using GostCryptography.Base;
using GostCryptography.Gost_28147_89;
using System;
using System.Security;
namespace GostCryptography.Gost_R3411
{
/// <summary>
/// Базовый класс для всех реализаций генератора псевдослучайной последовательности (Pseudorandom Function, PRF) на базе алгоритма хэширования ГОСТ Р 34.11
/// </summary>
/// <typeparam name="THMAC">Тип HMAC</typeparam>
public abstract class Gost_R3411_PRF<THMAC> : GostPRF where THMAC : GostHMAC
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="key">Симметричный ключ ГОСТ 28147 для вычисления HMAC на основе алгоритма ГОСТ Р 34.11</param>
/// <param name="label">Метка для порождения ключей (аргумент label функции PRF)</param>
/// <param name="seed">Начальное число для порождения ключей (аргумент seed функции PRF)</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
[SecuritySafeCritical]
protected Gost_R3411_PRF(Gost_28147_89_SymmetricAlgorithmBase key, byte[] label, byte[] seed)
: this(key.ProviderType, Gost_28147_89_SymmetricAlgorithm.CreateFromKey(key), label, seed)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
/// <param name="key">Симметричный ключ ГОСТ 28147 для вычисления HMAC на основе алгоритма ГОСТ Р 34.11</param>
/// <param name="label">Метка для порождения ключей (аргумент label функции PRF)</param>
/// <param name="seed">Начальное число для порождения ключей (аргумент seed функции PRF)</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
[SecuritySafeCritical]
protected Gost_R3411_PRF(ProviderType providerType, byte[] key, byte[] label, byte[] seed)
: this(providerType, Gost_28147_89_SymmetricAlgorithm.CreateFromSessionKey(providerType, key), label, seed)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="providerType">Тип криптографического провайдера</param>
/// <param name="key">Симметричный ключ ГОСТ 28147 для вычисления HMAC на основе алгоритма ГОСТ Р 34.11</param>
/// <param name="label">Метка для порождения ключей (аргумент label функции PRF)</param>
/// <param name="seed">Начальное число для порождения ключей (аргумент seed функции PRF)</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
[SecuritySafeCritical]
private Gost_R3411_PRF(ProviderType providerType, Gost_28147_89_SymmetricAlgorithm key, byte[] label, byte[] seed) : base(providerType)
{
if (label == null)
{
throw ExceptionUtility.ArgumentNull(nameof(label));
}
if (seed == null)
{
throw ExceptionUtility.ArgumentNull(nameof(seed));
}
_key = key;
_hmac = CreateHMAC(key);
var labelAndSeed = new byte[label.Length + seed.Length];
label.CopyTo(labelAndSeed, 0);
seed.CopyTo(labelAndSeed, label.Length);
_labelAndSeed = labelAndSeed;
_buffer = new byte[labelAndSeed.Length + (_hmac.HashSize / 8)];
_value = labelAndSeed;
_keyIndex = 0;
}
private readonly Gost_28147_89_SymmetricAlgorithm _key;
private readonly GostHMAC _hmac;
private readonly byte[] _labelAndSeed;
private readonly byte[] _buffer;
private byte[] _value;
private int _keyIndex;
/// <summary>
/// Создает экземпляр <typeparamref name="THMAC"/> на основе заданного ключа
/// </summary>
[SecuritySafeCritical]
protected abstract THMAC CreateHMAC(Gost_28147_89_SymmetricAlgorithm key);
/// <summary>
/// Возвращает очередной набор псевдослучайной последовательности
/// </summary>
/// <remarks>
/// Размер последовательности зависит от алгоритма хэширования
/// </remarks>
[SecurityCritical]
public byte[] DeriveBytes()
{
var randomBuffer = GenerateNextBytes();
return _hmac.ComputeHash(randomBuffer);
}
/// <summary>
/// Возвращает псевдослучайный симметричный ключ ГОСТ 28147
/// </summary>
[SecuritySafeCritical]
public Gost_28147_89_SymmetricAlgorithmBase DeriveKey()
{
var randomPassword = GenerateNextBytes();
using (var hmac = CreateHMAC(_key))
{
return Gost_28147_89_SymmetricAlgorithm.CreateFromPassword(hmac, randomPassword);
}
}
/// <summary>
/// Возвращает псевдослучайный симметричный ключ ГОСТ 28147
/// </summary>
/// <param name="position">Позиция ключа в псевдослучайной последовательности</param>
/// <exception cref="ArgumentOutOfRangeException">Если позиция ключа <paramref name="position"/> не кратна размеру ключа в байтах или ключ с данной позицией уже был создан</exception>
[SecurityCritical]
public Gost_28147_89_SymmetricAlgorithmBase DeriveKey(int position)
{
if ((position % _hmac.HashSize) != 0)
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(position));
}
var keyIndex = position / _hmac.HashSize;
if (keyIndex < _keyIndex)
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(position));
}
while (keyIndex > _keyIndex)
{
DeriveKey().Clear();
}
return DeriveKey();
}
[SecurityCritical]
private byte[] GenerateNextBytes()
{
_value = _hmac.ComputeHash(_value);
_value.CopyTo(_buffer, 0);
_labelAndSeed.CopyTo(_buffer, _value.Length);
_keyIndex++;
return _buffer;
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
_key.Clear();
_hmac.Dispose();
}
}
}