Skip to content

Instantly share code, notes, and snippets.

@DarioAlonsoCerezo
Created July 25, 2022 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarioAlonsoCerezo/36575b4cd6c59f3f7f1c8e1d79662714 to your computer and use it in GitHub Desktop.
Save DarioAlonsoCerezo/36575b4cd6c59f3f7f1c8e1d79662714 to your computer and use it in GitHub Desktop.
Generate a new encrypted database for Microsoft.Data.Sqlite.Core
public class GenerateDatabase
{
public void Generate()
{
var databasePlainName = "plaintext.db";
var databasePlainPath = Path.Combine(FileSystem.AppDataDirectory, databasePlainName);
var databaseEncryptedName = "database_encrypted.db";
var databaseEncryptedPath = Path.Combine(FileSystem.AppDataDirectory, databaseEncryptedName);
var databasePassword = "YOUR_SUPER_SECRET_PASSWORD";
var encryptQuery = @$"ATTACH DATABASE '{databasePath}' AS database_encrypted KEY '{YOUR_SUPER_SECRET_PASSWORD}'; SELECT sqlcipher_export('database_encrypted'); DETACH DATABASE database_encrypted;";
var connection = new SqliteConnection($"Data Source = {databasePlainPath}");
connection.Open();
using var cmd = new SqliteCommand(encryptQuery, connection);
cmd.ExecuteNonQuery();
connection.Close();
if (File.Exists(databasePlainPath))
{
File.Delete(databasePlainPath);
}
//from here, you can connect to your database using your password. Enjoy!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment