示例#1
0
        public void AesCngPaddingRoundTripTests()
        {
            int blockSize = 0;

            using (AesCng aes = new AesCng())
            {
                blockSize = aes.BlockSize / 8;
            }

            using (RNGCng rng = new RNGCng())
            {
                byte[] zeroByte = new byte[0];

                byte[] oneByte = new byte[1];
                rng.GetBytes(oneByte);

                byte[] blockMinusOne = new byte[blockSize - 1];
                rng.GetBytes(blockMinusOne);

                byte[] block = new byte[blockSize];
                rng.GetBytes(block);

                byte[] blockPlusOne = new byte[blockSize + 1];
                rng.GetBytes(blockPlusOne);

                foreach (var paddingMode in new PaddingMode[] { PaddingMode.ANSIX923, PaddingMode.ISO10126, PaddingMode.PKCS7 })
                {
                    Assert.IsTrue(RoundTripHelper(zeroByte, typeof(AesCng), typeof(AesCng), (aes) => { aes.Padding = paddingMode; }), paddingMode.ToString() + " - zeroByte");
                    Assert.IsTrue(RoundTripHelper(oneByte, typeof(AesCng), typeof(AesCng), (aes) => { aes.Padding = paddingMode; }), paddingMode.ToString() + " - oneByte");
                    Assert.IsTrue(RoundTripHelper(blockMinusOne, typeof(AesCng), typeof(AesCng), (aes) => { aes.Padding = paddingMode; }), paddingMode.ToString() + " - blockMinusOne");
                    Assert.IsTrue(RoundTripHelper(block, typeof(AesCng), typeof(AesCng), (aes) => { aes.Padding = paddingMode; }), paddingMode.ToString() + " - block");
                    Assert.IsTrue(RoundTripHelper(blockPlusOne, typeof(AesCng), typeof(AesCng), (aes) => { aes.Padding = paddingMode; }), paddingMode.ToString() + " - blockPlusOne");
                }
            }
        }
示例#2
0
        private static (byte[] CipherText, byte[] IV) EncryptData(byte[] data, byte[] key)
        {
            Aes aes;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                aes = new AesCng();
            }
            else
            {
                aes = new AesManaged();
            }

            aes.Key = key;
            var iv = RandomNumberOracle.GetRandomBytes(16);

            aes.IV = iv;

            using var encryptor = aes.CreateEncryptor();

            byte[] cipherText = encryptor.TransformFinalBlock(data, 0, data.Length);

            //Log.Verbose($"Encrypting message with key: {key.ToHashedHexString()}");
            //Log.Verbose($"Encrypting message with IV: {aes.IV.ToHashedHexString()}");
            //Log.Verbose($"Cipher text: {cipherText.ToHashedHexString()}");
            //Log.Verbose($"Plaintext: {data.ToHashedHexString()}");

            aes.Dispose();

            return(cipherText, iv);
        }
        public void CompliantAES()
        {
            AesManaged aes1 = new AesManaged
            {
                KeySize   = 128, // Compliant
                BlockSize = 128,
                Mode      = CipherMode.CBC,
                Padding   = PaddingMode.PKCS7
            };

            AesCryptoServiceProvider aes2 = new AesCryptoServiceProvider();

            aes2.KeySize = 128; // Compliant

            AesCng aes3 = new AesCng();

            aes3.KeySize = 128; // Compliant

            AesManaged aes4 = new AesManaged
            {
                KeySize   = 64, // OK - ignore as it is not possible to create AES instance with smaller than 128 key size
                BlockSize = 128,
                Mode      = CipherMode.CBC,
                Padding   = PaddingMode.PKCS7
            };

            AesCryptoServiceProvider aes5 = new AesCryptoServiceProvider();

            aes5.KeySize = 64; // OK - ignore as it is not possible to create AES instance with smaller than 128 key size

            AesCng aes6 = new AesCng();

            aes6.KeySize = 64; // OK - ignore as it is not possible to create AES instance with smaller than 128 key size
        }
        private byte[] DecryptBytes(string file)
        {
            byte[] encryptedByteArray = 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.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(encryptedByteArray, 0, encryptedByteArray.Length);
                        cryptoStream.Close();
                        byte[] decryptedBytes = memStream.ToArray();
#if DEBUG
                        Console.WriteLine($"{ConsoleDateTag()} Decrypting {GetFileNameFromPath(file)} using password {passwordTextBox.Text}");
#endif
                        ZeroMemory(gcHandle.AddrOfPinnedObject(), aes.Key.Length);
                        return(decryptedBytes);
                    }
                }
            }
        }
示例#5
0
        //[Fact] - Keeping this test for reference but we don't want to run it as an inner-loop test because
        //         it creates a key on disk.
        public static void AesRoundTrip256BitsNoneECBUsingStoredKey()
        {
            CngAlgorithm algname = new CngAlgorithm("AES");
            string       keyName = "CoreFxTest-" + Guid.NewGuid();
            CngKey       _cngKey = CngKey.Create(algname, keyName);

            try
            {
                using (Aes alg = new AesCng(keyName))
                {
                    try
                    {
                        alg.Padding = PaddingMode.None;
                        alg.Mode    = CipherMode.ECB;

                        int keySize = alg.KeySize;

                        byte[] plainText         = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray();
                        byte[] cipher            = alg.Encrypt(plainText);
                        byte[] decrypted         = alg.Decrypt(cipher);
                        byte[] expectedDecrypted = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray();
                        Assert.Equal <byte>(expectedDecrypted, decrypted);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            finally
            {
                _cngKey.Delete();
            }
        }
示例#6
0
        public void AesCngModeRoundTripTests()
        {
            int blockSize = 0;

            using (AesCng aes = new AesCng())
            {
                blockSize = aes.BlockSize / 8;
            }

            using (RNGCng rng = new RNGCng())
            {
                for (int i = 1; i <= 10; ++i)
                {
                    byte[] data = new byte[i * blockSize];
                    rng.GetBytes(data);

                    foreach (var cipherMode in new CipherMode[] { CipherMode.CBC, CipherMode.ECB, CipherMode.CFB })
                    {
                        Assert.IsTrue(RoundTripHelper(data, typeof(AesCng), typeof(AesCng), (aes) => { aes.Mode = cipherMode; }), i.ToString() + " blocks - " + cipherMode.ToString());
                    }

                    foreach (var chainingMode in new CngChainingMode[] { CngChainingMode.Cbc, CngChainingMode.Ecb, CngChainingMode.Cfb })
                    {
                        Assert.IsTrue(RoundTripHelper(data, typeof(AesCng), typeof(AesCng), (aes) => { (aes as ICngSymmetricAlgorithm).CngMode = chainingMode; }), i.ToString() + " blocks - " + chainingMode.ToString());
                    }
                }
            }
        }
示例#7
0
        static async Task <string> DecryptStringFromBytesAsync(byte[] cipherText, byte[] Key, byte[] IV)
        {
            string plaintext = string.Empty;

            using (var aes = new AesCng())
            {
                // Copy given key and IV into AES object
                aes.Key = Key;
                aes.IV  = IV;

                // Create decryptor
                ICryptoTransform decryptor = aes.CreateDecryptor();

                // Create memory stream that will read encrypted bytes from memory (byte[])
                using (var msDecrypt = new MemoryStream(cipherText))
                {
                    // Create crypto stream that does the decryption with the given decryptor
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        // Create reader with which we read the ciphertext for decryption
                        using (var srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read decrypted plaintext from crypto stream
                            plaintext = await srDecrypt.ReadToEndAsync();
                        }
                    }
                }
            }

            return(plaintext);
        }
示例#8
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));
        }
示例#9
0
 /// <summary>
 /// Decrypts a cipher text with a password using AES-256 CBC with SHA-256.
 /// </summary>
 /// <param name="cipherText">The cipher text to be decrypted.</param>
 /// <param name="password">The password to decrypt the cipher text with.</param>
 /// <returns>The decrypted text.</returns>
 public static string AESDecrypt(string cipherText, string password)
 {
     if (string.IsNullOrEmpty(cipherText))
     {
         return(string.Empty);
     }
     byte[] iv                  = new byte[16];
     byte[] passwordBytes       = Encoding.UTF8.GetBytes(password);
     byte[] cipherBytes         = Convert.FromBase64String(cipherText);
     byte[] hashedPasswordBytes = SHA256Managed.Create().ComputeHash(passwordBytes);
     Array.Copy(cipherBytes, iv, 16);
     byte[] decryptedBytes = null;
     using (AesCng AES = new AesCng())
     {
         AES.IV      = iv;
         AES.KeySize = 256;
         AES.Mode    = CipherMode.CBC;
         AES.Key     = hashedPasswordBytes;
         using ICryptoTransform decryptor = AES.CreateDecryptor();
         using MemoryStream msDecrypted   = new MemoryStream();
         using (CryptoStream csDecrypt = new CryptoStream(msDecrypted, decryptor, CryptoStreamMode.Write))
         {
             csDecrypt.Write(cipherBytes, 16, cipherBytes.Length - 16);
             csDecrypt.Close();
         }
         decryptedBytes = msDecrypted.ToArray();
     }
     return(Encoding.UTF8.GetString(decryptedBytes));
 }
示例#10
0
        private static byte[] DecryptData(byte[] cipherText, byte[] key, byte[] iv)
        {
            Aes aes;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                aes = new AesCng();
            }
            else
            {
                aes = new AesManaged();
            }
            aes.Key = key;
            aes.IV  = iv;

            //Log.Verbose($"Ciphertext: {cipherText.ToHashedHexString()}");
            //Log.Verbose($"Decrypting message with key: {key.ToHashedHexString()}");
            //Log.Verbose($"Decrypting message with IV: {aes.IV.ToHashedHexString()}");

            using var decryptor = aes.CreateDecryptor();

            byte[] plainText = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);

            //Log.Verbose($"Plaintext: {plainText.ToHashedHexString()}");

            aes.Dispose();

            return(plainText);
        }
示例#11
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
        }
示例#12
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);
        }
示例#13
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.}}
        }
示例#14
0
 public SerializableAes(AesCng aes)
 {
     IV      = aes.IV;
     Key     = aes.Key;
     KeySize = aes.KeySize;
     Mode    = aes.Mode;
     Padding = aes.Padding;
 }
示例#15
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());
                }
            }
        }
示例#16
0
 public Aes128_CBC()
 {
     _aes = new AesCng
     {
         KeySize = this.KeySize,
         Mode    = CipherMode.CBC,
         Padding = PaddingMode.None
     };
 }
示例#17
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)
                {
                }
            }
        }
        /// <summary>
        /// Getting an object of a cryptographic class
        /// </summary>
        /// <returns></returns>
        private SymmetricAlgorithm GetSymmetricAlgorithm(string encryptionKey)
        {
            var algorithm = new AesCng();

            var keyBytes = Encoding.ASCII.GetBytes(encryptionKey);

            algorithm.Key = keyBytes;

            return(algorithm);
        }
示例#19
0
        /// <summary>
        /// Getting an object of a cryptographic class
        /// </summary>
        /// <returns></returns>
        private SymmetricAlgorithm GetSymmetricAlgorithm(ApplicationDbContext context)
        {
            var algorithm = new AesCng();

            var keyBytes = Encoding.ASCII.GetBytes(context.Settings.FirstOrDefault(x => x.Key == "EncryptionKey")?.Value ?? "");

            algorithm.Key = keyBytes;

            return(algorithm);
        }
        /// <summary>
        /// Getting an object of a cryptographic class
        /// </summary>
        /// <returns></returns>
        private SymmetricAlgorithm GetSymmetricAlgorithm()
        {
            var algorithm = new AesCng();

            var keyBytes = Encoding.ASCII.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(encryptionKey)));

            algorithm.Key = keyBytes;

            return(algorithm);
        }
示例#21
0
        public AesCng GetAes()
        {
            AesCng aes = new AesCng();

            aes.KeySize = KeySize;
            aes.Mode    = Mode;
            aes.Padding = Padding;
            aes.IV      = IV;
            aes.Key     = Key;
            return(aes);
        }
示例#22
0
        public async Task Execute()
        {
            string text = "Encrypt/Decrypt using Aes algorithm";

            using var ars = new AesCng();
            byte[] bytes = await Encrypt(text, ars.Key, ars.IV);

            string sameText = await Decrypt(bytes, ars.Key, ars.IV);

            Console.WriteLine($"Original text = '{text}' & DecryptedText = '{sameText}'");
        }
示例#23
0
 public void AesCngDefaultPropertiesTest()
 {
     using (AesCng aes = new AesCng())
     {
         Assert.AreEqual(128, aes.BlockSize);
         Assert.AreEqual(CngChainingMode.Cbc, aes.CngMode);
         Assert.AreEqual(256, aes.KeySize);
         Assert.AreEqual(CipherMode.CBC, aes.Mode);
         Assert.AreEqual(PaddingMode.PKCS7, aes.Padding);
         Assert.AreEqual(CngProvider2.MicrosoftPrimitiveAlgorithmProvider, aes.Provider);
     }
 }
示例#24
0
        // при ЗАГРУЗКЕ ФОРМЫ для ввода ключа и IV
        private void Form2_Load(object sender, EventArgs e)
        {
            // Выделили память и установили длину ключей и IV
            // в зависимости от алгоритма
            aescng    = new AesCng();
            tripledes = new TripleDESCng();
            if (AlgName == "AES")
            {
                this.txt_key.MaxLength = 64;
                this.txt_iv.MaxLength  = 32;
            }

            if (AlgName == "3DES")
            {
                this.txt_key.MaxLength = 48;
                this.txt_iv.MaxLength  = 16;
            }

            // если раннее были введенны ключи то вывести их на форму
            if (global.Simm_KeyIV_isEntry)
            {
                this.txt_key.Text = alg.ByteArrayTOStringHEX(global.Simm_byte_key);
                this.txt_iv.Text  = alg.ByteArrayTOStringHEX(global.Simm_byte_iv);
            }

            // Подсказка у кнопки загрузки ключа
            this.toolTip_LoadKeyIV.ToolTipTitle = this.btn_loadKeyIV.Text;
            this.toolTip_LoadKeyIV.ToolTipIcon  = ToolTipIcon.Info;
            this.toolTip_LoadKeyIV.SetToolTip(this.btn_loadKeyIV, "В файле должно быть две строки в 16-ричном виде.\n1-ая строка: Ключ длинной 64 знака.\n2-ая строка: Вектор(IV) длиной 32 знакак.");

            // Инструкция сверху формы
            this.label_simm_entryKeyIV.Text  = "> Ключом могут быть только 16-ричные цифры (0-9, A-F).\n";
            this.label_simm_entryKeyIV.Text += "> Длина ключа должна быть обязательно равна " + txt_key.MaxLength + " знакам!\n\n";
            this.label_simm_entryKeyIV.Text += "> В векторе могут быть только 16-ричные цифры (0-9, A-F).\n";
            this.label_simm_entryKeyIV.Text += "> Длина должна быть обязательно равна " + txt_iv.MaxLength + " знакам!\n";


            if (global.Simm_EncryptOrDecrypt) // если загрузили для ШИФРОВАНИЯ
            {
                this.Text = "ШИФРОВАНИЕ: Ввод ключа (Key) и вектора инициализации (IV)";
                // показать кнопки случайно генерации
                this.btn_generate_key.Visible    = true;
                this.btn_generate_iv.Visible     = true;
                this.label_simm_entryKeyIV.Text += "\n> Стрелки - случайное заполнение ключа и вектора (IV).";
            }
            else  // если загрузили для РАСШИФРОВКИ
            {
                this.Text = "РАСШИФРОВКА: Ввод ключа (Key) и вектора инициализации (IV)";
                this.btn_generate_key.Visible = false;
                this.btn_generate_iv.Visible  = false;
            }
        }
示例#25
0
        protected static byte[] Decrypt(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.CreateDecryptor()) return(decryptor.TransformFinalBlock(bytes, offset, length));
            }
        }
示例#26
0
        public static bool DecryptFile(string filename, string password)
        {
            FileStream file           = File.OpenRead(filename);
            string     outputFileName = $"{filename}.decrypted";

            if (!(File.Exists(filename) && !File.Exists(outputFileName)))
            {
                return(false);
            }

            // read magic first
            byte[] buff = new byte[8];
            int    read = file.Read(buff, 0, 8);
            bool   returnValue;

            if (Encoding.UTF8.GetString(buff) != "Malted__")
            {
                returnValue = false;
            }
            else
            {
                byte[] salt = new byte[8];
                read = file.Read(salt, 0, 8);

                var    deriveKey = new Rfc2898DeriveBytes(password, salt, 1_000_000, HashAlgorithmName.SHA256);
                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);

                var aescng = new AesCng();
                aescng.Mode      = CipherMode.CBC;
                aescng.KeySize   = 256;
                aescng.BlockSize = 128;
                aescng.Padding   = PaddingMode.PKCS7;
                FileStream fileOutputStream = File.Create(outputFileName);
                var        decryptor        = aescng.CreateDecryptor(key, iv);

                using (CryptoStream csDecrypt = new CryptoStream(file, decryptor, CryptoStreamMode.Read))
                {
                    csDecrypt.CopyTo(fileOutputStream);
                }
                returnValue = true;
                fileOutputStream.Close();
            }

            file.Close();

            return(returnValue);
        }
示例#27
0
        public static void EncryptSomeText()
        {
            string original = "My secret data!";

            using (SymmetricAlgorithm symmetricAlgorithm = new AesCng())
            {
                byte[] encryted = Encrypt(symmetricAlgorithm, original);

                var originByte = Encoding.ASCII.GetBytes(original);
                Console.WriteLine(string.Join(" ", originByte));
                Console.WriteLine(string.Join(" ", encryted));
                Console.Read();
            }
        }
示例#28
0
 /// <summary></summary>
 public void Dispose()
 {
     if (_AesServices != null)
     {
         _AesServices.Clear();
         _AesServices = null;
     }
     if (_MD5Services != null)
     {
         _MD5Services.Dispose();
         _MD5Services = null;
     }
     if (_SHA1Services != null)
     {
         _SHA1Services.Dispose();
         _SHA1Services = null;
     }
     if (_SHA256Services != null)
     {
         _SHA256Services.Dispose();
         _SHA256Services = null;
     }
     if (_SHA384Services != null)
     {
         _SHA384Services.Dispose();
         _SHA384Services = null;
     }
     if (_SHA512Services != null)
     {
         _SHA512Services.Dispose();
         _SHA512Services = null;
     }
     if (_Pkcs11Library != null)
     {
         _Pkcs11Library.Dispose();
         _Pkcs11Library = null;
     }
     if (_Randomness != null)
     {
         _Randomness.Dispose();
         _Randomness = null;
     }
     if (_RsaServices != null)
     {
         _RsaServices.Clear();
         _RsaServices = null;
     }
 }
示例#29
0
        private static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, int nonSecretPayloadLength)
        {
            //Basic Usage Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException($"CryptKey needs to be {KeyBitSize} bit!", nameof(cryptKey));
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage));
            }


            var ivLength = (BlockBitSize / 8);

            using (var aes = new AesCng
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {
                //Grab IV from message
                var iv = new byte[ivLength];
                Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
                    using (var plainTextStream = new MemoryStream())
                    {
                        using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
                            using (var binaryWriter = new BinaryWriter(decrypterStream))
                            {
                                //Decrypt Cipher Text from Message
                                binaryWriter.Write(
                                    encryptedMessage,
                                    nonSecretPayloadLength + iv.Length,
                                    encryptedMessage.Length - nonSecretPayloadLength - iv.Length
                                    );
                            }
                        //Return Plain Text

                        var pt = plainTextStream.ToArray();
                        return(pt);
                    }
            }
        }
示例#30
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)}");
            }
        }