Created
July 25, 2022 20:35
-
-
Save DarioAlonsoCerezo/36575b4cd6c59f3f7f1c8e1d79662714 to your computer and use it in GitHub Desktop.
Generate a new encrypted database for Microsoft.Data.Sqlite.Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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