1 下载安装DB Browser for SQLite
下载,该工具可以打开程序创建的加密数据库,方便我们调试和检查。
2 通过vcpkg安装原版的sqlcipher
vcpkg search openssl
vcpkg install openssl --triplet=x64-windows
vcpkg search sqlcipher
vcpkg install sqlcipher --triplet=x64-windows
3 安装qsqlcipher-qt5
注意:为确保程序的可靠性,不要使用qsqlcipher-qt5源文件中的sqlcipher(qsqlcipher-qt5\3rdparty目录),使用通过vcpkg安装的sqlcipher。
git clone https://github.com/sjemens/qsqlcipher-qt5.git
修改qsqlcipher-qt5\qsqlcipher\qsqlcipher.pro中的!system-sqlcipher节点
修改前
system-sqlcipher {
CONFIG += link_pkgconfig
PKGCONFIG += sqlcipher
# or if pkg-config is not available
# INCLUDEPATH += /path/to/include/sqlcipher
# LIBS += -L/path/to/lib/ -lsqlcipher -lcrypto
} else {
include($$PWD/../3rdparty/sqlcipher.pri)
}
修改后
system-sqlcipher {
#CONFIG += link_pkgconfig
#PKGCONFIG += sqlcipher
# or if pkg-config is not available
# 注意E:/tools/vcpkg/installed/x64-windows/include改为您的vcpkg安装目录
INCLUDEPATH += E:/tools/vcpkg/installed/x64-windows/include
LIBS += -LE:/tools/vcpkg/installed/x64-windows/lib -lsqlcipher -llibcrypto
} else {
include($$PWD/../3rdparty/sqlcipher.pri)
}
- 在开始编译之前必须设置qt的环境变量;
- 命令在“开始-》Visual Studio 2019-》x64 Native Tools Command Prompt for VS 2019”中执行。
cd qsqlcipher-qt5
mkdir -p build && cd build
#表示使用系统自带的sqlcipher
qmake ../qsqlcipher.pro CONFIG+=system-sqlcipher
nmake
#自动安装至qmake对应的库所在的位置
#本例中QT位置为E:\Qt,版本5.15.1,安装了msvc2019 X64所需的库
#因此qmake位置为E:\Qt\5.15.1\msvc2019_64\bin
#对应的安装位置为E:\Qt\5.15.1\msvc2019_64\plugins\sqldrivers\qsqlcipher.dll和E:\Qt\5.15.1\msvc2019_64\plugins\sqldrivers\qsqlcipherd.dll
nmake install
5 使用qsqlcipher
在执行任何操作之前先设置密码
void TestQSqlCipher::createDbWithPassphrase()
{
QSqlQuery q(QSqlDatabase::database("db"));
QStringList queries;
// PRAGMA key='foobar'中的foobar就是密码,然后再执行您的sql
queries << "PRAGMA key='foobar'"
<< "create table foo(bar integer)"
<< "insert into foo values (42)";
for(const QString& qs : queries)
{
QVERIFY2(q.exec(qs), q.lastError().text().toLatin1().constData());
}
}
编译成功运行前要先将vcpkg中的libcrypto-1_1-x64.dll和sqlcipher.dll复制至exe所在目录.
copy E:\tools\vcpkg\installed\x64-windows\bin\sqlcipher.dll D:\MyWork\202109\test\build\Release /Y
copy E:\tools\vcpkg\installed\x64-windows\bin\libcrypto-1_1-x64.dll D:\MyWork\202109\test\build\Release /Y