一、 sqlCipher介绍
sqlCipher是一个开源的软件,它提供的sqlite数据库的透明加密,在数据页被写入之前加密存储和读取解密,基于256-bit AES加密。
目前支持的平台有C/C++,Obj-C,QT,Win32/.NET,Java,Python,Ruby,Linux,Mac OS X,iPhone/iOS,Android,Xamarin.iOS,和Xamarin.Android。
二、 编译安装
1.安装openssl加密库
sudo apt-get install openssl
sudo apt-get install libssl-dev
2.安装tclsh
sudo apt-get install tclsh
3.下载安装sqlCipher
下载地址:https://github.com/sqlcipher/sqlcipher
3.1修改源文件
#define sqlITE_LIMIT_WORKER_THREADS 11
3.2执行configure
./configure --enable-tempstore=yes CFLAGS="-DsqlITE_HAS_CODEC" LDFLAGS="-lcrypto" CXXFLAGS=-fPIC
3.3.编译源文件
make
4.测试
5.sqlcipher使用demo
/* gcc c_demo.c -o demo -lsqlcipher */
#include "sqlite3.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(X)
static int callback(void *NotUsed,int argc,char **argv,char **col_name)
{
int i;
for(i=0; i<argc; i++)
{
printf("%s\n",argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc,char *argv[])
{
sqlite3 *db;
const char *file= "test.db";
const char *key = "123456";//key为使用sqlcipher设置的密码
if (sqlite3_open(file,&db) == sqlITE_OK)
{
int rc;
if(db == NULL)
{
ERROR(("sqlite3_open reported OK,but db is null,retrying open %s\n",sqlite3_errmsg(db)))
}
//验证密码是否正确
if(sqlite3_key(db,key,strlen(key)) != sqlITE_OK)
{
ERROR(("error setting key %s\n",sqlite3_errmsg(db)))
exit(-1);
}
//sqllite 操作代码...
char* sql1 = "create table if not exists test(int id,varchar name);";
char* sql2 = "insert into test values(1,'hello');";
char* sql3 = "select * from test;";
char* err_msg = NULL;
rc = sqlite3_exec(db,sql1,callback,0,&err_msg);
if( rc!=sqlITE_OK )
{
fprintf(stderr,"sql error: %s\n",err_msg);
sqlite3_free(err_msg);
err_msg = NULL;
}
rc = sqlite3_exec(db,sql2,&err_msg);
if( rc!=sqlITE_OK )
{
fprintf(stderr,err_msg);
sqlite3_free(err_msg);
err_msg = NULL;
}
rc = sqlite3_exec(db,sql3,err_msg);
sqlite3_free(err_msg);
err_msg = NULL;
}
sqlite3_close(db);
}
}