How to Encrypt the SQLite DB File using AES

Here, we will discuss how to encrypt the SQLite DB file using an AES encryption method in .NET C#, encrypting using AES symmetric encryption algorithm, which stands for Advanced Encryption Standard. Using key and IV - -initialization vector encryption will be done from the sender. From the receiver, the same key will be used and decrypted from the other end.

IV is a pseudo-random value multiple times encrypting the plain text, IV size typically 16 bytes (128 bits). AES supports different key sizes like 128 bits, 192 bits, and 256 bits. Hash key using SHA256 method example is given here.

using System.Security.Cryptography;
using System.Text;

Console.WriteLine("SQLite DB file Encrpytion");
 
string encryptedCsvFilePath = @"file path";
using (var aesAlg = new AesCryptoServiceProvider())
{
    byte[][] KeyIV = GetHashKeys();
    aesAlg.Key = KeyIV[0];
    aesAlg.IV = KeyIV[1];

    using (FileStream inputFileStream = new FileStream(@"file path", FileMode.Open))
    using (FileStream outputFileStream = new FileStream(encryptedCsvFilePath, FileMode.Create))
    using (ICryptoTransform encryptor = aesAlg.CreateEncryptor())
    using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write))
    {
        inputFileStream.CopyTo(cryptoStream);
        Console.WriteLine("Encrpytion in progress..... ");
    }
    Console.WriteLine(" Encrpytion completed ");
}

 public static string EncryptStringToBytes_Aes(string strPlainText, byte[] Key, byte[] IV)
          {
              byte[] encrypted;
              try
              {
                  //check the plaintext & key exists or not
                  if (strPlainText == null || strPlainText.Length <= 0)
                      throw new ArgumentNullException("strPlainText");
                  if (Key == null || Key.Length <= 0)
                      throw new ArgumentNullException("_strEncryptionKey");
                  if (IV == null || IV.Length <= 0)
                      throw new ArgumentNullException("IV");
                  using (AesManaged aesAlg = new AesManaged())
                  {
                      //encrypt the text using Hash key &  initialization vector
                      aesAlg.Key = Key;
                      aesAlg.IV = IV;
                      ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                      using (MemoryStream msEncrypt = new MemoryStream())
                      {
                          using (CryptoStream csEncrypt =
                                  new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                          {
                              using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                              {
                                  swEncrypt.Write(strPlainText);
                              }
                              //encrpted array is generated and save in string
                              encrypted = msEncrypt.ToArray();
                          }
                      }
                  }
              }
              catch (Exception ex) { throw new Exception(ex.Message); }

              //generete a encoded string using base64
              return Convert.ToBase64String(encrypted);
          }

Using Security.Cryptography library AES encryption encryption is handled, and CryptographicException is used for Exception handling. SHA256CryptoServiceProvider is used to get the hash key.

 public static byte[][] GetHashKeys()
 {
     byte[][] result = new byte[2][];
     try
     {
         Encoding enc = Encoding.UTF8;
         SHA256 sha2 = new SHA256CryptoServiceProvider();
         //covert the readable key hashing value in byte array
         byte[] raw_strEncryptionKey = enc.GetBytes(_strEncryptionKey);
         byte[] rawIV = enc.GetBytes(_strEncryptionKey);
         // initialization vector and hashkey genrate
         byte[] hash_strEncryptionKey = sha2.ComputeHash(raw_strEncryptionKey);
         byte[] hashIV = sha2.ComputeHash(rawIV);
         Array.Resize(ref hashIV, 16);
         result[0] = hash_strEncryptionKey;
         result[1] = hashIV;

     }
     catch (Exception ex) {  throw new Exception(ex.Message); }
     return result;
 }

Using the FileStream class, an Encrypted SQLite DB file will be created.

 public static void CreateEncrytedSQLiteFile()
 {
     try
     {
         using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
         {
             byte[][] KeyIV = GetHashKeys();
             aesAlg.Key = KeyIV[0];
             aesAlg.IV = KeyIV[1];

             using (FileStream inputFileStream = new FileStream(SQLITE_DB_FILE, FileMode.Open))
             using (FileStream outputFileStream = new FileStream(SQLITE_DB_ENCRYTED_FILE, FileMode.Create))
             using (ICryptoTransform encryptor = aesAlg.CreateEncryptor())
             using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write))
             {
                 inputFileStream.CopyTo(cryptoStream);
             }
         }
       
     }
     catch (Exception ex) {  throw ex; }

 }

Output

SQLite DB file Encrpytion

Up Next
    Ebook Download
    View all
    Learn
    View all