forked from dotnet/efcore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
88 lines (76 loc) · 2.9 KB
/
Copy pathProgram.cs
File metadata and controls
88 lines (76 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.IO;
using Microsoft.Data.Sqlite;
namespace EncryptionSample
{
class Program
{
static void Main()
{
const string connectionString = "Data Source=EncryptionSample.db";
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
// Notice which packages are referenced by this project:
// - Microsoft.Data.Sqlite.Core
// - SQLitePCLRaw.bundle_sqlcipher
// Immediately after opening the connection, send PRAGMA key to use encryption
var keyCommand = connection.CreateCommand();
keyCommand.CommandText =
@"
PRAGMA key = 'password';
";
keyCommand.ExecuteNonQuery();
var createCommand = connection.CreateCommand();
createCommand.CommandText =
@"
CREATE TABLE data (
value TEXT
);
INSERT INTO data
VALUES ('Hello, encryption!');
";
createCommand.ExecuteNonQuery();
}
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
Console.Write("Password (it's 'password'): ");
var password = Console.ReadLine();
// Sanitize the user input using the quote() function
var quoteCommand = connection.CreateCommand();
quoteCommand.CommandText =
@"
SELECT quote($value)
";
quoteCommand.Parameters.AddWithValue("$value", password);
var quotedPassword = (string)quoteCommand.ExecuteScalar();
// PRAGMA statements can't be parameterized. We're forced to concatenate the
// escaped user input
var keyCommand = connection.CreateCommand();
keyCommand.CommandText =
$@"
PRAGMA key = {quotedPassword}
";
keyCommand.ExecuteScalar();
try
{
var queryCommand = connection.CreateCommand();
queryCommand.CommandText =
@"
SELECT *
FROM data
";
var data = (string)queryCommand.ExecuteScalar();
Console.WriteLine(data);
}
catch (SqliteException ex) when (ex.SqliteErrorCode == SQLitePCL.raw.SQLITE_NOTADB)
{
Console.WriteLine("Access denied.");
}
}
// Clean up
File.Delete("EncryptionSample.db");
}
}
}