Skip to content

Commit

Permalink
Microsoft.Data.Sqlite: Don't force decryption when password unset
Browse files Browse the repository at this point in the history
  • Loading branch information
bricelam committed Nov 12, 2020
1 parent 53d6d02 commit 4402dee
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
10 changes: 5 additions & 5 deletions src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,12 +256,12 @@ public override void Open()
"SELECT quote($password);",
new SqliteParameter("$password", ConnectionOptions.Password));
this.ExecuteNonQuery("PRAGMA key = " + quotedPassword + ";");
}

if (SQLitePCLExtensions.EncryptionSupported() != false)
{
// NB: Forces decryption. Throws when the key is incorrect.
this.ExecuteNonQuery("SELECT COUNT(*) FROM sqlite_master;");
if (SQLitePCLExtensions.EncryptionSupported() != false)
{
// NB: Forces decryption. Throws when the key is incorrect.
this.ExecuteNonQuery("SELECT COUNT(*) FROM sqlite_master;");
}
}

if (ConnectionOptions.ForeignKeys.HasValue)
Expand Down
29 changes: 26 additions & 3 deletions test/Microsoft.Data.Sqlite.Tests/SqliteConnectionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Data.Sqlite.Properties;
using Microsoft.Data.Sqlite.Utilities;
using Xunit;
using static SQLitePCL.raw;

Expand Down Expand Up @@ -314,7 +312,7 @@ private void Open_works_when_password_supported()
// NB: The file is only encrypted after writing
connection1.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS dual (dummy)");

using (var connection2 = new SqliteConnection("Data Source=encrypted.db"))
using (var connection2 = new SqliteConnection("Data Source=encrypted.db;Password=wrong"))
{
var stateChangeRaised = false;
connection2.StateChange += (sender, e) => stateChangeRaised = true;
Expand All @@ -334,6 +332,31 @@ private void Open_works_when_password_might_be_supported()
connection.Open();
}

#if E_SQLCIPHER || SQLCIPHER
[Fact]
public void Open_decrypts_lazily_when_no_password()
{
using (var connection1 = new SqliteConnection("Data Source=encrypted.db;Password=password"))
{
connection1.Open();

// NB: The file is only encrypted after writing
connection1.ExecuteNonQuery(
"CREATE TABLE IF NOT EXISTS data (value); INSERT INTO data (value) VALUES (1);");

using (var connection2 = new SqliteConnection("Data Source=encrypted.db"))
{
connection2.Open();
connection2.ExecuteNonQuery("PRAGMA key = 'password';");

var value = connection2.ExecuteScalar<long>("SELECT value FROM data;");

Assert.Equal(1L, value);
}
}
}
#endif

[Theory]
[InlineData("True", 1L)]
[InlineData("False", 0L)]
Expand Down

0 comments on commit 4402dee

Please sign in to comment.