Esempio n. 1
0
        public void PaddingISO10126_PaddedCheckValidBlock()
        {
            byte[] invalidPadding = new byte[] {
                0x11, 0x22, 0x33,
                0x0D, 0x0D, 0x0D, 0x0D,
                0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D,
                0x0D // Ошибка!
            };

            // Шифруем без padding
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.None;
            ICryptoTransform encryptor = key.CreateEncryptor();

            byte[] encypted = encryptor.TransformFinalBlock(invalidPadding,
                                                            0, invalidPadding.Length);
            Assert.Equal(16, encypted.Length);

            // Расшифровываем как бы с padding
            key.Padding = PaddingMode.ISO10126;
            ICryptoTransform decryptor = key.CreateDecryptor();

            // Не пользуемся ExpectedExceptionAttribute он может случится на encrypt
            Assert.ThrowsAny <CryptographicException>(() => decryptor.TransformFinalBlock(encypted,
                                                                                          0, encypted.Length));
        }
Esempio n. 2
0
        public void PaddingNone_PaddedEncrypt()
        {
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.None;

            ICryptoTransform encryptor = key.CreateEncryptor();

            Assert.Equal(8, encryptor.InputBlockSize);
            Assert.Equal(8, encryptor.OutputBlockSize);

            byte[] encypted = encryptor.TransformFinalBlock(WellKnownData,
                                                            0, WellKnownData.Length);
            Assert.Equal(WellKnownData.Length, encypted.Length);

            ICryptoTransform decryptor = key.CreateDecryptor();

            Assert.Equal(8, decryptor.InputBlockSize);
            Assert.Equal(8, decryptor.OutputBlockSize);

            byte[] decrypted = decryptor.TransformFinalBlock(encypted,
                                                             0, encypted.Length);
            Assert.Equal(WellKnownData, decrypted);
        }
Esempio n. 3
0
        public void PaddingISO10126_PaddedSetValid()
        {
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.ISO10126;
            ICryptoTransform encryptor = key.CreateEncryptor();

            byte[] encypted = encryptor.TransformFinalBlock(WellKnownUnpaddedData,
                                                            0, WellKnownUnpaddedData.Length);
            Assert.Equal(8, encypted.Length);

            // Расшифровываем без padding
            key.Padding = PaddingMode.None;
            ICryptoTransform decryptor = key.CreateDecryptor();

            byte[] decrypted = decryptor.TransformFinalBlock(encypted,
                                                             0, encypted.Length);

            // проверяем что ожидаем из текста.
            Assert.Equal(WellKnownUnpaddedData, decrypted.Take(WellKnownUnpaddedData.Length));
            // проверяем что ожидаем из длины.
            Assert.Equal(5, decrypted[7]);
        }
Esempio n. 4
0
        public void PaddingPKCS7_PaddedSetValid()
        {
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.PKCS7;
            ICryptoTransform encryptor = key.CreateEncryptor();

            byte[] encypted = encryptor.TransformFinalBlock(WellKnownUnpaddedData,
                                                            0, WellKnownUnpaddedData.Length);
            Assert.Equal(8, encypted.Length);

            // Расшифровываем без padding
            key.Padding = PaddingMode.None;
            ICryptoTransform decryptor = key.CreateDecryptor();

            byte[] decrypted = decryptor.TransformFinalBlock(encypted,
                                                             0, encypted.Length);

            // Один в один проверяем что ожидаем.
            byte[] expected = new byte[] {
                0x11, 0x22, 0x33,
                0x05, 0x05, 0x05, 0x05,
                0x05
            };
            Assert.Equal <byte>(expected, decrypted);
        }
Esempio n. 5
0
 /// <summary>
 /// Формирование данных обмена, на основе симметричного
 /// ключа шифрования сообщения ГОСТ 28147.
 /// </summary>
 ///
 /// <param name="data">"Чистый" симметричный ключ
 /// ГОСТ 28147.</param>
 ///
 /// <returns>Зашифрованные данные для отправки стороне
 /// получателю.</returns>
 ///
 /// <remarks>
 /// <if notdefined="symimp"><para>В данной сборке функция всегда
 /// возбуждает исключение <see cref="CryptographicException"/>.
 /// </para></if>
 /// <para>В зависимости от сборки функция может всегда возбуждать
 /// исключение <see cref="CryptographicException"/>, так
 /// как использует "чистый" ключ. По возможности используйте
 /// безопасную функцию
 /// <see cref="CreateKeyExchange(SymmetricAlgorithm)"/></para>
 /// </remarks>
 public override byte[] CreateKeyExchange(byte[] data)
 {
     using (Gost28147CryptoServiceProvider alg =
                new Gost28147CryptoServiceProvider())
     {
         alg.Key = data;
         return(CreateKeyExchangeData(alg));
     }
 }
Esempio n. 6
0
        public void PaddingNone_UnpaddedEncrypt()
        {
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.None;
            ICryptoTransform encryptor = key.CreateEncryptor();

            Assert.ThrowsAny <CryptographicException>(() => encryptor.TransformFinalBlock(WellKnownUnpaddedData,
                                                                                          0, WellKnownUnpaddedData.Length));
        }
        public void CipherOidTest()
        {
            var szOID_Gost28147_89_CryptoPro_A_ParamSet = "1.2.643.2.2.31.1";
            var szOID_Gost28147_89_TC26_Z_ParamSet      = "1.2.643.7.1.2.5.1.1";

            using (var gost = new Gost28147CryptoServiceProvider())
            {
                gost.CipherOid = szOID_Gost28147_89_CryptoPro_A_ParamSet;
                Assert.Equal(gost.CipherOid, szOID_Gost28147_89_CryptoPro_A_ParamSet);

                gost.CipherOid = szOID_Gost28147_89_TC26_Z_ParamSet;
                Assert.Equal(gost.CipherOid, szOID_Gost28147_89_TC26_Z_ParamSet);
            }
        }
Esempio n. 8
0
        //Функция генерации ключа из парольной фразы
        public byte[] GetSecretKey()
        {
            Gost28147CryptoServiceProvider gostCSP = new
                                                     Gost28147CryptoServiceProvider();

            randBytes = new byte[8];
            RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();

            rand.GetBytes(randBytes);
            byte[] pwd = Encoding.UTF8.GetBytes(PassFraseBox1.Text);
            byte[] buf = new byte[pwd.Length + randBytes.Length];
            pwd.CopyTo(buf, 0);
            randBytes.CopyTo(buf, pwd.Length);
            gostCSP.ByDeriveBytes(buf);
            return(buf);
        }
Esempio n. 9
0
        public void PaddingISO10126_Unpadded()
        {
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.ISO10126;
            ICryptoTransform encryptor = key.CreateEncryptor();

            byte[] encypted = encryptor.TransformFinalBlock(WellKnownUnpaddedData,
                                                            0, WellKnownUnpaddedData.Length);
            ICryptoTransform decryptor = key.CreateDecryptor();

            byte[] decrypted = decryptor.TransformFinalBlock(encypted, 0, encypted.Length);
            Assert.Equal(WellKnownUnpaddedData, decrypted);
        }
Esempio n. 10
0
        public void EncryptSymmectricKey()
        {
            using (Gost28147CryptoServiceProvider key = new Gost28147CryptoServiceProvider())
            {
                // Создаем Xml файл для зашифрования.
                CreateSomeXml("sto_encrypt.xml");
                Console.WriteLine("Создан новый XML файл.");

                // На стороне отправителя.
                // Зашифровываем узел, заданный xpath выражением, XML документа
                // ato_encrypt.xml в документ a_encrypted.xml
                Encrypt("sto_encrypt.xml", "s_encrypt.xml", "//SomeNode[@ToEncrypt='true']", key);
                Console.WriteLine("Узел XML файла зашифрован.");

                Decrypt("s_encrypt.xml", "s_decrypted.xml", key);
                Console.WriteLine("XML документ расшифрован.");
            }
        }
Esempio n. 11
0
        public void PaddingZero_Unpadded()
        {
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.Zeros;
            ICryptoTransform encryptor = key.CreateEncryptor();

            byte[] encypted = encryptor.TransformFinalBlock(WellKnownUnpaddedData,
                                                            0, WellKnownUnpaddedData.Length);
            ICryptoTransform decryptor = key.CreateDecryptor();

            byte[] decrypted = decryptor.TransformFinalBlock(encypted, 0, encypted.Length);
            byte[] expected  = new byte[] { 0x11, 0x22, 0x33, 0, 0, 0, 0, 0 };
            Assert.Equal(expected, decrypted);
        }
Esempio n. 12
0
        private void TestKeyWrap(GostKeyWrapMethod keyWrapMethod)
        {
            using (Gost28147 gost = new Gost28147CryptoServiceProvider())
            {
                using (Gost28147 keyToWrap = new Gost28147CryptoServiceProvider())
                {
                    var data          = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1 };
                    var encryptedData = GostEncrypt(keyToWrap, data);

                    var wrappedKey   = gost.Wrap(keyToWrap, keyWrapMethod);
                    var unwrappedKey = gost.Unwrap(wrappedKey, keyWrapMethod) as Gost28147;
                    var iv           = keyToWrap.IV;

                    var decryptedData = GostDecrypt(unwrappedKey, encryptedData, iv);

                    Assert.Equal(data, decryptedData);
                }
            }
        }
Esempio n. 13
0
        public void TestKeyExchange2012_256()
        {
            // Ассиметричный ключ получателя.
            Gost3410_2012_256 AssymKey;

            // Синхропосылка.
            byte[] IV;

            // Создаем случайный открытый ключ.
            using (Gost3410_2012_256 gkey = GetGostProvider2012_256())
            {
                AssymKey = gkey;

                // Создаем случайный секретный ключ, который необходимо передать.
                Gost28147 key = new Gost28147CryptoServiceProvider();
                // Синхропосылка не входит в GostKeyTransport и должна
                // передаваться отдельно.
                IV = key.IV;

                // Создаем форматтер, шифрующий на ассиметричном ключе получателя.
                GostKeyExchangeFormatter Formatter = new GostKeyExchangeFormatter(AssymKey);
                // GostKeyTransport - формат зашифрованной для безопасной передачи
                // ключевой информации.
                GostKeyTransport encKey = Formatter.CreateKeyExchange(key);

                // Шифруемая строка
                string message     = "012345678901234567890";
                byte[] sourceBytes = Encoding.ASCII.GetBytes(message);
                Console.WriteLine("** Строка до шифрования: " + message);

                // Шифруем строку на сессионном ключе
                byte[] encBytes = GostEncrypt(key, sourceBytes);
                Console.WriteLine("** Строка после шифрования: " +
                                  Encoding.ASCII.GetString(encBytes));

                // Получатель расшифровывает GostKeyTransport и само сообщение.
                byte[] decBytes = GostDecrypt(encKey, encBytes, IV, AssymKey);
                Console.WriteLine("** Строка после расшифрования: " +
                                  Encoding.ASCII.GetString(decBytes));

                Assert.Equal(sourceBytes, decBytes);
            }
        }
Esempio n. 14
0
        public void TestAgreeCert2012_512TkZ()
        {
            using (var cert = GetGost2012_512Certificate())
            {
                var gost    = (Gost3410_2012_512CryptoServiceProvider)cert.PrivateKey;
                var gostRes = (Gost3410_2012_512CryptoServiceProvider)cert.PrivateKey;

                var gostPk    = (Gost3410_2012_512CryptoServiceProvider)cert.PublicKey.Key;
                var gostResPk = (Gost3410_2012_512CryptoServiceProvider)cert.PublicKey.Key;

                var symmetric = new Gost28147CryptoServiceProvider();

                gostPk.CipherOid    = "1.2.643.7.1.2.5.1.1";
                gostResPk.CipherOid = "1.2.643.7.1.2.5.1.1";

                var    agree = (GostSharedSecretCryptoServiceProvider)gost.CreateAgree(gostResPk.ExportParameters(false));
                byte[] wrappedKeyBytesArray = agree.Wrap(symmetric, GostKeyWrapMethod.CryptoProKeyWrap);

                var agreeRes = (GostSharedSecretCryptoServiceProvider)gostRes.CreateAgree(gostPk.ExportParameters(false));
                var key      = agreeRes.Unwrap(wrappedKeyBytesArray, GostKeyWrapMethod.CryptoProKeyWrap);
            }
        }
Esempio n. 15
0
        public void ResetNormal()
        {
            Gost28147CryptoServiceProvider key =
                new Gost28147CryptoServiceProvider();

            key.GenerateKey();
            key.Mode    = CipherMode.ECB;
            key.Padding = PaddingMode.ANSIX923;
            ICryptoTransform encryptor = key.CreateEncryptor();
            ICryptoTransform decryptor = key.CreateDecryptor();

            // Первое преобразование.
            byte[] encrypted = encryptor.TransformFinalBlock(WellKnownUnpaddedData,
                                                             0, WellKnownUnpaddedData.Length);
            byte[] decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);
            Assert.Equal(WellKnownUnpaddedData, decrypted);

            // Второе преобразование, на тех же encryptor и decryptor
            encrypted = encryptor.TransformFinalBlock(WellKnownUnpaddedData,
                                                      0, WellKnownUnpaddedData.Length);
            decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);
            Assert.Equal(WellKnownUnpaddedData, decrypted);
        }
Esempio n. 16
0
        //Проверка целостности файла
        private void VerifyBut_Click(object sender, EventArgs e)
        {
            string sourceFile  = InFile.Text;
            string sourceFile1 = OuFile.Text;

            byte[]        buffer    = null;
            byte[]        randBytes = new byte[8];
            byte[]        hashValue;
            HashAlgorithm myhash = HashAlgorithm.Create("GOST3411");

            if (InFile.Text.Length > 0 && OuFile.Text.Length > 0 && File.Exists(InFile.Text) && File.Exists(OuFile.Text))
            {
                using (FileStream inStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                {
                    if (PassFrase.Checked)
                    {
                        //Считывание случаной примеси
                        using (FileStream inStream1 = new FileStream(sourceFile1, FileMode.Open, FileAccess.Read))
                        {
                            inStream1.Read(randBytes, 0, 8);
                        }

                        //Генерация ключа из парольной фразы и примеси
                        Gost28147CryptoServiceProvider gostCSP = new
                                                                 Gost28147CryptoServiceProvider();
                        byte[] pwd    = Encoding.UTF8.GetBytes(PassFraseText.Text);
                        byte[] bufkey = new byte[pwd.Length + randBytes.Length];
                        pwd.CopyTo(bufkey, 0);
                        randBytes.CopyTo(bufkey, pwd.Length);
                        gostCSP.ByDeriveBytes(bufkey);
                        buffer = new byte[inStream.Length + bufkey.Length];
                        bufkey.CopyTo(buffer, 0);
                        inStream.Read(buffer, bufkey.Length, (int)inStream.Length);

                        //вычисление хэш-значения
                        hashValue = myhash.ComputeHash(buffer);
                    }
                    else
                    {
                        //вычисление хэш при отсутствии примеси и парольной фразы
                        buffer = new byte[inStream.Length];
                        inStream.Read(buffer, 0, (int)inStream.Length);
                        hashValue = myhash.ComputeHash(buffer);
                    }
                    string hashnew  = "";
                    string oldhashv = "";

                    //Преобразование данных
                    for (int i = 0; i < hashValue.Length; i++)
                    {
                        hashnew += Convert.ToString(hashValue[i], 16);
                    }
                    StreamReader sr = new StreamReader(sourceFile1);
                    if (PassFrase.Checked)
                    {
                        for (int i = 0; i < 8; ++i)
                        {
                            sr.Read();
                        }
                        oldhashv = sr.ReadToEnd();
                    }
                    else
                    {
                        oldhashv = sr.ReadToEnd();
                    }


                    //Сравнений хэш-значений
                    if (oldhashv == hashnew)
                    {
                        CheckResult.Text = "Файл исправен";
                    }
                    else
                    {
                        CheckResult.Text = "Файл не исправен или неправильная парольная фраза";
                    }
                }
            }
            else
            {
                MessageBox.Show("Ошибка: Один из файлов пустой или такого файла не существует!.", "Error!", MessageBoxButtons.OK);
                return;
            }
        }
Esempio n. 17
0
        // Зашифрование узла XML документа на ассиметричном ключе
        private static void Encrypt(string srcName, string destName,
                                    string xpath, string EncryptionElementID, AsymmetricAlgorithm alg,
                                    string KeyName)
        {
            // Создаем новый объект xml документа.
            XmlDocument xmlDoc = new XmlDocument();

            // Пробельные символы участвуют в вычислении подписи и должны быть сохранены для совместимости с другими реализациями
            xmlDoc.PreserveWhitespace = true;

            // Загружаем в объект созданный XML документ.
            xmlDoc.Load(srcName);

            // Ищем заданный элемент для заширования.
            XmlElement elementToEncrypt = xmlDoc.SelectSingleNode(xpath)
                                          as XmlElement;

            if (elementToEncrypt == null)
            {
                throw new XmlException("Узел не найден");
            }

            // Создаем случайный симметричный ключ.
            // В целях безопасности удаляем ключ из памяти после использования.
            using (Gost28147CryptoServiceProvider sessionKey =
                       new Gost28147CryptoServiceProvider())
            {
                // Создаем объект класса EncryptedXml и используем
                // его для зашифрования узла на случайной симметричном ключе.
                EncryptedXml eXml = new EncryptedXml();

                // Зашифровываем элемент на сессионном ключе.
                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt,
                                                           sessionKey, false);

                // Создаем объект EncryptedData и заполняем его
                // необходимой информацией.
                EncryptedData edElement = new EncryptedData();
                // Тип элемента зашифрованный узел
                edElement.Type = EncryptedXml.XmlEncElementUrl;
                // Созданный элемент помечаем EncryptionElementID
                edElement.Id = EncryptionElementID;

                // Заполняем алгоритм зашифрования данных.
                // Он будет использован при расшифровании.
                edElement.EncryptionMethod = new EncryptionMethod(
                    EncryptedXml.XmlEncGost28147Url);

                // Зашифровываем сессионный ключ и добавляем эти зашифрованные данные
                // к узлу EncryptedKey.
                EncryptedKey ek = new EncryptedKey();
                byte[]       encryptedKey;

                if (alg is Gost3410 gost3410)
                {
                    encryptedKey = EncryptedXml.EncryptKey(sessionKey, gost3410);
                }
                else if (alg is Gost3410_2012_256 gost3410_2012_256)
                {
                    encryptedKey = EncryptedXml.EncryptKey(sessionKey, gost3410_2012_256);
                }
                else if (alg is Gost3410_2012_512 gost3410_2012_512)
                {
                    encryptedKey = EncryptedXml.EncryptKey(sessionKey, gost3410_2012_512);
                }
                else
                {
                    throw new NotSupportedException();
                }
                ek.CipherData       = new CipherData(encryptedKey);
                ek.EncryptionMethod = new EncryptionMethod(
                    EncryptedXml.XmlEncGostKeyTransportUrl);

                // Создаем элемент DataReference для KeyInfo.
                // Эта необязательная операция позволяет указать
                // какие данные используют данный ключ.
                // XML документ может содержвать несколько
                // элементов EncryptedData с различными ключами.
                DataReference dRef = new DataReference();

                // Указываем URI EncryptedData.
                // Для этого используем ранее проставленную ссылку
                // EncryptionElementID
                dRef.Uri = "#" + EncryptionElementID;

                // Добавляем к EncryptedKey ссылку на зашифрованные
                // данные.
                ek.AddReference(dRef);

                // Создаем новую ссылку на ключ.
                edElement.KeyInfo = new KeyInfo();

                // Добавляем ссылку на зашифрованный ключ к
                // зашифрованным данным.
                edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));

                // Указываем имя ассиметричного ключа.

                // Создаем новый элемент KeyInfoName
                KeyInfoName kin = new KeyInfoName();

                // Указываем имя ассиметричного ключа.
                kin.Value = KeyName;

                // Добавляем элемент KeyInfoName к
                // объекту EncryptedKey.
                ek.KeyInfo.AddClause(kin);

                // Добавляем зашифрованные данные
                // к объекту EncryptedData.
                edElement.CipherData.CipherValue = encryptedElement;

                // Заменяем исходный узел на зашифрованный.
                EncryptedXml.ReplaceElement(elementToEncrypt,
                                            edElement, false);

                // Сохраняем зашифрованный документ.
                xmlDoc.Save(destName);
            }
        }