SQLCipher for .NET

Commercial & Enterprise Edition Feature

SQLCipher for .NET encompasses a set of packages that provide full database encryption for Microsoft .NET targets on Windows, iOS, Android, and macOS, and Linux. These libraries support .NET Core, Maui, .NET Framework, and .NET standard, making it quick and easy to integrate SQLCipher's AES-256 full database encryption into any application. They are fully interoperable with other SQLCipher platform libraries. No special knowledge of cryptography is required, and the libraries support popular data access APIs including:

  • A sqlite-net compatible package based on the official praeclarum/sqlite-net library
  • Microsoft Entity Framework via Microsoft.EntityFrameworkCore.Sqlite.Core
  • Microsoft's ADO.NET implementation via Microsoft.Data.Sqlite.Core

SQLCipher takes care of data security behind the scenes with a small footprint and great performance that makes it well suited for protecting application databases on mobile platforms. SQLCipher .NET packages are exclusively available through our Commercial Edition licensing via the link below or through the SQLCipher Enterprise program.

Buy SQLCipher for .NET Packages Now »

SQLCipher for supported .NET platforms are delivered directly via NuGet packages that may be installed from a local NuGet project source.

🔥 Before using the package(s) be sure to remove any prior references in your project to:
  • Legacy SQLCipher .nupkg or .xam packages
  • Any previous SQLite-based NuGet or assembly references, e.g. sqlite-net-pcl, Microsoft.EntityFrameworkCore.Sqlite, Microsoft.Data.Sqlite, etc.

There are several ways to setup local NuGet repositories, including file shares, global Visual Studio settings, and even running a NuGet web repository. However, one simple, flexible, and recommended approach is to store the SQLCipher NuGet packages alongside the project itself. This approach ensures that the dependencies are stored in version control alongside the application, that the packages are instantly available to all developers and build tools, and that the dependencies can be fulfilled even offline. Note that this approach works both with Visual Studio for Windows or Mac, though the former is used here for demonstration purposes.

Start by copying the appropriate .nupkg filesinto a folder under the root of the application. It is even possible to place the package(s) in the top level folder of the application sources itself alongside the Solution (.sln) file. Next, create a simple nuget.config file in the same directory as the .sln and .nupkg files, that points a package source to the directory where the .nupkg file(s) are located.

nuget.config file and package in solution folder

In the following example, the the package source points to the current directory where the nuget.config and .sln file are located:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="Local" value="." />
  </packageSources>
</configuration>

Finally, in Visual Studio, add the nuget.config file at the solution level, save the solution, and restart the IDE.

add nuget.config file to solution

The nuget.config should now show up as a Solution Item.

nuget.config file as a solution item

Once the NuGet configuration is complete you will be able bring up the NuGet package manager and select the Local source to install the appropriate SQLCipher package at the project level. SQLCipher packages should be installed to the executable / Application project. For example, consider a non-Maui multi-target Solution that includes a separate iOS application, Android application, and Windows UWP application that use a shared data access project. In this case, the platform-specific SQLCipher packages zetetic-sqlcipher-ios, zetetic-sqlcipher-android, zetetic-sqlcipher-windows or zetetic-sqlcipher-windows-uwp should be each be installed to the respective application project. Note that the platform-specific SQLCipher packages should __not__ be installed added as dependencies to shared class library projects (because they are not platform specific the requisite native components will not be applied if the dependency is added there).

add nuget package to project

To ensure that the SQLCipher package appropriate for you platform is used, add the following early in your application's startup lifecycle code:

SQLitePCL.Batteries_V2.Init();

For iOS, it is important to ensure that the linker does not operate on the packaged assemblies. The easiest and recommended way do this is to set the project Linker Behavior to either Link SDK assemblies only or Don't Link. Using Link all assemblies can result in runtime failure. If you use Link all assemblies for the smallest possible executable size, then configure a linker description file to exclude all SQLCipher assemblies from linking. You will also need to call one additional method, SQLitePCL.lib.embedded.Init(), to instruct the linker to properly bundle SQLCipher, i.e.

SQLitePCL.lib.embedded.Init(); /* required on iOS to link SQLCipher library */
SQLitePCL.Batteries_V2.Init();

When deploying and debugging using Visual Studio on Windows, it is important to not use the "Hot Restart" feature. This can either be disabled entirely under Tools, Options, Xamarin, iOS Settings or implicitly by using Remote deployment to a device connected to your macOS build machine.

Windows projects using SQLCipher UWP (zetetic-sqlcipher-windows-uwp) outside of a UWP application container package should:

  • Add the zetetic-sqlcipher-windows-vcrtforwarders NuGet package to ensure that the proper runtime dependencies are available to SQLCipher. Failure to do so may result in the following exception message: Unable to load DLL 'sqlcipher' or one of its dependencies: The specified module could not be found. (0x8007007E).
  • Ensure that the Microsoft Visual C++ Redistributable package on the target environment. When packaging using a .appxmanifest the following can be added to the <Dependencies/> section to ensure the required runtime is available:
        <PackageDependency Name="Microsoft.VCLibs.140.00.UWPDesktop" MinVersion="14.0.24217.0" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" />
                
    For other installation methods the latest downloads are available from Microsoft.

For Windows projects using the UWP package (zetetic-sqlcipher-windows-uwp) inside a UWP application container, the SQLitePCLRaw 2.x version used in recent releases no longer calls sqlite3_win32_set_directory() automatically. Thus you may need to add the following to your application initialization

var rc = SQLitePCL.raw.sqlite3_win32_set_directory(
  1, // data
  Windows.Storage.ApplicationData.Current.LocalFolder.Path
);

rc = SQLitePCL.raw.sqlite3_win32_set_directory(
  2, // temp
  Windows.Storage.ApplicationData.Current.TemporaryFolder.Path
);

Microsoft AppCenter provides a popular set of tools that enable crash reporting, application analytics, and other features for integrating applications. Due to the design of AppCenter, it brings in several transitive NuGet dependencies that include assets that conflict with SQLCipher packages. As such, we recommend including the following explicit PackageReference statements in any project file that includes AppCenter.

<PackageReference Include="sqlite-net-pcl">
  <Version>*</Version>
  <ExcludeAssets>All</ExcludeAssets>
</PackageReference>
<PackageReference Include="SQLitePCLRaw.bundle_green">
  <Version>*</Version>
  <ExcludeAssets>All</ExcludeAssets>
</PackageReference>
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3">
  <Version>*</Version>
  <ExcludeAssets>All</ExcludeAssets>
</PackageReference>

A similar technique can be used to resolve conflicts with any other package that include a dependency on sqlite-net-pcl or any non-Zetetic SQLitePCLRaw bundles.

Once the appropriate project-specific packages are installed you can choose the desired client libraries for accessing databases. SQLCipher supports multiple APIs for accessing data: sqlite-net, Entity Framework, and ADO.NET. Details on each integration approach are included here.

SQLCipher ships with a sqlite-net compatible package based on the official praeclarum/sqlite-net library. To use this interface, make sure that zetetic-sqlite-net-base-X.X.X.nupkg is present in the local NuGet repository and install it to the project.

Note: Do not install the publicly available sqlite-net-pcl NuGet package because it will bring in a native library dependency that will conflict with SQLCipher. If you want to use the latest version of sqlite-net it is permissible to use sqlite-net-base package instead.

Example

The following example provides an abbreviated code sample for using SQLCipher via the sqlite-net API, where the key material is passed to the constructor. Note that a fully functional referece application is included with each SQLCipher package to demonstrate library usage.

using SQLite;

...

public class Model
{
  [PrimaryKey,AutoIncrement]
  public int Id { get; set; }
  public string Content { get; set; }
}

...

var conn = new SQLiteConnection(new SQLiteConnectionString(filename, true, password));

// When using Commercial or Enterprise packages you must call PRAGMA cipher_license with a valid License Code.
// Failure to provide a license code will result in an SQLITE_AUTH(23) error.
// Trial licenses are available at https://www.zetetic.net/sqlcipher/trial/
conn.ExecuteScalar<int>(String.Format("PRAGMA cipher_license = '{0}';", "YOUR LICENSE CODE HERE"));
conn.CreateTable<Model>();

...

// use SQLiteConnection

SQLCipher supports the use of Microsoft Entity Framework Core.

NuGet Package Requirements

To integrate Microsoft.EntityFrameworkCore.Sqlite.Core, configure the following Nuget packages:

  1. Microsoft.EntityFrameworkCore.Sqlite.Core
  2. platform-specific SQLCipher packages
  3. ensure that there are no references to zetetic-sqlite-net-base package

Note: Do not install the Microsoft.EntityFrameworkCore.Sqlite package because it will bring in a native library dependency which will conflict with SQLCipher. Only install Microsoft's *.Core variant, Microsoft.EntityFrameworkCore.Sqlite.Core.

Example

The following example provides an abbreviated code sample for using Microsoft Entity Framework Core where the key material is passed to via PRAGMA. Note that a fully functional referece application is included with each SQLCipher package to demonstrate library usage.

using Microsoft.EntityFrameworkCore;

...

public class Model
{
  [PrimaryKey,AutoIncrement]
  public int Id { get; set; }
  public string Content { get; set; }
}

...


public class SQLCipherDbContext : DbContext
{
    public string Filename {get; set;}
    public DbSet<Model> Records { get; set; }

    public SQLCipherDbContext(string filename)
    {
        Filename = filename;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite($"Filename={Filename}");
    }
}

...

context = new SQLCipherDbContext(filename);

var connection = context.Database.GetDbConnection();
connection.Open();
using (var command = connection.CreateCommand())
{
    command.CommandText = $"PRAGMA key = '{password}';";
    command.ExecuteNonQuery();
}

using (var command = connection.CreateCommand())
{
    // When using Commercial or Enterprise packages you must call PRAGMA cipher_license with a valid License Code.
    // Failure to provide a license code will result in an SQLITE_AUTH(23) error.
    // Trial licenses are available at https://www.zetetic.net/sqlcipher/trial/
    command.CommandText = $"PRAGMA cipher_license = 'YOUR LICENSE CODE HERE';";
    command.ExecuteNonQuery();
}

context.Database.EnsureCreated();

...

// use context

SQLCipher supports ADO.NET via the Microsoft.Data.Sqlite.Core library. To use this interface, add a NuGet dependency on Microsoft.Data.Sqlite.Core.

NuGet Package Requirements

To integrate Microsoft.EntityFrameworkCore.Sqlite.Core, configure the following Nuget packages:

  1. Microsoft.Data.Sqlite.Core
  2. platform-specific SQLCipher packages
  3. ensure that there are no references to zetetic-sqlite-net-base package

Note: Do not install the Microsoft.Data.Sqlite package because it will bring in a native library dependency which will conflict with SQLCipher. Only install Microsoft's *.Core variant, Microsoft.Data.Sqlite.Core.

Example

The following example provides an abbreviated code sample for using the ADO.NET Adapter where the key material is passed to via PRAGMA. Note that a fully functional referece application is included with each SQLCipher package to demonstrate library usage.

using Microsoft.Data.Sqlite;
using System.Data;

...

connection = (IDbConnection)new SqliteConnection($"Data Source={filename}");
connection.Open();

using (var command = _connection.CreateCommand())
{
    command.CommandText = $"PRAGMA key = '{password}';";
    command.ExecuteNonQuery();
}

using (var command = _connection.CreateCommand())
{
    // When using Commercial or Enterprise packages you must call PRAGMA cipher_license with a valid License Code.
    // Failure to provide a license code will result in an SQLITE_AUTH(23) error.
    // Trial licenses are available at https://www.zetetic.net/sqlcipher/trial/
    command.CommandText = $"PRAGMA cipher_license = 'YOUR LICENSE CODE HERE';";
    command.ExecuteNonQuery();
}

using (var command = _connection.CreateCommand())
{
    command.CommandText = "CREATE TABLE IF NOT EXISTS Model(id, a,b);";
    command.ExecuteNonQuery();
}

...

// use connection

Applications that are simultaneously targeting multiple platforms (e.g. iOS and Android, Windows, etc.), can place shared data access code in a separate project that depends on the appropriate data access library. Then install the SQLCipher platform NuGet package(s) and the data access library at the platform-specific project level.

If you have addition comments or questions please contact us.

Buy SQLCipher for .NET Packages Now »