How to Use AES to Encrypt a SQLite Database File?

Leave a Comment

Here, we'll go over how to use the Advanced Encryption Standard (AES) symmetric encryption algorithm to encrypt the SQLite DB file in.NET C#. The encryption will be carried out from the sender using a key and IV (initialization vector). The same key will be used by the receiver to decode the data on 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


 

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 8.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/


Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment