让unidac支持加密的sqlite

sqlite是一款优秀的单文件数据库软件,只需一个dll就就完全包含数据库引擎的功能,而且可以嵌入至其它程序中,完全不用额外的设定。其特性如下:
* 支持ACID (Atomic, Consistent, Isolated, Durable) 交易。
* 零组态设定(Zero-configuration),无须管理者的设定及管理。
* 支持大部分SQL92的语法。
* 数据库存在于一个单一的文件中。
* 数据库系统所在机器的字节顺序(Byte order)无关。
* 支援大小至2 TB (2^41 bytes)。
* 极小的内存需求:小于3万行的C语言程序代码。小于250KB的程序空间。
* 大部分的数据库操作皆快于一般流行的数据库系统。
* 简单易用的API。
* 支援TCL。也有其它语言的支持可用。
* 注释详细的程序代码,以及超过90%的测试。
* 链接库自己包含完整的功能,无须其它额外的程序或链接库。
* 程序代码版权为public domain。任何用途皆可免费使用。

不过sqlite开源版是不支持加密的,只留有接口,没有进行实现,不过开源界从来不缺乏雷锋,于是有了wxsqlite工程,wxsqlite是 sqlite的wxWidgets c++实现接口,顺便用aes加密算法实现了sqlite的加密功能,与sqlite 100%兼容,实在是赞!

我常用的数据库连接组件是unidac,最新的3.x版本已经支持sqlite,不过也没有实现加密函数定义,于是自已动手帮它加上,我用的版本是3.0.0.6。

\UniProviders\SQLite\LiteCallUni.pas是调用接口定义

// functions下面加上以下代码:

_sqlite3_key = function(
    pDb: Tsqlite3;          // Database handle
    pKey: PAnsiChar;        // Database PassWord (UTF-8)
    nKey: Integer           // Database sizeofpassword
  ): integer; {$IFNDEF CLR}cdecl;{$ENDIF}

  _sqlite3_rekey = function(//If the current database is not encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the database is decrypted.
    pDb: Tsqlite3;          // Database handle
    pNew: PAnsiChar;        // Database New PassWord (UTF-8)
    nNew: Integer           // Database sizeofnewpassword 
  ): integer; {$IFNDEF CLR}cdecl;{$ENDIF}
...........................

var 下面加

  sqlite3_key: _sqlite3_key;
  sqlite3_rekey: _sqlite3_rekey;
........................................

procedure InitFunctions;
begin
{$IFDEF CLR}下面加
  sqlite3_key := {$IFNDEF UNIDACPRO}LiteCallCLR{$ELSE}LiteCallCLRUni{$ENDIF}.sqlite3_key;
  sqlite3_rekey := {$IFNDEF UNIDACPRO}LiteCallCLR{$ELSE}LiteCallCLRUni{$ENDIF}.sqlite3_rekey;
...................

{$ELSE}下面加
  sqlite3_key := GetProc('sqlite3_key');
  sqlite3_rekey := GetProc('sqlite3_rekey');

..................................

initialization
  LockInit := TCriticalSection.Create;

{$IFNDEF CLR}下面加
  sqlite3_key := @NotLink;
  sqlite3_rekey := @NotLink;

..................................

\UniProviders\SQLite\LiteClassesUni.pas是引擎调用接口实现

      Check(sqlite3_open(PAnsiChar(UTF8Encode(FDatabase)), FSQLite));
     下面加:

      if Pos('ChangePassword',FUsername)=1 then
      begin
        if Copy(FUsername,16,Length(FUsername))<>'' then
          SQLite3_key(FSQLite,PAnsiChar(Copy(FUsername,16,Length(FUsername))),SizeOf(FUsername));
        if FPassword<>'' then
          SQLite3_rekey(FSQLite,PAnsiChar(FPassword),SizeOf(FPassword));
      end
      else if FUsername='ClearPassword' then
      begin
        if FPassword<>'' then
          SQLite3_key(FSQLite,PAnsiChar(FPassword),SizeOf(FPassword));
        SQLite3_rekey(FSQLite,0,0);
      end
      else
      if FPassword<>'' then
         Check(SQLite3_key(FSQLite,PAnsiChar(FPassword),SizeOf(FPassword)));


 

测试加密,解密正常。


发表评论

您的电子邮箱地址不会被公开。

70 − 64 =