-
Notifications
You must be signed in to change notification settings - Fork 42
/
Gost_3412_M_SymmetricAlgorithm.cs
471 lines (373 loc) · 17.2 KB
/
Gost_3412_M_SymmetricAlgorithm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
using System.Collections.Generic;
using System.Security;
using System.Security.Cryptography;
using GostCryptography.Asn1.Gost.Gost_28147_89;
using GostCryptography.Base;
using GostCryptography.Native;
using GostCryptography.Properties;
namespace GostCryptography.Gost_28147_89
{
/// <summary>
/// Реализация алгоритма симметричного шифрования по ГОСТ Р 34.12-2015 Магма.
/// </summary>
public sealed class Gost_3412_M_SymmetricAlgorithm : GostSymmetricAlgorithm, ISafeHandleProvider<SafeKeyHandleImpl>
{
public const int DefaultKeySize = 256;
public const int DefaultBlockSize = 64;
public const int DefaultFeedbackSize = 64;
public const int DefaultIvSize = DefaultBlockSize / 8;
public static readonly KeySizes[] DefaultLegalKeySizes = { new KeySizes(DefaultKeySize, DefaultKeySize, 0) };
public static readonly KeySizes[] DefaultLegalBlockSizes = { new KeySizes(DefaultBlockSize, DefaultBlockSize, 0) };
/// <summary>
/// Наименование алгоритма шифрования ГОСТ Р 34.12-2015 Магма.
/// </summary>
public const string AlgorithmNameValue = "id-tc26-cipher-gostr3412-2015-magma";
/// <summary>
/// Известные наименования алгоритма шифрования ГОСТ Р 34.12-2015 Магма.
/// </summary>
public static readonly string[] KnownAlgorithmNames = { AlgorithmNameValue };
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_3412_M_SymmetricAlgorithm()
{
InitDefaults();
_providerHandle = CryptoApiHelper.GetProviderHandle(ProviderType).DangerousAddRef();
_keyHandle = SafeKeyHandleImpl.InvalidHandle;
}
/// <inheritdoc />
[SecuritySafeCritical]
public Gost_3412_M_SymmetricAlgorithm(ProviderType providerType) : base(providerType)
{
InitDefaults();
_providerHandle = CryptoApiHelper.GetProviderHandle(ProviderType).DangerousAddRef();
_keyHandle = SafeKeyHandleImpl.InvalidHandle;
}
[SecurityCritical]
internal Gost_3412_M_SymmetricAlgorithm(ProviderType providerType, SafeProvHandleImpl providerHandle, SafeKeyHandleImpl keyHandle) : base(providerType)
{
InitDefaults();
_providerHandle = providerHandle.DangerousAddRef();
_keyHandle = CryptoApiHelper.DuplicateKey(keyHandle);
if (CryptoApiHelper.GetKeyParameterInt32(_keyHandle, Constants.KP_ALGID) != Constants.CALG_GR3412_2015_M)
{
throw ExceptionUtility.Argument(nameof(keyHandle), Resources.RequiredGost3412_M);
}
}
[SecurityCritical]
private void InitDefaults()
{
KeySizeValue = DefaultKeySize;
BlockSizeValue = DefaultBlockSize;
FeedbackSizeValue = DefaultFeedbackSize;
LegalBlockSizesValue = DefaultLegalBlockSizes;
LegalKeySizesValue = DefaultLegalKeySizes;
Mode = CipherMode.CFB;
Padding = PaddingMode.None;
}
/// <inheritdoc />
public override string AlgorithmName => AlgorithmNameValue;
/// <summary>
/// Создает экземпляр <see cref="Gost_3412_M_SymmetricAlgorithm"/> на основе указанного алгоритма шифрования.
/// </summary>
/// <param name="keyAlgorithm">Алгоритм симметричного шифрования ключа.</param>
[SecurityCritical]
public static Gost_3412_M_SymmetricAlgorithm CreateFromKey(Gost_3412_M_SymmetricAlgorithm keyAlgorithm)
{
if (keyAlgorithm == null)
{
throw ExceptionUtility.ArgumentNull(nameof(keyAlgorithm));
}
return new Gost_3412_M_SymmetricAlgorithm(keyAlgorithm.ProviderType, keyAlgorithm._providerHandle, keyAlgorithm.GetSafeHandle());
}
/// <summary>
/// Создает экземпляр <see cref="Gost_3412_M_SymmetricAlgorithm"/> на основе указанного пароля.
/// </summary>
[SecuritySafeCritical]
public static Gost_3412_M_SymmetricAlgorithm CreateFromPassword(HashAlgorithm hashAlgorithm, byte[] password)
{
if (hashAlgorithm == null)
{
throw ExceptionUtility.ArgumentNull(nameof(hashAlgorithm));
}
if (!(hashAlgorithm is IGostAlgorithm gostHashAlgorithm))
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(hashAlgorithm));
}
if (!(hashAlgorithm is ISafeHandleProvider<SafeHashHandleImpl> hashHandleProvider))
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(hashAlgorithm));
}
if (password == null)
{
throw ExceptionUtility.ArgumentNull(nameof(password));
}
hashAlgorithm.TransformBlock(password, 0, password.Length, password, 0);
var providerType = gostHashAlgorithm.ProviderType;
var providerHandle = CryptoApiHelper.GetProviderHandle(providerType);
var symKeyHandle = CryptoApiHelper.DeriveSymKey(providerHandle, hashHandleProvider.SafeHandle, Constants.CALG_GR3412_2015_M);
return new Gost_3412_M_SymmetricAlgorithm(providerType, providerHandle, symKeyHandle);
}
/// <summary>
/// Создает экземпляр <see cref="Gost_3412_M_SymmetricAlgorithm"/> на основе сессионного ключа.
/// </summary>
[SecuritySafeCritical]
public static Gost_3412_M_SymmetricAlgorithm CreateFromSessionKey(ProviderType providerType, byte[] sessionKey)
{
if (sessionKey == null)
{
throw ExceptionUtility.ArgumentNull(nameof(sessionKey));
}
if (sessionKey.Length != DefaultKeySize / 8)
{
throw ExceptionUtility.Argument(nameof(sessionKey), Resources.InvalidHashSize, DefaultKeySize / 8);
}
var providerHandle = CryptoApiHelper.GetProviderHandle(providerType);
var randomNumberGenerator = CryptoApiHelper.GetRandomNumberGenerator(providerType);
using (var keyHandle = CryptoApiHelper.ImportBulkSessionKey(providerType, providerHandle, sessionKey, randomNumberGenerator, Constants.CALG_GR3412_2015_M, Constants.CALG_GR3413_2015_M_IMIT))
{
return new Gost_3412_M_SymmetricAlgorithm(providerType, providerHandle, keyHandle);
}
}
[SecurityCritical]
private SafeProvHandleImpl _providerHandle;
[SecurityCritical]
private SafeKeyHandleImpl _keyHandle;
/// <inheritdoc />
SafeKeyHandleImpl ISafeHandleProvider<SafeKeyHandleImpl>.SafeHandle
{
[SecurityCritical]
get
{
if (_keyHandle.IsInvalid)
{
GenerateKey();
}
return _keyHandle;
}
}
/// <inheritdoc />
public override byte[] Key
{
[SecuritySafeCritical]
get { throw ExceptionUtility.NotSupported(Resources.SymmetryExportBulkKeyNotSupported); }
[SecuritySafeCritical]
set { throw ExceptionUtility.NotSupported(Resources.SymmetryImportBulkKeyNotSupported); }
}
/// <inheritdoc />
public override int KeySize
{
[SecuritySafeCritical]
get { return base.KeySize; }
[SecuritySafeCritical]
set
{
base.KeySize = value;
_keyHandle.TryDispose();
_providerHandle.TryDispose();
_keyHandle = SafeKeyHandleImpl.InvalidHandle;
_providerHandle = SafeProvHandleImpl.InvalidHandle;
}
}
/// <summary>
/// Создает симметричный ключ на основе пароля.
/// </summary>
[SecuritySafeCritical]
public void DeriveFromPassword(GostHashAlgorithm hashAlgorithm, byte[] password)
{
var provider = CreateFromPassword(hashAlgorithm, password);
_keyHandle.TryDispose();
_providerHandle.TryDispose();
_keyHandle = provider._keyHandle;
_providerHandle = provider._providerHandle;
provider._keyHandle = SafeKeyHandleImpl.InvalidHandle;
provider._providerHandle = SafeProvHandleImpl.InvalidHandle;
}
/// <inheritdoc />
[SecuritySafeCritical]
public override byte[] ComputeHash(HashAlgorithm hash)
{
if (!(hash is ISafeHandleProvider<SafeHashHandleImpl> hashHandleProvider))
{
throw ExceptionUtility.Argument(nameof(hash), Resources.RequiredGostHash);
}
var hashHandle = hashHandleProvider.SafeHandle;
CryptoApiHelper.HashKeyExchange(hashHandle, this.GetSafeHandle());
return CryptoApiHelper.EndHashData(hashHandle);
}
/// <inheritdoc />
[SecuritySafeCritical]
public override void GenerateIV()
{
IVValue = new byte[DefaultIvSize];
CryptoApiHelper.GetRandomNumberGenerator(ProviderType).GetBytes(IVValue);
}
/// <inheritdoc />
[SecuritySafeCritical]
public override void GenerateKey()
{
_keyHandle = CryptoApiHelper.GenerateKey(_providerHandle, Constants.CALG_GR3412_2015_M, CspProviderFlags.NoFlags);
KeyValue = null;
KeySizeValue = DefaultKeySize;
}
/// <inheritdoc />
[SecuritySafeCritical]
public override ICryptoTransform CreateEncryptor()
{
var hKey = CryptoApiHelper.DuplicateKey(this.GetSafeHandle());
return CreateCryptoTransform(hKey, IV, Gost_28147_89_CryptoTransformMode.Encrypt);
}
/// <inheritdoc />
[SecuritySafeCritical]
public override ICryptoTransform CreateEncryptor(byte[] key, byte[] iv)
{
throw ExceptionUtility.NotSupported(Resources.Gost28147UnsafeCreateDecryptorNotSupported);
}
/// <inheritdoc />
[SecuritySafeCritical]
public override ICryptoTransform CreateDecryptor()
{
var hKey = CryptoApiHelper.DuplicateKey(this.GetSafeHandle());
return CreateCryptoTransform(hKey, IV, Gost_28147_89_CryptoTransformMode.Decrypt);
}
/// <inheritdoc />
[SecuritySafeCritical]
public override ICryptoTransform CreateDecryptor(byte[] key, byte[] iv)
{
throw ExceptionUtility.NotSupported(Resources.Gost28147UnsafeCreateDecryptorNotSupported);
}
[SecurityCritical]
private ICryptoTransform CreateCryptoTransform(SafeKeyHandleImpl hKey, byte[] iv, Gost_28147_89_CryptoTransformMode transformMode)
{
// TODO: Refactor this!
// NOTE: The params order is important!
if (hKey == null)
{
hKey = CryptoApiHelper.GenerateKey(CryptoApiHelper.GetProviderHandle(ProviderType), Constants.CALG_GR3412_2015_M, CspProviderFlags.NoFlags);
}
var keyParameters = new Dictionary<int, object>();
if (ModeValue == CipherMode.CTS)
{
throw ExceptionUtility.CryptographicException(Resources.CipherTextSteamingNotSupported);
}
if ((Padding != PaddingMode.None) && ((ModeValue == CipherMode.OFB) || (ModeValue == CipherMode.CFB)))
{
throw ExceptionUtility.CryptographicException(Resources.InvalidPaddingMode);
}
// Установка KP_MODE
keyParameters.Add(Constants.KP_MODE, ModeValue);
// Установка KP_PADDING
keyParameters.Add(Constants.KP_PADDING, Constants.ZERO_PADDING);
if ((ModeValue == CipherMode.CFB) && (FeedbackSizeValue != DefaultFeedbackSize))
{
throw ExceptionUtility.CryptographicException(Resources.IncorrectFeedbackSize);
}
// Установка KP_IV
if (ModeValue != CipherMode.ECB)
{
if (iv == null)
{
iv = new byte[DefaultIvSize];
CryptoApiHelper.GetRandomNumberGenerator(ProviderType).GetBytes(iv);
}
if (iv.Length < DefaultIvSize)
{
throw ExceptionUtility.CryptographicException(Resources.InvalidIvSize);
}
keyParameters.Add(Constants.KP_IV, iv);
}
return new Gost_28147_89_CryptoTransform(ProviderType, hKey, keyParameters, PaddingValue, ModeValue, BlockSizeValue, transformMode);
}
/// <inheritdoc />
[SecuritySafeCritical]
public override SymmetricAlgorithm DecodePrivateKey(byte[] encodedKeyExchangeData, GostKeyExchangeExportMethod keyExchangeExportMethod)
{
if (encodedKeyExchangeData == null)
{
throw ExceptionUtility.ArgumentNull(nameof(encodedKeyExchangeData));
}
int keyExchangeExportAlgId;
if (keyExchangeExportMethod == GostKeyExchangeExportMethod.GostKeyExport)
{
keyExchangeExportAlgId = Constants.CALG_SIMPLE_EXPORT;
}
else if (keyExchangeExportMethod == GostKeyExchangeExportMethod.CryptoProKeyExport)
{
keyExchangeExportAlgId = Constants.CALG_PRO_EXPORT;
}
else if (keyExchangeExportMethod == GostKeyExchangeExportMethod.CryptoProTk26KeyExport)
{
keyExchangeExportAlgId = Constants.CALG_PRO12_EXPORT;
}
else
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(keyExchangeExportMethod));
}
var providerHandle = CryptoApiHelper.GetProviderHandle(ProviderType);
var keyExchangeInfo = new Gost_28147_89_KeyExchangeInfo();
keyExchangeInfo.Decode(encodedKeyExchangeData);
using (var keyHandle = CryptoApiHelper.DuplicateKey(this.GetSafeHandle()))
{
CryptoApiHelper.SetKeyExchangeExportAlgId(ProviderType, keyHandle, keyExchangeExportAlgId);
var keyExchangeHandle = CryptoApiHelper.ImportKeyExchange(providerHandle, keyExchangeInfo, keyHandle);
return new Gost_3412_M_SymmetricAlgorithm(ProviderType, providerHandle, keyExchangeHandle);
}
}
/// <inheritdoc />
[SecuritySafeCritical]
public override byte[] EncodePrivateKey(GostSymmetricAlgorithm keyExchangeAlgorithm, GostKeyExchangeExportMethod keyExchangeExportMethod)
{
if (keyExchangeAlgorithm == null)
{
throw ExceptionUtility.ArgumentNull(nameof(keyExchangeAlgorithm));
}
int keyExchangeExportAlgId;
if (keyExchangeExportMethod == GostKeyExchangeExportMethod.GostKeyExport)
{
keyExchangeExportAlgId = Constants.CALG_SIMPLE_EXPORT;
}
else if (keyExchangeExportMethod == GostKeyExchangeExportMethod.CryptoProKeyExport)
{
keyExchangeExportAlgId = Constants.CALG_PRO_EXPORT;
}
else
{
throw ExceptionUtility.ArgumentOutOfRange(nameof(keyExchangeExportMethod));
}
var currentSessionKey = keyExchangeAlgorithm as ISafeHandleProvider<SafeKeyHandleImpl>;
if (currentSessionKey == null)
{
using (var derivedSessionKey = new Gost_3412_M_SymmetricAlgorithm(ProviderType))
{
derivedSessionKey.Key = keyExchangeAlgorithm.Key;
return EncodePrivateKeyInternal(derivedSessionKey, keyExchangeExportAlgId);
}
}
return EncodePrivateKeyInternal(currentSessionKey, keyExchangeExportAlgId);
}
[SecurityCritical]
private byte[] EncodePrivateKeyInternal(ISafeHandleProvider<SafeKeyHandleImpl> sessionKey, int keyExchangeExportAlgId)
{
var hSessionKey = sessionKey.GetSafeHandle();
using (var keyHandle = CryptoApiHelper.DuplicateKey(this.GetSafeHandle()))
{
CryptoApiHelper.SetKeyExchangeExportAlgId(ProviderType, keyHandle, keyExchangeExportAlgId);
CryptoApiHelper.SetKeyParameter(keyHandle, Constants.KP_IV, IV);
var keyExchangeInfo = CryptoApiHelper.ExportKeyExchange(hSessionKey, keyHandle);
return keyExchangeInfo.Encode();
}
}
[SecuritySafeCritical]
public override GostSymmetricAlgorithm Clone()
{
return CreateFromKey(this);
}
/// <inheritdoc />
[SecuritySafeCritical]
protected override void Dispose(bool disposing)
{
_keyHandle.TryDispose();
_providerHandle.TryDispose();
base.Dispose(disposing);
}
}
}