Windows10编译pysqlcipher3 平替 SQLite,文章包括Windows10编译sqlcipher

Windows10编译pysqlcipher3来增强本地数据的安全性(替换SQLite)

本文是基于 系列文章 PyQt5+SQLAlchemy做登录注册页 的补充,并不单独放在系列文中,主要讲的是,使用 sqlcipher 来保存本地密码,这比直接使用 SQLite 更安全

关于 sqlcipher,官方介绍原文如下:

SQLCipher is a standalone fork of the SQLite database library that adds 256 bit AES encryption of database files and other security features like:

  • on-the-fly encryption
  • tamper detection
  • memory sanitization
  • strong key derivation

目录

编译安装pysqlcipher3,比较繁琐,本步骤执行下来并没有任何报错,但是由于每个人环境并不一样,所以希望也能顺利

  1. 编译适用于 Windows10 的 Python x64 的 pysqlcipher3
  2. 编译适用于 Windows10 的 Python x32 的 pysqlcipher3
  3. 测试 pysqlcipher3
  4. 在虚拟环境使用 pysqlcipher3
  5. 修改记住密码 crypto.py,改为 pysqlcipher3

64位

第1步,编译准备

  1. 安装 ActiveTcl 8.6,需要用到其中的 tclsh.exe,安装后,需要添加到系统环境变量:path=C:\ActiveTcl\bin
    image

  2. 安装Microsoft Visual Studio 2017 只安装 C++ 桌面开发,此处你安装最新版的 Visual Studio 也行,只是2017安装体积会小些
    image

  3. 安装 Win64 OpenSSL v1.1.1w(我发现此网站上已经不提供:Win64 OpenSSL v1.1.1w下载了,于是我这里分享一个网盘链供需要得下载:蓝奏云网盘分享 提取码:d0ht)
    除了安装路径,其他都选项不做修改,安装后需要添加系统环境变量:
    x64 添加OPENSSL_CONF=D:\Program Files\OpenSSL-Win64\bin\openssl.cfg
    image

  4. 对安装的OpenSSL 做一些修改,下面操作全在文件夹 D:\Program Files\OpenSSL-Win64\lib中执行
    复制 libcrypto.deflibcrypto.lib 为副本,并修改副本名称为libeay32.deflibeay32.lib
    复制 libssl.deflibssl.lib 为副本,并修改副本名称为ssleay32.defssleay32.lib
    image

  5. 复制路径 D:\Program Files\OpenSSL-Win64\include 下的openssl文件夹到D:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.39.33519\include,前一个路径是 OpenSSL 安装路径,后一个路径是Visual Studio 2017安装路径
    image


第2步,安装sqlcipher x64

  1. 下载 sqlcipher,可直接克隆,或者下载压缩包

  2. 打开 Visual Studio 的 x64工具,执行下的操作: image,执行后会在 sqlcipher文件夹中生成sqlite3.csqlite3.h

    # 切换到sqlcipher
    cd /d F:\Projects\sqlcipher
    
    # 编译
    nmake /f Makefile.msc clean
    nmake /f Makefile.msc sqlite3.c
    

    image

  3. 安装 sqlcipher(这一步可有可无,因为最后将安装pysqlcipher3来集成sqlcipher)

    # 注意修改其中的 OpenSSL 的安装路径
    cl -I"D:\Program Files\OpenSSL-Win64\include" sqlite3.c -DSQLITE_API=__declspec(dllexport) -DSQLITE_TEMP_STORE=2 -DSQLITE_HAS_CODEC /MT -link -dll -out:sqlcipher.dll -LIBPATH:"D:\Program Files\OpenSSL-Win64\lib" libeay32.lib ssleay32.lib
    

    image


第3步,安装pysqlcipher3 x64

  1. 下载pysqlcipher3,可直接克隆,或者下载压缩包。在 /pysqlcipher3 中创建文件夹 amalgamation,然后将上面中生成的sqlite3.csqlite3.h复制到 amalgamation中。

  2. 下载sqlite-amalgamation,我这里使用的是这个sqlite-amalgamation-3340100,下载解压后,复制其中的4个文件shell.c sqlite3.c sqlite.h sqliteext.h,并复制到/pysqlcipher3/src/python3/sqlcipher路径中

  3. 继续在 Visual Studio 的 x64工具,执行下的操作: image,我这里使用的是 Python3.8.10 64bit

    # 切换到 pysqlcipher3
    cd F:\Projects\pysqlcipher3
    
    python setup.py clean
    python setup.py build_amalgamation
    
    python setup.py install
    

    python setup.py build_amalgamation执行后截图
    image

    python setup.py install执行后截图
    image


32位

第1步,编译准备

  1. 安装 ActiveTcl 8.6,需要用到其中的 tclsh.exe,安装后,需要添加到系统环境变量:path=C:\ActiveTcl\bin
    image

  2. 安装Microsoft Visual Studio 2017 只安装 C++ 桌面开发,此处你安装最新版的 Visual Studio 也行,只是2017安装体积会小些
    image

  3. 安装 Win32 OpenSSL v1.1.1w(我发现此网站上已经不提供:Win32 OpenSSL v1.1.1w下载了,于是我这里分享一个网盘链供需要得下载:蓝奏云网盘分享 提取码:d0ht)
    除了安装路径,其他都选项不做修改,安装后需要添加系统环境变量:
    x32 添加OPENSSL_CONF=D:\Program Files(x86)\OpenSSL-Win32\bin\openssl.cfg
    image

  4. 对安装的OpenSSL 做一些修改,下面操作全在文件夹 D:\Program Files (x86)\OpenSSL-Win32\lib中执行
    复制 libcrypto.deflibcrypto.lib 为副本,并修改副本名称为libeay32.deflibeay32.lib
    复制 libssl.deflibssl.lib 为副本,并修改副本名称为ssleay32.defssleay32.lib
    image

  5. 复制此路径 D:\Program Files (x86)\OpenSSL-Win32\include下的openssl文件夹到D:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include,前一个路径是 OpenSSL 安装路径,后一个路径是Visual Studio 2017安装路径
    image


第2步,安装sqlcipher x32

  1. 下载 sqlcipher,可直接克隆,或者下载压缩包

  2. 打开 Visual Studio 的 x64_x86交叉工具,执行下的操作: image,执行后会在 sqlcipher文件夹中生成sqlite3.csqlite3.h

    # 切换到sqlcipher
    cd /d F:\Projects\sqlcipher
    
    # 编译
    nmake /f Makefile.msc clean
    nmake /f Makefile.msc sqlite3.c
    

    image

  3. 安装 sqlcipher(这一步可有可无,因为最后将安装pysqlcipher3来集成sqlcipher)

    # 注意修改其中的 OpenSSL 的安装路径
    cl -I"D:\Program Files (x86)\OpenSSL-Win32\include" sqlite3.c -DSQLITE_API=__declspec(dllexport) -DSQLITE_TEMP_STORE=2 -DSQLITE_HAS_CODEC /MT -link -dll -out:sqlcipher.dll -LIBPATH:"D:\Program Files (x86)\OpenSSL-Win32\lib" libeay32.lib ssleay32.lib
    

    image


第3步,安装pysqlcipher3 x32

  1. 下载pysqlcipher3,可直接克隆,或者下载压缩包,在 /pysqlcipher3 中创建文件夹 amalgamation,然后将上面生成的sqlite3.csqlite3.h复制到 amalgamation中。

  2. 下载sqlite-amalgamation,我这里使用的是这个sqlite-amalgamation-3340100,下载解压后,复制其中的4个文件shell.c sqlite3.c sqlite.h sqliteext.h,复制到/pysqlcipher3/src/python3/sqlcipher

  3. 打开 Visual Studio 的 x64_x86交叉工具,执行下的操作: image,我这里使用的是Python3.8.10 32bit

    # 切换到 pysqlcipher3
    cd F:\Projects\pysqlcipher3
    
    python setup.py clean
    python setup.py build_amalgamation
    
    python setup.py install
    

    python setup.py build_amalgamation执行后截图
    image

    python setup.py install执行后截图
    image


测试安装

使用下列代码测试

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@ File        : test.py
@ Version     : V1.0.0
@ Description :
"""
from pysqlcipher3 import dbapi2 as sqlite

conn1 = sqlite.connect("test.db")
c1 = conn1.cursor()
c1.execute("PRAGMA key='123456'")
c1.execute("""create table stocks (date text, trans text, symbol text, qty real, price real)""")
c1.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")
conn1.commit()
c1.close()

conn2 = sqlite.connect("test.db")
c2 = conn2.cursor()
c2.execute("PRAGMA key='123456'")
print(c2.execute("""select * from stocks""").fetchall())
c2.close()

使用最新版本的DB.Browser.for.SQLite 3.12.2查看
image

image


虚拟环境使用

若需要在虚拟环境中使用pysqlcipher3,则需要在已安装的系统环境中的Lib\site-packages目录下,复制下面两个,到虚拟环境 venv\Lib\site-packages 目录下

  • 文件夹: pysqlcipher3-1.2.1-py3.8-win32.egg
  • 文件:easy-install.pth

修改替换

修改crypto.py,将 sqlite3 替换为 pysqlcipher3,GitHUb源码见这里

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@ Project     : QtLoginRegistration
@ File        : crypto_sqlcipher.py
@ Author      : yqbao
@ Version     : V1.0.0
@ Description : 将 sqlite3 替换为 pysqlcipher3,实现密码访问
                pysqlcipher3 实现密码访问 SQLite,需要手动安装
                安装看这里:https://www.cnblogs.com/yqbaowo/p/18043628
"""
from os import getenv

from pysqlcipher3 import dbapi2 as sqlite3
import win32crypt

db_password = getenv('DB_PASSWORD')  # 读取环境变量,数据库密码


def crypto(password):
    encrypt = win32crypt.CryptProtectData(password.encode('utf-8'))
    return encrypt


def create_db(db, table):
    conn = sqlite3.connect(db)
    cursor = conn.cursor()
    cursor.execute(f"PRAGMA key='{db_password}'")  # 密码
    try:
        cursor.execute(f'CREATE TABLE {table} (username text , password text)')
        conn.commit()
    except sqlite3.OperationalError:
        pass
    conn.close()


def insert_db(db, table, username, password):
    conn = sqlite3.connect(db)
    cursor = conn.cursor()
    cursor.execute(f"PRAGMA key='{db_password}'")  # 密码
    encrypt = crypto(password)
    cursor.execute(f"INSERT INTO {table}(username,password) VALUES(?,?)", (username, encrypt))
    conn.commit()
    conn.close()


def delete_db(db, table):
    conn = sqlite3.connect(db)
    cursor = conn.cursor()
    cursor.execute(f"PRAGMA key='{db_password}'")  # 密码
    cursor.execute(f"DELETE FROM {table}")
    conn.commit()
    conn.close()


def decrypt(db, table):
    conn = sqlite3.connect(db)
    cursor = conn.cursor()
    cursor.execute(f"PRAGMA key='{db_password}'")  # 密码
    cursor.execute(f"SELECT * FROM {table}")
    result = cursor.fetchall()[-1]
    username = result[0]
    password = win32crypt.CryptUnprotectData(result[1])[-1]
    password = password.decode('utf-8')
    return username, password


if __name__ == '__main__':
    db_ = 'test.db'
    table_ = 'test'
    create_db(db_, table_)
    delete_db(db_, table_)
    insert_db(db_, table_, 'test', '111111')
    print(decrypt(db_, table_))

效果如下:
image

参考文章

Install pysqlcipher3 windows
编译Windows 64bit平台pysqlcipher3 for Python3.7

本文章的原文地址
GitHub主页

posted @ 2024-03-18 16:19  星尘的博客  阅读(620)  评论(0编辑  收藏  举报