Exemplo n.º 1
0
        /// <summary></summary>
        public byte[] EncryptAes(byte[] abKey, byte[] abPlain)
        {
            byte[] abReturn = null;

            if ((abKey != null) && (abPlain != null))
            {
                _Randomness.GetBytes(_abInitialisationVector);
                _AesServices.Key     = abKey; // TODO SetKey
                _AesServices.IV      = _abInitialisationVector;
                _AesServices.Padding = PaddingMode.PKCS7;

                using (ICryptoTransform AesEncryptor = _AesServices.CreateEncryptor())
                {
                    using (MemoryStream AesMemoryStream = new MemoryStream())
                    {
                        AesMemoryStream.Write(_abInitialisationVector, 0, _abInitialisationVector.Length);
                        using (CryptoStream AesCryptoStream = new CryptoStream(AesMemoryStream, AesEncryptor, CryptoStreamMode.Write))
                        {
                            AesCryptoStream.Write(abPlain, 0, abPlain.Length);
                        }
                        abReturn = AesMemoryStream.ToArray();
                    }
                }
            }
            return(abReturn);
        }
Exemplo n.º 2
0
        public static void TestCases()
        {
            var aes = new AesCng();

            aes.CreateEncryptor();
            aes.CreateEncryptor(aes.Key, new byte[16]); // Noncompliant (S3329) {{Use a dynamically-generated, random IV.}}
        }
Exemplo n.º 3
0
        public void InConditionals(int a)
        {
            var constantIV = new byte[16];

            using var aes = new AesCng();
            using var rng = new RNGCryptoServiceProvider();

            var e = a switch
            {
                1 => aes.CreateEncryptor(),                    // Compliant
                2 => aes.CreateEncryptor(aes.Key, constantIV), // Noncompliant
                _ => null
            };

            var iv = new byte[16];

            using var aes2 = new AesCng();
            if (a == 1)
            {
                aes2.IV = iv;       // Set IV to constant
            }
            aes2.CreateEncryptor(); // Noncompliant

            var aes3 = a == 2 ? aes2 : aes;

            aes3.CreateEncryptor(); // Noncompliant
        }
Exemplo n.º 4
0
        private byte[] EncryptBytes(string file)
        {
            byte[] plainByteArray = File.ReadAllBytes(file);
            using (Aes aes = new AesCng())
            {
                PasswordDeriveBytes pwDerivedBytes = new PasswordDeriveBytes(passwordTextBox.Text, new byte[] { 0x32, 0xF4, 0x83, 0xC });

                aes.Key = pwDerivedBytes.GetBytes(aes.KeySize / 8);
                aes.IV  = pwDerivedBytes.GetBytes(aes.BlockSize / 8);

                GCHandle gcHandle = GCHandle.Alloc(aes.Key, GCHandleType.Pinned);

                using (MemoryStream memStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainByteArray, 0, plainByteArray.Length);
                        cryptoStream.Close();
                        byte[] encryptedBytes = memStream.ToArray();
#if DEBUG
                        Console.WriteLine($"{ConsoleDateTag()} Encrypting {GetFileNameFromPath(file)} using password {passwordTextBox.Text}");
#endif
                        ZeroMemory(gcHandle.AddrOfPinnedObject(), aes.Key.Length);
                        return(encryptedBytes);
                    }
                }
            }
        }
Exemplo n.º 5
0
        // using AES with:
        // Key hash algorithm: SHA-256
        // Key Size: 256 Bit
        // Block Size: 128 Bit
        // Input Vector (IV): 128 Bit
        // Mode of Operation: Cipher-Block Chaining (CBC)
        /// <summary>
        /// Encrypts a plain text with a password using AES-256 CBC with SHA-256.
        /// </summary>
        /// <param name="plainText">The text to be encrypted.</param>
        /// <param name="password">The password to encrypt the text with.</param>
        /// <returns>The encrypted text.</returns>
        public static string AESEncrypt(string plainText, string password)
        {
            byte[] passwordBytes       = Encoding.UTF8.GetBytes(password);
            byte[] hashedPasswordBytes = SHA256Managed.Create().ComputeHash(passwordBytes);
            byte[] plainTextBytes      = Encoding.UTF8.GetBytes(plainText);
            byte[] encryptedBytes      = null;

            using (MemoryStream ms = new MemoryStream())
            {
                using AesCng AES = new AesCng
                      {
                          KeySize = 256,
                          Key     = hashedPasswordBytes
                      };
                AES.IV   = GetRandomBytes(AES.BlockSize / 8);
                AES.Mode = CipherMode.CBC;

                using (CryptoStream cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cs.Close();
                }
                encryptedBytes = new byte[AES.IV.Length + ms.ToArray().Length];
                AES.IV.CopyTo(encryptedBytes, 0);
                ms.ToArray().CopyTo(encryptedBytes, AES.IV.Length);
            }
            return(Convert.ToBase64String(encryptedBytes));
        }
Exemplo n.º 6
0
        static async Task <byte[]> EncryptStringToBytesAsync(string plainText, byte[] Key, byte[] IV)
        {
            byte[] encrypted;
            using (var aes = new AesCng())
            {
                // Copy given key and IV into AES object
                aes.Key = Key;
                aes.IV  = IV;

                // Create encryptor
                ICryptoTransform encryptor = aes.CreateEncryptor();

                // Create memory stream that will receive encrypted bytes
                using (var msEncrypt = new MemoryStream())
                {
                    // Create crypto stream that does the encryption with the given encryptor
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        // Create writer with which we write the plaintext for encryption
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            // Write plaintext that should be encrypted to the crypto stream
                            await swEncrypt.WriteAsync(plainText);
                        }

                        // Get encrypted bytes from memory stream
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            return(encrypted);
        }
Exemplo n.º 7
0
        private static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] nonSecretPayload)
        {
            //User Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException($"Key needs to be {KeyBitSize} bit!", nameof(cryptKey));
            }

            if (secretMessage == null || secretMessage.Length < 1)
            {
                throw new ArgumentException("Secret Message Required!", nameof(secretMessage));
            }

            //non-secret payload optional
            nonSecretPayload = nonSecretPayload ?? new byte[] { };

            byte[] cipherText;
            byte[] iv;

            using (var aes = new AesCng()
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {
                //Use random IV
                aes.GenerateIV();
                iv = aes.IV;

                using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                {
                    using (var cipherStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                        {
                            using (var binaryWriter = new BinaryWriter(cryptoStream))
                                binaryWriter.Write(secretMessage);
                        }
                        cipherText = cipherStream.ToArray();
                    }
                }

                using (var encryptedStream = new MemoryStream())
                {
                    using (var binaryWriter = new BinaryWriter(encryptedStream))
                    {
                        binaryWriter.Write(nonSecretPayload);
                        //Prepend IV
                        binaryWriter.Write(iv);
                        binaryWriter.Write(cipherText);
                        binaryWriter.Flush();
                    }
                    return(encryptedStream.ToArray());
                }
            }
        }
Exemplo n.º 8
0
        public static void AesCbcEncrypt(string inputFile, string password)
        {
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            using SHA256 sha = SHA256.Create();
            byte[]   hashedPasswordBytes = sha.ComputeHash(passwordBytes);
            FileInfo info          = new FileInfo(inputFile);
            long     size          = info.Length;
            long     encryptedSize = 0;
            string   outputFile    = inputFile + (isLegacy ? ".aes2" : ".lsec");

            PrintStats(info, outputFile, false);
            Console.WriteLine("Starting Encryption ...");
            using FileStream fsin  = new FileStream(inputFile, FileMode.Open);
            using FileStream fsout = new FileStream(outputFile, FileMode.Create);
            using AesCng AES       = new AesCng
                  {
                      KeySize = 256,
                      Key     = hashedPasswordBytes
                  };
            AES.IV   = GetRandomBytes(AES.BlockSize / 8);
            AES.Mode = CipherMode.CBC;
            if (!isLegacy)
            {
                ScryptProvider scryptProvider = new ScryptProvider(password);
                passwordBytes = Encoding.UTF8.GetBytes(scryptProvider.ComputeHash());
                fsout.Write(passwordBytes, 0, passwordBytes.Length);
            }
            fsout.Write(AES.IV, 0, AES.IV.Length);
            using ICryptoTransform encryptor = AES.CreateEncryptor();
            using CryptoStream cs            = new CryptoStream(fsout, encryptor, CryptoStreamMode.Write);
            byte[] buffer = new byte[BufferSize];
            int    read;

            try
            {
                while ((read = fsin.Read(buffer, 0, buffer.Length)) > 0)
                {
                    cs.Write(buffer, 0, read);
                    encryptedSize += buffer.Length;
                    ShowProgress(encryptedSize, size, false);
                }
                cs.FlushFinalBlock();
                fsout.Flush();
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("\nFatal error: " + e.Message);
                try
                {
                    File.Delete(outputFile);
                }
                catch (Exception)
                {
                }
            }
        }
Exemplo n.º 9
0
        public byte[] Encrypt(byte[] plain, byte[] key, byte[] iv, byte[] aead_aad = null, byte[] aead_associated = null)
        {
            if (key.Length * 8 != this.KeySize)
            {
                throw new InvalidOperationException($"the given key has invalid size {key.Length * 8}, expect {this.KeySize}");
            }
            _aes.Key = key;
            _aes.IV  = iv;
            var encryptor = _aes.CreateEncryptor();

            return(encryptor.TransformFinalBlock(plain, 0, plain.Length));
        }
Exemplo n.º 10
0
        protected static byte[] Encrypt(ECDiffieHellmanCng ecc, CngKey publicKey, byte[] bytes, int offset, int length)
        {
            using (AesCng aes = new AesCng()) {
                aes.KeySize   = 256;
                aes.BlockSize = 128;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.None;
                aes.Key       = ecc.DeriveKeyMaterial(publicKey);
                aes.IV        = new byte[16];

                using (var decryptor = aes.CreateEncryptor()) return(decryptor.TransformFinalBlock(bytes, offset, length));
            }
        }
Exemplo n.º 11
0
 public override string Encrypt(string Message)
 {
     // Generate new initialization vector for each encryption to prevent identical plaintexts from producing identical ciphertexts when encrypted using the same key.
     _cipher.GenerateIV();
     using (var stream = new MemoryStream())
         using (var encryptor = _cipher.CreateEncryptor(SharedKey, _cipher.IV))
             using (var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
                 using (var streamWriter = new StreamWriter(cryptoStream))
                 {
                     stream.Write(_cipher.IV, 0, _cipher.IV.Length);
                     streamWriter.Write(Message);
                     return(Convert.ToBase64String(stream.ToArray()));
                 }
 }
Exemplo n.º 12
0
        public void Invoke()
        {
            using (AesCng aes = new AesCng()) {

                Console.Write("Enter Key Password: "******"Confirm Password: "******"Passwords did not match.");
                    return;
                }

                CngKey pk = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521, null, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport });
                byte[] publicKeyBlock = pk.Export(CngKeyBlobFormat.EccPublicBlob);

                byte[] privateKeyBlob = pk.Export(CngKeyBlobFormat.EccPrivateBlob);

                aes.KeySize = 256;
                aes.BlockSize = 128;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.None;
                aes.IV = IV;
                aes.Key = HashString(p1);

                byte[] decryptedECPrivateBlob = new byte[EncryptedECPrivateBlobLength];
                Buffer.BlockCopy(privateKeyBlob, 0, decryptedECPrivateBlob, 0, privateKeyBlob.Length);

                byte[] encryptedData = null;
                using (var encryptor = aes.CreateEncryptor()) {
                    encryptedData = encryptor.TransformFinalBlock(decryptedECPrivateBlob, 0, decryptedECPrivateBlob.Length);
                }

                using (var file = new System.IO.FileStream(PublicKeyFile, System.IO.FileMode.CreateNew))
                using (var writer = new System.IO.BinaryWriter(file)) {
                    writer.Write((int)FileType.Public);
                    file.Write(publicKeyBlock, 0, publicKeyBlock.Length);
                }

                using (var file = new System.IO.FileStream(PrivateKeyFile, System.IO.FileMode.CreateNew))
                using (var writer = new System.IO.BinaryWriter(file)) {
                    writer.Write((int)FileType.Private);
                    writer.Write(encryptedData, 0, encryptedData.Length);
                }

                Console.WriteLine($"Thumbprint: {new KeyThumbprint(pk)}");
            }
        }
Exemplo n.º 13
0
        public static byte[] EncryptDataWithPersistedKey(byte[] data, byte[] iv)
        {
            using (Aes aes = new AesCng("CDD_KEY",
                                        CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.UserKey))
            {
                aes.IV = iv;

                // Using the zero-argument overload is required to make use of the persisted key
                using (var encryptor = aes.CreateEncryptor())
                {
                    if (!encryptor.CanTransformMultipleBlocks)
                    {
                        throw new InvalidOperationException("This is a sample, this case wasn’t handled...");
                    }

                    return(encryptor.TransformFinalBlock(data, 0, data.Length));
                }
            }
        }
Exemplo n.º 14
0
        public void Setup()
        {
            _Aes256         = Aes.Create();
            _Aes256.KeySize = 256;
            _Aes256Cng      = new AesCng {
                KeySize = 256
            };
            _Aes256Csp = new AesCryptoServiceProvider()
            {
                KeySize = 256
            };
            _Aes256Managed = new AesManaged()
            {
                KeySize = 256
            };

            _Aes256Encryptor        = _Aes256.CreateEncryptor();
            _Aes256ManagedEncryptor = _Aes256Managed.CreateEncryptor();
            _Aes256CngEncryptor     = _Aes256Cng.CreateEncryptor();
            _Aes256CspEncryptor     = _Aes256Csp.CreateEncryptor();
        }
Exemplo n.º 15
0
        private void EncryptButton_Click(object sender, EventArgs e)
        {
            RSACng myRSAProv;

            if (CngKey.Exists(KeyContainerEncryptTextBox.Text))
            {
                myRSAProv = new RSACng(CngKey.Open(KeyContainerEncryptTextBox.Text));
            }
            else
            {
                myRSAProv = new RSACng(CngKey.Create(CngAlgorithm.Rsa, KeyContainerEncryptTextBox.Text));
            }


            RSAOAEPKeyExchangeFormatter myKeyFormatter = new RSAOAEPKeyExchangeFormatter(myRSAProv);
            AesCng mySymmProv = new AesCng();

            byte[] encrKey = myKeyFormatter.CreateKeyExchange(mySymmProv.Key);
            byte[] data    = File.ReadAllBytes(FileEncryptTextBox.Text);
            using (FileStream fsout = new FileStream(FileEncryptTextBox.Text + ".encrypted", FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fsout))
                {
                    bw.Write(encrKey.Length);
                    bw.Write(encrKey, 0, encrKey.Length);
                    bw.Write(mySymmProv.IV.Length);
                    bw.Write(mySymmProv.IV, 0, mySymmProv.IV.Length);
                    bw.Flush();
                    using (CryptoStream cs = new CryptoStream(fsout, mySymmProv.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        using (BinaryWriter sw = new BinaryWriter(cs))
                        {
                            sw.Write(data);
                        }
                    }
                }
            }
            MessageBox.Show("Encryption completed.");
        }
        public void AuthenticatedSymmetricAlgorithmVerifierTestNegativeStandardEncryptAuthenticatedDecryptTest()
        {
            byte[] plaintext  = Encoding.UTF8.GetBytes("Plaintext");
            byte[] ciphertext = null;

            byte[] key = null;
            SymmetricEncryptionState encryptionState = null;

            using (SymmetricAlgorithm encryptAes = new AesCng().EnableLogging())
            {
                key = encryptAes.Key;

                using (MemoryStream ms = new MemoryStream())
                    using (CryptoStream cs = new CryptoStream(ms, encryptAes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        cs.FlushFinalBlock();

                        ciphertext      = ms.ToArray();
                        encryptionState = encryptAes.GetLastEncryptionState();
                    }
            }

            using (SymmetricAlgorithm decryptAes = (new AuthenticatedAesCng() as SymmetricAlgorithm).EnableDecryptionVerification(encryptionState))
            {
                decryptAes.Key = key;
                decryptAes.IV  = new byte[] { 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

                using (MemoryStream ms = new MemoryStream())
                    using (CryptoStream cs = new CryptoStream(ms, decryptAes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(ciphertext, 0, ciphertext.Length);
                        cs.FlushFinalBlock();
                    }
            }

            Assert.Fail("Decryption should have failed.");
        }
Exemplo n.º 17
0
        private void EncryptButton_Click(object sender, EventArgs e)
        {
            AesCng algorithm = new AesCng();
            RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create();

            // salt has to be as big as the blocksize. Blocksize is in bits, salt size is in bytes!
            byte[] salt = new byte[algorithm.BlockSize / 8];
            randomNumberGenerator.GetBytes(salt);
            Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(PasswordEncryptTextBox.Text, salt);

            //key size is in bits!
            byte[] key = keyGenerator.GetBytes(algorithm.KeySize / 8);
            byte[] iv  = algorithm.IV;
            algorithm.Key = key;

            ICryptoTransform cryptoTransformer = algorithm.CreateEncryptor();

            byte[] data = File.ReadAllBytes(FileEncryptTextBox.Text);
            using (FileStream fStream = File.Open(FileEncryptTextBox.Text + ".encrypted", FileMode.OpenOrCreate))
            {
                using (BinaryWriter bWriter = new BinaryWriter(fStream))
                {
                    bWriter.Write(salt.Length);
                    bWriter.Write(salt);
                    bWriter.Write(iv.Length);
                    bWriter.Write(iv);

                    using (CryptoStream cStream = new CryptoStream(fStream, cryptoTransformer, CryptoStreamMode.Write))
                    {
                        using (BinaryWriter sWriter = new BinaryWriter(cStream))
                        {
                            sWriter.Write(data);
                        }
                    }
                }
            }
            MessageBox.Show("Encryption completed.");
        }
Exemplo n.º 18
0
 private string EncryptPayload(string plain, string key)
 {
     try
     {
         using (AesCng aes = new AesCng())
         {
             byte[] plainBytes = Encoding.UTF8.GetBytes(plain);
             byte[] keyBytes   = CreatePasswordFromKey(key);
             aes.Key = keyBytes;
             aes.IV  = _iv;
             using (ICryptoTransform cryptoTransform = aes.CreateEncryptor())
             {
                 byte[] cipherBytes = cryptoTransform.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
                 return(Convert.ToBase64String(cipherBytes));
             }
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.ToString());
         return(string.Empty);
     }
 }
Exemplo n.º 19
0
        public static bool EncryptFile(string filename, string password)
        {
            var deriveKey = new Rfc2898DeriveBytes(password, 8, 1_000_000, HashAlgorithmName.SHA256);

            string outputFileName = $"{filename}.malted";

            if (!(File.Exists(filename) && !File.Exists(outputFileName)))
            {
                return(false);
            }
            FileStream inputStream      = File.OpenRead(filename);
            FileStream fileOutputStream = File.Create(outputFileName);

            var aescng = new AesCng();

            byte[] tmpKey = deriveKey.GetBytes(32 + 16);
            byte[] key    = new byte[32];
            byte[] iv     = new byte[16];
            Array.Copy(tmpKey, key, 32);
            Array.Copy(tmpKey, 32, iv, 0, 16);
            aescng.Padding   = PaddingMode.PKCS7;
            aescng.KeySize   = 256;
            aescng.BlockSize = 128;
            aescng.Mode      = CipherMode.CBC;
            var encryptor = aescng.CreateEncryptor(key, iv);

            fileOutputStream.Write(Encoding.UTF8.GetBytes("Malted__"));
            fileOutputStream.Write(deriveKey.Salt);
            using (CryptoStream csEncrypt = new CryptoStream(fileOutputStream, encryptor, CryptoStreamMode.Write))
            {
                inputStream.CopyTo(csEncrypt);
                csEncrypt.FlushFinalBlock();
            }
            inputStream.Close();
            fileOutputStream.Close();
            return(true);
        }
Exemplo n.º 20
0
        static async Task <byte[]> Encrypt(string text, byte[] key, byte[] vector)
        {
            byte[] bytes;
            using (var aes = new AesCng())
            {
                aes.Key = key;
                aes.IV  = vector;

                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        using (var writer = new StreamWriter(cryptoStream))
                        {
                            await writer.WriteAsync(text);
                        }
                    }

                    bytes = memoryStream.ToArray();
                }

                return(bytes);
            }
        }
Exemplo n.º 21
0
        static async Task <(byte[] encryptedKey, byte[] encryptedIV, byte[] ciphertext)> GetEncryptedData(RSAParameters publicKey, string text)
        {
            byte[] ciphertext;
            byte[] key;
            byte[] iv;

            // Use AES to encrypt secret message.
            using (var aes = new AesCng())
            {
                key = aes.Key;
                iv  = aes.IV;
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, aes.CreateEncryptor(), CryptoStreamMode.Write))
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            await swEncrypt.WriteAsync("Secret Message");
                        }

                    ciphertext = msEncrypt.ToArray();
                }
            }

            // Use RSA to encrypt AES key/IV
            using (var rsa = new RSACng())
            {
                // Import given public key to RSA
                rsa.ImportParameters(publicKey);

                // Encrypt symmetric key/IV using RSA (public key).
                // Return encrypted key/IV and ciphertext
                return(encryptedKey : rsa.Encrypt(key, RSAEncryptionPadding.OaepSHA512),
                       encryptedIV : rsa.Encrypt(iv, RSAEncryptionPadding.OaepSHA512),
                       ciphertext);
            }
        }
Exemplo n.º 22
0
        public void AesCngCreateEncryptor()
        {
            using var aes = new AesCng();
            using var rng = new RNGCryptoServiceProvider();

            var noParams = aes.CreateEncryptor(); // Compliant

            aes.GenerateKey();
            var withGeneratedKey = aes.CreateEncryptor(); // Compliant

            var constantIV   = new byte[16];
            var withConstant = aes.CreateEncryptor(aes.Key, constantIV); // Noncompliant

            aes.GenerateIV();
            aes.CreateEncryptor();
            var withGeneratedKeyAndIV = aes.CreateEncryptor(aes.Key, aes.IV);

            aes.CreateDecryptor(aes.Key, constantIV); // Compliant, we do not check CreateDecryptor

            rng.GetBytes(constantIV);
            var fromRng = aes.CreateEncryptor(aes.Key, constantIV);
        }
Exemplo n.º 23
0
 public ICryptoTransform CreateEncryptorCng()
 {
     return(_Aes256Cng.CreateEncryptor());
 }
Exemplo n.º 24
0
        // функция для СИММ. Шифрования массива байт заданным алгоритмом и режимом, на выходе массив байт
        // аргументы: вход. байты; ключ; вектор инициализации; алгоритм AES / 3DES; режим шифруем / расшифровываем
        public static Byte[] SimmAlg(Byte[] arrayByte_in, Byte[] key, Byte[] iv, string selectedAlgSimm, bool EncryptIsTrue)
        {
            byte[]           arrayByte_out = new byte[0]; // Выходная последовательность байт после шифрования/расшифровки
            ICryptoTransform cryptoTransform;

            try
            {
                switch (selectedAlgSimm) // Получение хеша определенным алгоритмом
                {
                case "AES":
                    AesCng aescng = new AesCng(); // объект класса у алгоритма AES
                    aescng.Key = key;             // присваиваем ключ из аргумента
                    aescng.IV  = iv;              // присваиваем вектор из аргумента
                    if (EncryptIsTrue == true)    // если вызвали для ШИФРования AES
                    {
                        // создали объект-шифратор
                        cryptoTransform = aescng.CreateEncryptor();
                    }
                    else      // если вызвали для РАСшифровки AES
                    {
                        // создали объект-расшифратор
                        cryptoTransform = aescng.CreateDecryptor();
                    }
                    // получили байты на выходе
                    arrayByte_out = cryptoTransform.TransformFinalBlock(arrayByte_in, 0, arrayByte_in.Length);

                    aescng.Dispose();          // освобождаем ресурсы
                    cryptoTransform.Dispose(); // освобождаем ресурсы
                    break;

                case "3DES":
                    TripleDESCng tripledescng = new TripleDESCng(); // объект класса у алгоритма AES
                    tripledescng.Key = key;                         //  присваиваем ключ из аргумента
                    tripledescng.IV  = iv;                          //  присваиваем вектор из аргумента
                    if (EncryptIsTrue == true)                      // если вызвали для ШИФРования AES
                    {
                        // создали объект-шифратор
                        cryptoTransform = tripledescng.CreateEncryptor();
                    }
                    else      // если вызвали для РАСшифровки 3DES
                    {
                        // создали объект-расшифратор
                        cryptoTransform = tripledescng.CreateDecryptor();
                    }
                    // получили байты на выходе
                    arrayByte_out = cryptoTransform.TransformFinalBlock(arrayByte_in, 0, arrayByte_in.Length);

                    tripledescng.Dispose();     // освобождаем ресурсы
                    cryptoTransform.Dispose();  // освобождаем ресурсы
                    break;

                default: break;
                }
            }
            catch (Exception error)
            {
                //MessageBox.Show(error.Message, "НЕПРЕДВИДЕННАЯ ОШИБКА", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (EncryptIsTrue == true) // если шифрование
                {
                    MessageBox.Show(error.Message, "НЕПРЕДВИДЕННАЯ ОШИБКА", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                //MessageBox.Show("Ключ или вектор инициализации не подходят", "Ошибка шифрования", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    MessageBox.Show("Заданные ключ или вектор инициализации не подходят для заданного шифра!\nРасшифровка не возможна.", "Ошибка расшифровки", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            return(arrayByte_out);
        }