Skip to content

Commit f579e11

Browse files
committed
Fix issue with encrypted db and Clone()
1 parent 319a05a commit f579e11

5 files changed

Lines changed: 70 additions & 94 deletions

File tree

README.md

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,19 @@ The T in `db.Query<T>` specifies the object to create for each row. It can be a
171171

172172
## Using an encrypted database file
173173

174-
Add the nuget [SQLitePCLRaw.bundle_e_sqlcipher](https://www.nuget.org/packages/SQLitePCLRaw.bundle_e_sqlcipher) to your common project.
175-
Then add this code right after opening or creating the db, and before any other db call:
174+
Add the nuget [SQLitePCLRaw.bundle_e_sqlcipher](https://www.nuget.org/packages/SQLitePCLRaw.bundle_e_sqlcipher) to your common project.
175+
176+
### Option 1 (preferred)
177+
178+
Use the `encryptionKey` parameter in the constructor of `SQLiteConnection`.
179+
180+
Then use the db as usual.
181+
182+
With this option, the encryption key is kept in memory. That should not be an issue.
183+
184+
185+
### Option 2 (roots)
186+
Add this code right after opening or creating the db, and before any other db call:
176187

177188
```c#
178189
string key = "yourCryptingKey";
@@ -182,8 +193,12 @@ if(ok != "ok")
182193
throw new Exception("Bad key");
183194
```
184195

196+
If you will use `InsertAll(), InsertOrUpdateAll(), ReplaceAll()` you must create a new class deriving from `SQLiteConnection` and override `Clone()` so it sets the encryption key after cloning.
197+
185198
Then use the db as usual.
186199

200+
### Final Thoughts
201+
187202
You can read the version of the cypher lib using the code. Check the [Zenetik](//https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_version) website for more information.
188203

189204
```c#

SQLite.Net.Tests/BlobSerializationTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public abstract class BlobSerializationTest : BaseTest
1616
public class BlobDatabase : SQLiteConnection
1717
{
1818
public BlobDatabase(IBlobSerializer serializer) :
19-
base(TestPath.CreateTemporaryDatabase(), false, serializer)
19+
base(TestPath.CreateTemporaryDatabase(), storeDateTimeAsTicks: false, serializer: serializer)
2020
{
2121
DropTable<ComplexOrder>();
2222
}

SQLite.Net.Tests/TestDb.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,10 @@ public enum OrderLineStatus
106106
public class TestDb : SQLiteConnection
107107
{
108108
public TestDb(bool storeDateTimeAsTicks = true, IContractResolver resolver = null)
109-
: base(
110-
TestPath.CreateTemporaryDatabase(), storeDateTimeAsTicks, null,
111-
extraTypeMappings: null,
112-
resolver: resolver)
113-
{
109+
: base(TestPath.CreateTemporaryDatabase(), storeDateTimeAsTicks: storeDateTimeAsTicks, resolver: resolver)
110+
{
114111
TraceListener = DebugTraceListener.Instance;
115-
}
112+
}
116113
}
117114

118115
public class TestPath

nuget/pack.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ if ($IsMacOS) {
77
$msbuild = join-path $msbuild 'MSBuild\Current\Bin\MSBuild.exe'
88
}
99
$version="2.1.0"
10-
$versionSuffix="-pre2"
10+
$versionSuffix="-pre3"
1111

1212
#####################
1313
#Build release config

src/SQLite.Net/SQLiteConnection.cs

Lines changed: 48 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,22 @@
11
//
2-
// Copyright (c) 2012 Krueger Systems, Inc.
3-
// Copyright (c) 2013 Øystein Krog (oystein.krog@gmail.com)
4-
// Copyright (c) 2014 Benjamin Mayrargue (softlion@softlion.com)
2+
// Copyright (c) 2014-2022 Benjamin Mayrargue (benjamin@vapolia.fr)
53
// - Support for multi-columns primary keys (create table / get / find / delete)
64
// - ExecuteSimpleQuery
7-
// - Fix disposing bug
5+
// - Fix disposing issues
6+
// - Remove locks
7+
// - Fix transaction issues
8+
// Copyright (c) 2013 Øystein Krog (oystein.krog@gmail.com)
9+
// Copyright (c) 2012 Krueger Systems, Inc.
810
//
9-
// Permission is hereby granted, free of charge, to any person obtaining a copy
10-
// of this software and associated documentation files (the "Software"), to deal
11-
// in the Software without restriction, including without limitation the rights
12-
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13-
// copies of the Software, and to permit persons to whom the Software is
14-
// furnished to do so, subject to the following conditions:
11+
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
12+
// in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
1514
//
16-
// The above copyright notice and this permission notice shall be included in
17-
// all copies or substantial portions of the Software.
15+
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
1816
//
19-
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20-
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21-
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22-
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23-
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24-
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25-
// THE SOFTWARE.
26-
//
17+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2720

2821
using System;
2922
using System.Collections;
@@ -40,7 +33,7 @@
4033
namespace SQLite.Net2
4134
{
4235
/// <summary>
43-
/// Represents an open connection to a SQLite database.
36+
/// Represents an open connection to a SQLite database.
4437
/// </summary>
4538
public class SQLiteConnection : IDisposable
4639
{
@@ -64,6 +57,7 @@ public class SQLiteConnection : IDisposable
6457
private bool _open;
6558
private Stopwatch? _sw;
6659
private readonly SQLiteOpenFlags databaseOpenFlags;
60+
private readonly string encryptionKey;
6761

6862
public IBlobSerializer? Serializer { get; }
6963
public string DatabasePath { get;}
@@ -84,82 +78,40 @@ static SQLiteConnection()
8478
}
8579
}
8680

87-
/// <summary>
88-
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
89-
/// </summary>
90-
/// <param name="sqlitePlatform"></param>
91-
/// <param name="databasePath">
92-
/// Specifies the path to the database file.
93-
/// </param>
94-
/// <param name="storeDateTimeAsTicks">
95-
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
96-
/// absolutely do want to store them as Ticks in all new projects. The option to set false is
97-
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
98-
/// down sides, when setting storeDateTimeAsTicks = true.
99-
/// </param>
100-
/// <param name="serializer">
101-
/// Blob serializer to use for storing undefined and complex data structures. If left null
102-
/// these types will thrown an exception as usual.
103-
/// </param>
104-
/// <param name="tableMappings">
105-
/// Exisiting table mapping that the connection can use. If its null, it creates the mappings,
106-
/// if and when required. The mappings are also created when an unknown type is used for the first
107-
/// time.
108-
/// </param>
109-
/// <param name="extraTypeMappings">
110-
/// Any extra type mappings that you wish to use for overriding the default for creating
111-
/// column definitions for SQLite DDL in the class Orm (snake in Swedish).
112-
/// </param>
113-
/// <param name="resolver">
114-
/// A contract resovler for resolving interfaces to concreate types during object creation
115-
/// </param>
116-
117-
public SQLiteConnection(string databasePath, bool storeDateTimeAsTicks = true, IBlobSerializer? serializer = null, IDictionary<string, TableMapping>? tableMappings = null, IDictionary<Type, string>? extraTypeMappings = null, IContractResolver? resolver = null)
118-
: this(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks, serializer, tableMappings, extraTypeMappings, resolver)
119-
{
120-
}
121-
12281
/// <summary>
12382
/// Create a new connection to the same database.
12483
/// </summary>
12584
/// <remarks>
12685
/// This support scenarios where a code needs to create a transaction, while leaving the current connection transactionless (ie: sharable with other codes), as a transaction creates a state in this object.
86+
///
87+
/// This is used by *All() methods.
88+
///
89+
/// Override it if you have not called the constructor with an encryption key and you database is encrypted.
12790
/// </remarks>
128-
public SQLiteConnection Clone()
129-
=> new (DatabasePath, databaseOpenFlags, StoreDateTimeAsTicks, Serializer, _tableMappings, ExtraTypeMappings, Resolver);
91+
public virtual SQLiteConnection Clone()
92+
=> new (DatabasePath, databaseOpenFlags, StoreDateTimeAsTicks, Serializer, _tableMappings, ExtraTypeMappings, Resolver, encryptionKey);
13093

13194
/// <summary>
132-
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
95+
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
13396
/// </summary>
134-
/// <param name="sqlitePlatform"></param>
135-
/// <param name="databasePath">
136-
/// Specifies the path to the database file.
137-
/// </param>
97+
/// <param name="databasePath">Specifies the path to the database file. </param>
13898
/// <param name="openFlags"></param>
13999
/// <param name="storeDateTimeAsTicks">
140-
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
141-
/// absolutely do want to store them as Ticks in all new projects. The option to set false is
142-
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
143-
/// down sides, when setting storeDateTimeAsTicks = true.
144-
/// </param>
145-
/// <param name="serializer">
146-
/// Blob serializer to use for storing undefined and complex data structures. If left null
147-
/// these types will thrown an exception as usual.
100+
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
101+
/// absolutely do want to store them as Ticks in all new projects. The option to set false is
102+
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
103+
/// down sides, when setting storeDateTimeAsTicks = true.
148104
/// </param>
105+
/// <param name="serializer">Blob serializer to use for storing undefined and complex data structures. If left null these types will thrown an exception as usual.</param>
149106
/// <param name="tableMappings">
150-
/// Exisiting table mapping that the connection can use. If its null, it creates the mappings,
151-
/// if and when required. The mappings are also created when an unknown type is used for the first
152-
/// time.
153-
/// </param>
154-
/// <param name="extraTypeMappings">
155-
/// Any extra type mappings that you wish to use for overriding the default for creating
156-
/// column definitions for SQLite DDL in the class Orm (snake in Swedish).
157-
/// </param>
158-
/// <param name="resolver">
159-
/// A contract resovler for resolving interfaces to concreate types during object creation
160-
/// </param>
161-
public SQLiteConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true, IBlobSerializer? serializer = null, IDictionary<string, TableMapping>? tableMappings = null,
162-
IDictionary<Type, string>? extraTypeMappings = null, IContractResolver? resolver = null)
107+
/// Existing table mapping that the connection can use. If its null, it creates the mappings,
108+
/// if and when required. The mappings are also created when an unknown type is used for the first time.
109+
/// </param>
110+
/// <param name="extraTypeMappings">Any extra type mappings that you wish to use for overriding the default for creating column definitions for SQLite DDL in the class Orm (snake in Swedish).</param>
111+
/// <param name="resolver">A contract resovler for resolving interfaces to concreate types during object creation</param>
112+
/// <param name="encryptionKey">When using SQL CIPHER, automatically sets the key (you won't need to override Clone() in this case)</param>
113+
public SQLiteConnection(string databasePath, SQLiteOpenFlags openFlags = SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, bool storeDateTimeAsTicks = true, IBlobSerializer? serializer = null, IDictionary<string, TableMapping>? tableMappings = null,
114+
IDictionary<Type, string>? extraTypeMappings = null, IContractResolver? resolver = null, string? encryptionKey = null)
163115
{
164116
if (string.IsNullOrEmpty(databasePath))
165117
throw new ArgumentException("Must be specified", nameof(databasePath));
@@ -172,6 +124,18 @@ public SQLiteConnection(string databasePath, SQLiteOpenFlags openFlags, bool sto
172124
Handle = handle ?? throw new NullReferenceException("Database handle is null");
173125
_open = true;
174126
databaseOpenFlags = openFlags;
127+
128+
if (!string.IsNullOrWhiteSpace(encryptionKey))
129+
{
130+
this.encryptionKey = encryptionKey!;
131+
var cipherVer = ExecuteScalar<string>("PRAGMA cipher_version");
132+
if (string.IsNullOrWhiteSpace(cipherVer))
133+
throw new Exception("This build is not using SQL CIPHER. See https://github.com/softlion/SQLite.Net-PCL2 for doc on how to setup SQL CIPHER.");
134+
135+
var o = ExecuteScalar<string>($"PRAGMA key = '{encryptionKey}';");
136+
if(o != "ok")
137+
throw new Exception("Invalid cipher key");
138+
}
175139

176140
BusyTimeout = TimeSpan.FromSeconds(0.1);
177141
Serializer = serializer;

0 commit comments

Comments
 (0)