1

new to AES, I visited several threads about it, ex: examples of Dan Esparza, Zeeshan Amber at this thread Simple encryption algorithm in c#.net , and smdrager at Simple encryption algorithm in c#.net

I tried to use some examples in my case, but I found something incorrect, let me explain:

  1. I want to encrypt a binary file (named "exa" ).
  2. I use git to check whether output file is different from input file.
  3. I read input file to stream(byte[] or string).
  4. Just after that, write to a different file by using File.WriteAllBytes() right away. ( make sure the reading bytes are right , succseed )
  5. Then, I used the examples of Dan Esparza, smdrager, Zeeshan Amber
  6. Every time I finished, I compared the decrypt bytes in memory from the original ones and see if the bytes different.
  7. I saved the decrypt result to file and compare.
  8. The results are all disappointing, all files failed, but in some cases the bytes comparison are fine.

The example of smdrager

byte[] orgBytes = File.ReadAllBytes("exa");

byte[] encQuote = EncryptByteToBytes(orgBytes , "password" );
byte[] endByte = DecryptToByte(encQuote, "password");

File.WriteAllBytes("exaOutputBytes", endByte);

The comparison failed in byte number, also failed in file comparison.

orgBytes.Length : 55732
endByte.Length : 55744

The example of Dan Esparza

In this case, bytes input will fail, therefore, I read by text with ASCII.

        string original = File.ReadAllText("exa" , Encoding.ASCII );

        using (RijndaelManaged myRijndael = new RijndaelManaged())
        {

            myRijndael.GenerateKey();
            myRijndael.GenerateIV();
            // Encrypt the string to an array of bytes. 
            byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

            // Decrypt the bytes to a string. 
            string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

            File.WriteAllText("exaOutputString", roundtrip , Encoding.ASCII);

The bytes comparison was fine, both in length and each byte content. But file comparison still failed.

The example of Zeeshan Amber

I use password and iv the same as example.

            Crypt cryptObj = new Crypt();

            string encryStr = cryptObj.Encrypt(original, "AGARAMUDHALA", "EZHUTHELLAM", "SHA1", 3, "@1B2c3D4e5F6g7H8", 256);
            string decryStr = cryptObj.Decrypt(encryStr, "AGARAMUDHALA", "EZHUTHELLAM", "SHA1", 3, "@1B2c3D4e5F6g7H8", 256);

In this case, the same with Dan Esparza , failed in file comparison.

I think the problem should be at my file importing/exporting, maybe special character in file, EOL, or BOM. I also tried different encoding when writing files, but found nothing.

Does anyone have something in mind?

Community
  • 1
  • 1
NDark
  • 60
  • 8
  • If you want to transfer bytes, don't treat them as text. If you must, use an encoding like CP437 that has the essential property of 256 codepoints encoded as values 0 to 255 with no invalid sequences—in other words, arbitrary bytes. ASCII, Windows-1252, UTF-8, etc don't have this property. – Tom Blodget May 08 '15 at 01:23
  • I see. Those code I found may only work on text input. – NDark May 11 '15 at 06:08

2 Answers2

1

I don't know why do you need the password in the encryption/decryption process and why do you encrypt/decrypt strings when you are basically working with bytes (files).

Here is an example using bytes and key/iv (pseudo)randomly generated:

using System;
using System.IO;
using System.Security.Cryptography;

namespace AesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] key = null;
            byte[] iv = null;
            byte[] bytesToEncrypt = null;
            byte[] encryptedBytes = null;
            byte[] decryptedBytes = null;

            // generate key and iv to use for encryption/decryption. 
            using (RijndaelManaged aesAlg = new RijndaelManaged())
            {
                aesAlg.GenerateKey();
                aesAlg.GenerateIV();
                key = aesAlg.Key;
                iv = aesAlg.IV;
            }

            // original bytes
            bytesToEncrypt = File.ReadAllBytes(@"c:\exe");
            Console.WriteLine("Bytes read: {0}",bytesToEncrypt.Length);

            // encrypt
            encryptedBytes = CryptoAes.Encrypt(bytesToEncrypt, key, iv);
            Console.WriteLine("Encrypted bytes length: {0}", encryptedBytes.Length);

            // decrypt
            decryptedBytes = CryptoAes.Decrypt(encryptedBytes, key, iv);
            Console.WriteLine("Decrypted bytes length: {0}", decryptedBytes.Length);

            // compare
            Console.WriteLine("Decrypted bytes same as original bytes: {0}", Convert.ToBase64String(decryptedBytes) == Convert.ToBase64String(bytesToEncrypt));
            Console.ReadLine();
        }
    }

    internal sealed class CryptoAes
    {
        /// <summary>
        /// Encrypts data with symetric key
        /// </summary>
        /// <param name="data">Data to be encrypted</param>
        /// <param name="key">Symetric key</param>
        /// <param name="iv">Initialization vector</param>
        /// <returns>Encrypted data</returns>
        public static byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
        {
            byte[] encryptedData = null;

            if (data == null)
                throw new ArgumentNullException("data");

            if (data == key)
                throw new ArgumentNullException("key");

            if (data == iv)
                throw new ArgumentNullException("iv");

            using (RijndaelManaged aesAlg = new RijndaelManaged())
            {
                aesAlg.Key = key;
                aesAlg.IV = iv;

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);
            }

            return encryptedData;
        }

        /// <summary>
        /// Decrypts data with symetric key
        /// </summary>
        /// <param name="data">Encrypted data</param>
        /// <param name="key">Symetric key</param>
        /// <param name="iv">Initialization vector</param>
        /// <returns>Decrypted data</returns>
        public static byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
        {
            byte[] decryptedData = null;

            if (data == null)
                throw new ArgumentNullException("data");

            if (data == key)
                throw new ArgumentNullException("key");

            if (data == iv)
                throw new ArgumentNullException("iv");

            using (RijndaelManaged aesAlg = new RijndaelManaged())
            {
                aesAlg.Key = key;
                aesAlg.IV = iv;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);
            }

            return decryptedData;
        }
    }
}
pepo
  • 8,644
  • 2
  • 27
  • 42
0

ASE file encryption

internal const string Inputkey = "560A18CD-6346-4CF0-A2E8-671F9B6B9EA9";
    ///<summary>
    /// Arvind - 23/11/2017.
    ///
    /// Encrypts a file using Rijndael algorithm.
    ///</summary>
    ///<param name="inputFile"></param>
    ///<param name="outputFile"></param>
    public static void EncryptFile(string inputFile, string outputFile)
    {
        try
        {
            string password = @"+kdkdkdjd8656589$**hh$^JHJBKLJJH#$$$__+0-f5546%$$^5434+"; // Secret Key
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
            Rijndael RMCrypto = NewRijndaelManaged(password);

            var encryptor = RMCrypto.CreateEncryptor(RMCrypto.Key, RMCrypto.IV);

            CryptoStream cs = new CryptoStream(fsCrypt,
                encryptor,
                CryptoStreamMode.Write);

            FileStream fsIn = new FileStream(inputFile, FileMode.Open);

            int data;
            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);


            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Encryption failed!" + ex.Message);
        }
    }


    /// <summary>
    /// Create a new RijndaelManaged class and initialize it
    /// </summary>
    /// <param name="salt" />The pasword salt
    /// <returns></returns>
    private static RijndaelManaged NewRijndaelManaged(string salt)
    {
        if (salt == null) throw new ArgumentNullException("salt");
        var saltBytes = Encoding.ASCII.GetBytes(salt);
        var key = new Rfc2898DeriveBytes(Inputkey, saltBytes);

        var aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
        aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

        return aesAlg;
    }

    **File decryption**
///<summary>
    /// Arvind - 23/11/2017.
    ///
    /// Decrypts a file using Rijndael algorithm.
    ///</summary>
    ///<param name="inputFile"></param>
    ///<param name="outputFile"></param>
    public static void DecryptDatabaseFile(string inputFile, string outputFile)
    {
        try
        {
            string password = System.Configuration.ConfigurationManager.AppSettings["encryptionKey"];
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
            var aesAlg = NewRijndaelManaged(password);
            var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            CryptoStream cs = new CryptoStream(fsCrypt,
               decryptor,
                CryptoStreamMode.Read);

            FileStream fsOut = new FileStream(outputFile, FileMode.Create);
            int data;
            while ((data = cs.ReadByte()) != -1)
                fsOut.WriteByte((byte)data);

            fsOut.Close();
            cs.Close();
            fsCrypt.Close();

        }
        catch (Exception ex)
        {
            throw new ApplicationException("decryption Fail!!" + ex.Message);
        }
    }
Arvind Singh
  • 71
  • 1
  • 3