private static Gost28147SymmetricAlgorithm DuplicateKeyAlg(Gost28147SymmetricAlgorithmBase keyAlgorithm) { var keySymmetricAlgorithm = keyAlgorithm as Gost28147SymmetricAlgorithm; return((keySymmetricAlgorithm != null) ? new Gost28147SymmetricAlgorithm(keySymmetricAlgorithm.InternalProvHandle, keySymmetricAlgorithm.InternalKeyHandle) : new Gost28147SymmetricAlgorithm { Key = keyAlgorithm.Key }); }
public void TearDown() { try { _sharedKey.Dispose(); } finally { _sharedKey = null; } }
public Gost28147ImitHashAlgorithm(Gost28147SymmetricAlgorithmBase key) { if (key == null) { throw ExceptionUtility.ArgumentNull("key"); } KeyValue = null; HashSizeValue = DefaultHashSize; _keyAlgorithm = DuplicateKeyAlg(key); }
public Gost3411Hmac(Gost28147SymmetricAlgorithmBase keyAlgorithm) { if (keyAlgorithm == null) { throw ExceptionUtility.ArgumentNull("keyAlgorithm"); } HashName = DefaultHashName; HashSizeValue = DefaultHashSize; _keyAlgorithm = DuplicateKeyAlg(keyAlgorithm); _hashHandle = CryptoApiHelper.CreateHashHmac(CryptoApiHelper.ProviderHandle, _keyAlgorithm.InternalKeyHandle); }
private static XmlDocument DecryptXmlDocument(XmlDocument encryptedXmlDocument, Gost28147SymmetricAlgorithmBase sharedKey) { // Создание объекта для дешифрации XML var encryptedXml = new GostEncryptedXml(encryptedXmlDocument); // Добавление ссылки на общий симметричный ключ encryptedXml.AddKeyNameMapping("SharedKey1", sharedKey); // Расшифровка зашифрованных элементов документа encryptedXml.DecryptDocument(); return encryptedXmlDocument; }
public Gost3411Prf(Gost28147SymmetricAlgorithmBase key, byte[] label, byte[] seed) : this(label, seed) { if (key == null) { throw ExceptionUtility.ArgumentNull("key"); } _hashHmacHandle = SafeHashHandleImpl.InvalidHandle; _buffer = new byte[_labelAndSeed.Length + 32]; var gostSymmetricAlgorithm = key as Gost28147SymmetricAlgorithm; _key = (gostSymmetricAlgorithm != null) ? new Gost28147SymmetricAlgorithm(gostSymmetricAlgorithm.InternalProvHandle, gostSymmetricAlgorithm.InternalKeyHandle) : new Gost28147SymmetricAlgorithm { Key = key.Key }; }
private static Stream CreateImitDataStream(Gost28147SymmetricAlgorithmBase sharedKey, Stream dataStream) { // Создание объекта для вычисления имитовставки using (var imitHash = new Gost28147ImitHashAlgorithm(sharedKey)) { // Вычисление имитовставки для потока данных var imitHashValue = imitHash.ComputeHash(dataStream); // Запись имитовставки в начало выходного потока данных var imitDataStream = new MemoryStream(); imitDataStream.Write(imitHashValue, 0, imitHashValue.Length); // Копирование исходного потока данных в выходной поток dataStream.Position = 0; dataStream.CopyTo(imitDataStream); imitDataStream.Position = 0; return imitDataStream; } }
public override byte[] EncodePrivateKey(Gost28147SymmetricAlgorithmBase keyExchangeAlgorithm, GostKeyExchangeExportMethod keyExchangeExportMethod) { if (keyExchangeAlgorithm == null) { throw ExceptionUtility.ArgumentNull("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("keyExchangeExportMethod"); } var currentSessionKey = keyExchangeAlgorithm as Gost28147SymmetricAlgorithm; if (currentSessionKey == null) { using (var derivedSessinKey = new Gost28147SymmetricAlgorithm()) { derivedSessinKey.Key = keyExchangeAlgorithm.Key; return(EncodePrivateKeyInternal(derivedSessinKey, keyExchangeExportAlgId)); } } return(EncodePrivateKeyInternal(currentSessionKey, keyExchangeExportAlgId)); }
/// <summary> /// Шифрует сессионный ключ с помощью указанного асимметричного ключа ГОСТ Р 34.10. /// </summary> /// <param name="sessionKey">Шифруемый сессионный ключ.</param> /// <param name="publicKey">Открытый ключ ГОСТ Р 34.10 для шифрования сессионного ключа.</param> /// <returns>Массив байт, содержащий зашифрованный сессионный ключ.</returns> /// <remarks>Как правило сессионный ключ используется для шифрования данных и в свою очередь так же шифруется.</remarks> public static byte[] EncryptKey(Gost28147SymmetricAlgorithmBase sessionKey, Gost3410AsymmetricAlgorithmBase publicKey) { return GostEncryptedXmlImpl.EncryptKey(sessionKey, publicKey); }
/// <summary> /// Экспортирует (шифрует) секретный ключ. /// </summary> /// <param name="keyExchangeAlgorithm">Общий секретный ключ.</param> /// <param name="keyExchangeExportMethod">Алгоритм экспорта общего секретного ключа.</param> public abstract byte[] EncodePrivateKey(Gost28147SymmetricAlgorithmBase keyExchangeAlgorithm, GostKeyExchangeExportMethod keyExchangeExportMethod);
private static Gost28147SymmetricAlgorithm DuplicateKeyAlg(Gost28147SymmetricAlgorithmBase keyAlgorithm) { var keySymmetricAlgorithm = keyAlgorithm as Gost28147SymmetricAlgorithm; return (keySymmetricAlgorithm != null) ? new Gost28147SymmetricAlgorithm(keySymmetricAlgorithm.InternalProvHandle, keySymmetricAlgorithm.InternalKeyHandle) : new Gost28147SymmetricAlgorithm { Key = keyAlgorithm.Key }; }
public static byte[] EncryptKey(Gost28147SymmetricAlgorithmBase sessionKey, Gost28147SymmetricAlgorithmBase sharedKey, GostKeyExchangeExportMethod exportMethod) { if (sessionKey == null) { throw ExceptionUtility.ArgumentNull("sessionKey"); } if (sharedKey == null) { throw ExceptionUtility.ArgumentNull("sharedKey"); } return sharedKey.EncodePrivateKey(sessionKey, exportMethod); }
public static byte[] EncryptKey(Gost28147SymmetricAlgorithmBase sessionKey, Gost3410AsymmetricAlgorithmBase publicKey) { if (sessionKey == null) { throw ExceptionUtility.ArgumentNull("sessionKey"); } if (publicKey == null) { throw ExceptionUtility.ArgumentNull("publicKey"); } var formatter = new GostKeyExchangeFormatter(publicKey); return formatter.CreateKeyExchangeData(sessionKey); }
public override byte[] EncodePrivateKey(Gost28147SymmetricAlgorithmBase keyExchangeAlgorithm, GostKeyExchangeExportMethod keyExchangeExportMethod) { if (keyExchangeAlgorithm == null) { throw ExceptionUtility.ArgumentNull("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("keyExchangeExportMethod"); } var currentSessionKey = keyExchangeAlgorithm as Gost28147SymmetricAlgorithm; if (currentSessionKey == null) { using (var derivedSessinKey = new Gost28147SymmetricAlgorithm()) { derivedSessinKey.Key = keyExchangeAlgorithm.Key; return EncodePrivateKeyInternal(derivedSessinKey, keyExchangeExportAlgId); } } return EncodePrivateKeyInternal(currentSessionKey, keyExchangeExportAlgId); }
private static XmlDocument EncryptXmlDocument(XmlDocument xmlDocument, Gost28147SymmetricAlgorithmBase sharedKey) { // Создание объекта для шифрации XML var encryptedXml = new GostEncryptedXml(); // Поиск элементов для шифрации var elements = xmlDocument.SelectNodes("//SomeElement[@Encrypt='true']"); if (elements != null) { var elementIndex = 0; foreach (XmlElement element in elements) { // Создание случайного сессионного ключа using (var sessionKey = new Gost28147SymmetricAlgorithm()) { // Шифрация элемента var encryptedData = encryptedXml.EncryptData(element, sessionKey, false); // Шифрация сессионного ключа с использованием общего симметричного ключа var encryptedSessionKeyData = GostEncryptedXml.EncryptKey(sessionKey, sharedKey, GostKeyExchangeExportMethod.CryptoProKeyExport); // Формирование элемента EncryptedData var elementEncryptedData = new EncryptedData(); elementEncryptedData.Id = "EncryptedElement" + elementIndex++; elementEncryptedData.Type = EncryptedXml.XmlEncElementUrl; elementEncryptedData.EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGost28147Url); elementEncryptedData.CipherData.CipherValue = encryptedData; elementEncryptedData.KeyInfo = new KeyInfo(); // Формирование информации о зашифрованном сессионном ключе var encryptedSessionKey = new EncryptedKey(); encryptedSessionKey.CipherData = new CipherData(encryptedSessionKeyData); encryptedSessionKey.EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGostCryptoProKeyExportUrl); encryptedSessionKey.AddReference(new DataReference { Uri = "#" + elementEncryptedData.Id }); encryptedSessionKey.KeyInfo.AddClause(new KeyInfoName { Value = "SharedKey1" }); // Добавление ссылки на зашифрованный ключ, используемый при шифровании данных elementEncryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedSessionKey)); // Замена элемента его зашифрованным представлением GostEncryptedXml.ReplaceElement(element, elementEncryptedData, false); } } } return xmlDocument; }
/// <summary> /// Шифрует сессионный ключ с помощью указанного симметричного ключа ГОСТ 28147. /// </summary> /// <param name="sessionKey">Шифруемый сессионный ключ.</param> /// <param name="sharedKey">Общий симметричный ключ ГОСТ 28147 для шифрования сессионного ключа.</param> /// <param name="exportMethod">Алгоритм экспорта сессионного ключа.</param> /// <returns>Массив байт, содержащий зашифрованный сессионный ключ.</returns> /// <remarks>Как правило сессионный ключ используется для шифрования данных и в свою очередь так же шифруется.</remarks> public static byte[] EncryptKey(Gost28147SymmetricAlgorithmBase sessionKey, Gost28147SymmetricAlgorithmBase sharedKey, GostKeyExchangeExportMethod exportMethod = GostKeyExchangeExportMethod.GostKeyExport) { return GostEncryptedXmlImpl.EncryptKey(sessionKey, sharedKey, exportMethod); }
public void SetUp() { _sharedKey = new Gost28147SymmetricAlgorithm(); }
private static bool VerifyImitDataStream(Gost28147SymmetricAlgorithmBase sharedKey, Stream imitDataStream) { // Создание объекта для вычисления имитовставки using (var imitHash = new Gost28147ImitHashAlgorithm(sharedKey)) { // Считывание имитовставки из потока данных var imitHashValue = new byte[imitHash.HashSize / 8]; imitDataStream.Read(imitHashValue, 0, imitHashValue.Length); // Вычисление реального значения имитовставки для потока данных var expectedImitHashValue = imitHash.ComputeHash(imitDataStream); // Сравнение исходной имитовствки с ожидаемой return imitHashValue.SequenceEqual(expectedImitHashValue); } }