├── index.js ├── src ├── nodejs │ ├── QueryJob.h │ ├── ExcuteJob.h │ ├── NodeFunction.h │ ├── ConnJob.h │ ├── Sqlite3Client.h │ ├── Statement.h │ ├── NodeFunction.cpp │ ├── Sqlite3Connection.h │ ├── QueryJob.cc │ ├── Statement.cpp │ ├── Sqlite3Client.cpp │ └── Sqlite3Connection.cpp ├── sqlite3_encrypt │ ├── DbSqlite.h │ ├── DbSqlite.cpp │ ├── sqlite3 │ │ ├── crypt.c │ │ ├── crypt.h │ │ ├── sqlite3.c │ │ ├── sqlite3secure.c │ │ ├── codec.h │ │ ├── sha2.h │ │ ├── rijndael.h │ │ ├── codecext.c │ │ ├── codec.c │ │ ├── sqlite3ext.h │ │ └── sha2.c │ ├── platform_config.h │ └── sqlite3_def.h └── third_party │ └── CodingConv │ ├── encodeutil.cpp │ └── encodeutil.h ├── README.md ├── test ├── jiami.js ├── tran.js ├── excute.js └── query.js ├── package.json ├── lib ├── node-sqlite.js ├── statment.js └── connection.js └── binding.gyp /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./lib/node-sqlite.js'); -------------------------------------------------------------------------------- /src/nodejs/QueryJob.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/nodejs/QueryJob.h -------------------------------------------------------------------------------- /src/nodejs/ExcuteJob.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/nodejs/ExcuteJob.h -------------------------------------------------------------------------------- /src/sqlite3_encrypt/DbSqlite.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/sqlite3_encrypt/DbSqlite.h -------------------------------------------------------------------------------- /src/sqlite3_encrypt/DbSqlite.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/sqlite3_encrypt/DbSqlite.cpp -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/crypt.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/sqlite3_encrypt/sqlite3/crypt.c -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/crypt.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/sqlite3_encrypt/sqlite3/crypt.h -------------------------------------------------------------------------------- /src/sqlite3_encrypt/platform_config.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/sqlite3_encrypt/platform_config.h -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/sqlite3.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/sqlite3_encrypt/sqlite3/sqlite3.c -------------------------------------------------------------------------------- /src/third_party/CodingConv/encodeutil.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhs077/node-sqlite3/HEAD/src/third_party/CodingConv/encodeutil.cpp -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | node-sqlite3 2 | =========== 3 | 4 | nodejs sqlite3驱动 5 | 支持linux windows 6 | windows sqlite3编码为UNICODE,linux 为UTF-8编码。 7 | 8 | npm install node-sqlite3 9 | -------------------------------------------------------------------------------- /test/jiami.js: -------------------------------------------------------------------------------- 1 | var sqlite3 = require('../'); 2 | var ret; 3 | ret = sqlite3.open("test.db",function(err,conn){ 4 | if(err){ 5 | console.log('err'+err); 6 | } 7 | else{ 8 | //加密一个数据库 9 | //conn.changekey('zhs'); 10 | //访问一个加密到数据库 11 | //conn.enterkey('zhs'); 12 | //删除密码 13 | conn.enterkey('zhs'); 14 | conn.delkey(); 15 | conn.query("select * from stu where id=1",function(err,state){ 16 | if(err) console.log(err); 17 | }) 18 | 19 | 20 | 21 | } 22 | }); 23 | -------------------------------------------------------------------------------- /src/nodejs/NodeFunction.h: -------------------------------------------------------------------------------- 1 | #ifndef _NODE_FUNCTION_H_ 2 | #define _NODE_FUNCTION_H_ 3 | #include 4 | #include 5 | using namespace v8; 6 | using namespace node; 7 | #include"../../sqlite3_encrypt/platform_config.h" 8 | #include "../../third_party/CodingConv/encodeutil.h" 9 | namespace NodeFunc 10 | { 11 | const char* ToCString(const String::Utf8Value& value); 12 | TSTRING Replace( const TSTRING& orignStr, const TSTRING& oldStr, const vector&vc ); 13 | TSTRING MergeSql(const Arguments&args); 14 | }; 15 | #endif 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-sqlite3", 3 | "version": "0.0.2", 4 | "description": "nodejs sqlite3", 5 | "main": "index.js", 6 | "directories": { 7 | "test": "test" 8 | }, 9 | "scripts": { 10 | "test": "nodeunit test", 11 | "install": "node-gyp rebuild" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/zhs077/node-sqlite3" 16 | }, 17 | "keywords": [ 18 | "sqlite3" 19 | ], 20 | "author": "zhenghuashan", 21 | "license": "BSD-2-Clause", 22 | "gypfile": true, 23 | "bugs": { 24 | "url": "https://github.com/zhs077/node-sqlite3/issues" 25 | }, 26 | "homepage": "https://github.com/zhs077/node-sqlite3" 27 | } 28 | -------------------------------------------------------------------------------- /src/nodejs/ConnJob.h: -------------------------------------------------------------------------------- 1 | #ifndef _CONN_JOB_ 2 | #define _CONN_JOB_ 3 | #include "DbSqlite.h" 4 | #include "Sqlite3Client.h" 5 | #include 6 | #include 7 | using namespace v8; 8 | class ConnJob 9 | { 10 | public: 11 | ConnJob(void) 12 | { 13 | pClient = NULL; 14 | //error = NULL; 15 | error.clear(); 16 | pConnect = NULL; 17 | } 18 | ~ConnJob(void){} 19 | public: 20 | //string strDblink; 21 | //string strUserName; 22 | //string strPwd; 23 | TSTRING path; 24 | Persistentjs_obj; 25 | Sqlite3Client* pClient; 26 | //const char* error; 27 | TSTRING error; 28 | CSqliteConn* pConnect; 29 | 30 | uv_work_t req; 31 | uv_async_t main_async; 32 | 33 | }; 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /lib/node-sqlite.js: -------------------------------------------------------------------------------- 1 | var node_sqlite3 = require('../build/Release/node_sqlite3.node'); 2 | var sqlite3 = new node_sqlite3.Sqlite3Client(); 3 | var Connection = require('./connection'); 4 | 5 | 6 | //callback (err,conn) 7 | exports.open = function(path,callback){ 8 | sqlite3.open(path,function(err,conn_){ 9 | if(err){ 10 | callback(err,null) 11 | } 12 | else{ 13 | var conn = new Connection(conn_) 14 | callback(null,conn); 15 | } 16 | }); 17 | 18 | 19 | }; 20 | 21 | //同步方法 22 | exports.openSync = function (path){ 23 | var conn = sqlite3.openSync(path); 24 | if (conn == null){ 25 | throw "cannot open sqlite3 please check path"; 26 | }else{ 27 | return new Connection(conn); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | 'targets': [ 3 | { 4 | 'target_name': 'node_sqlite3', 5 | 'sources': [ 6 | 'src/third_party/CodingConv/encodeutil.cpp','src/nodejs/Sqlite3Client.cpp' 7 | ,'src/nodejs/Sqlite3Connection.cpp','src/nodejs/QueryJob.cc','src/nodejs/Statement.cpp','src/nodejs/NodeFunction.cpp', 8 | 'src/sqlite3_encrypt/DbSqlite.cpp','src/sqlite3_encrypt/sqlite3/sqlite3secure.c' 9 | ], 10 | 'conditions':[ 11 | ["OS=='win'",{ 12 | 'defines': ['UNICODE'] 13 | 14 | } 15 | ] 16 | 17 | ], 18 | 'include_dirs':[ 19 | 'src/sqlite3_encrypt' 20 | ,'src/third_party/CodingConv' 21 | 22 | ], 23 | 24 | 'cflags':['-fexceptions'], 25 | 'cflags_cc':['-fexceptions'] 26 | 27 | 28 | 29 | } 30 | ] 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/nodejs/Sqlite3Client.h: -------------------------------------------------------------------------------- 1 | #ifndef _ORACLE_BINDINGS_ 2 | #define _ORACLE_BINDINGS_ 3 | 4 | #include 5 | #include 6 | using namespace node; 7 | using namespace v8; 8 | 9 | 10 | 11 | class Sqlite3Client : public ObjectWrap 12 | { 13 | public: 14 | static void Init(Handle target); 15 | static HandleNew(const Arguments& args); 16 | static HandleOpen(const Arguments& args); 17 | static HandleIsOpen(const Arguments& args); 18 | static void EIO_Open(uv_work_t* req); 19 | static void EIO_AfterOpen(uv_work_t* req, int status); 20 | static void open_asyn_callback(uv_async_t* handle, int status); 21 | static HandleOpenSync(const Arguments& args); 22 | Sqlite3Client(); 23 | ~Sqlite3Client(); 24 | 25 | 26 | 27 | private: 28 | static Persistent s_ct; 29 | 30 | 31 | }; 32 | #endif 33 | -------------------------------------------------------------------------------- /test/tran.js: -------------------------------------------------------------------------------- 1 | var sqlite3 = require('../'); 2 | var ret; 3 | ret = sqlite3.open("test.db",function(err,conn){ 4 | if(err){ 5 | console.log('err'+err); 6 | } 7 | else{ 8 | 9 | console.log(conn.beginTran()); 10 | conn.executesync("insert into stu(id,name) values(?,?)",1,'郑华山'); 11 | conn.executesync("insert into stu(id,name) values(?,?)",1,'郑华山'); 12 | conn.executesync("insert into stu(id,name) values(?,?)",1,'郑华山'); 13 | conn.executesync("insert into stu(id,name) values(?,?)",1,'郑华山'); 14 | conn.executesync("insert into stu(id,name) values(?,?)",1,'郑华山'); 15 | conn.executesync("insert into stu(id,name) values(?,?)",1,'郑华山'); 16 | conn.executesync("insert into stu(id,name) values(?,?)",1,'郑华山'); 17 | 18 | console.log(conn.commitTran()); //异步不好支持事务 19 | conn.close(); 20 | console.log(conn.isopen()); 21 | 22 | } 23 | }); 24 | -------------------------------------------------------------------------------- /lib/statment.js: -------------------------------------------------------------------------------- 1 | 2 | function Statment(statment){ 3 | this.statment_ = statment; 4 | } 5 | 6 | module.exports = Statment; 7 | Statment.prototype.first = function(){ 8 | return this.statment_.moveFirst(); 9 | } 10 | 11 | Statment.prototype.next = function(){ 12 | return this.statment_.moveNext(); 13 | } 14 | Statment.prototype.last = function(){ 15 | return this.statment_.moveLast(); 16 | } 17 | 18 | Statment.prototype.fieldCount = function(){ 19 | return this.statment_.getFieldCount(); 20 | } 21 | Statment.prototype.recordCount = function(){ 22 | return this.statment_.getRecordCount(); 23 | } 24 | Statment.prototype.fieldValue = function(arg){ 25 | if (typeof(arg) === "number") 26 | return this.statment_.getFieldValueByIndex(arg); 27 | else if ( typeof (arg) === "string") 28 | return this.statment_.getFieldValueByName(arg); 29 | else 30 | return null; 31 | 32 | } 33 | Statment.prototype.fieldName = function(index){ 34 | return this.statment_.getFieldName(index); 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /test/excute.js: -------------------------------------------------------------------------------- 1 | var sqlite3 = require('../'); 2 | 3 | var ret; 4 | ret = sqlite3.open("test.db",function(err,conn){ 5 | if(err){ 6 | console.log('err'+err); 7 | } 8 | else{ 9 | console.log(conn); 10 | 11 | 12 | //conn.begin(function(err){ 13 | // if(err)return; 14 | conn.executesync("create table stu(id text,name text)"); 15 | 16 | conn.execute("insert into stu(id,name) values(?,?)",1,'郑华山',function(err){console.log(err)}); 17 | conn.execute("insert into stu(id,name) values(?,?)",1,'郑华山',function(err){}); 18 | conn.execute("insert into stu(id,name) values(?,?)",1,'郑华山',function(err){}); 19 | conn.execute("insert into stu(id,name) values(?,?)",1,'郑华山',function(err){}); 20 | conn.execute("insert into stu(id,name) values(?,?)",1,'郑华山',function(err){}); 21 | conn.execute("insert into stu(id,name) values(?,?)",1,'郑华山',function(err){}); 22 | conn.execute("insert into stu(id,name) values(?,?)",1,'郑华山',function(err){}); 23 | 24 | 25 | 26 | } 27 | }); 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/nodejs/Statement.h: -------------------------------------------------------------------------------- 1 | #ifndef _STATEMENT_H_ 2 | #define _STATEMENT_H_ 3 | #include 4 | #include 5 | using namespace v8; 6 | using namespace node; 7 | #include "DbSqlite.h" 8 | 9 | class Statement : public ObjectWrap 10 | { 11 | public: 12 | Statement(){} 13 | ~Statement(){}; 14 | 15 | static void Init(Handle target); 16 | static Handle New(const Arguments& args); 17 | static Handle MoveFirst(const Arguments& args); 18 | static Handle MoveNext(const Arguments& args); 19 | static Handle MoveLast(const Arguments& args); 20 | static Handle GetFieldCount(const Arguments& args); 21 | static Handle GetRecordCount(const Arguments& args); 22 | static Handle GetFieldValueByIndex(const Arguments& args); 23 | static Handle GetFieldValueByName(const Arguments& args); 24 | static Handle GetFieldName(const Arguments& args); 25 | 26 | 27 | void SetRecordsetPtr(CSqliteRecordsetPtr ptr) 28 | { 29 | pRecord = ptr; 30 | } 31 | public: 32 | static Persistent s_ct; 33 | private: 34 | CSqliteRecordsetPtr pRecord; 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | }; 43 | #endif 44 | -------------------------------------------------------------------------------- /src/third_party/CodingConv/encodeutil.h: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | #ifndef OS_WIN32 8 | //#include 9 | #endif 10 | 11 | 12 | #ifndef ENCODE_CONV_H_ 13 | #define ENCODE_CONV_H_ 14 | 15 | namespace encodeConv 16 | { 17 | 18 | class CodingConv 19 | { 20 | public: 21 | static string Unicode2Utf8(const wchar_t* pUnicode); 22 | static wstring Utf82Unicode(const char* pUtf8); 23 | static wstring s2ws(const string&s); 24 | static string ws2s(const wstring ws); 25 | static string ascii2Utf8(const char* pAscii); 26 | static string utf82Ascii(const char* pUtf8); 27 | static string urlEncode(const wchar_t* pUnicode); 28 | /* static wstring urlDecode(const wchar_t* pUnoode); 29 | #ifndef OS_WIN32 30 | static int gb2312_to_utf8(char *in, char *out, size_t size); 31 | #endif 32 | */ 33 | private: 34 | 35 | static int enc_unicode_to_utf8_one(unsigned long unic, unsigned char *pOutput,int outSize); 36 | static int my_utf8_to_unicode(vector& strUnicode, unsigned char* utf8, int len); 37 | 38 | 39 | }; 40 | 41 | 42 | 43 | 44 | 45 | }; 46 | 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /test/query.js: -------------------------------------------------------------------------------- 1 | var sqlite3 = require('../'); 2 | var ret; 3 | ret = sqlite3.open("test.db",function(err,conn){ 4 | if(err){ 5 | console.log('err'+err); 6 | } 7 | else{ 8 | console.log(conn); 9 | conn.query('select * from stu where name=?','郑华山',function(err,statment){ 10 | if(err){console.log('err'+err); return;} 11 | console.log('statment'+statment); 12 | field_count = statment.fieldCount(); 13 | console.log('field_count:'+ field_count); 14 | console.log('record_count:'+ statment.recordCount()); 15 | 16 | var bret = statment.first(); 17 | console.log(bret); 18 | console.log(statment.fieldName()); 19 | while(bret){ 20 | 21 | for(var i =0 ; i < field_count; ++i){ 22 | console.log('value:'+ statment.fieldValue(0)); 23 | console.log('value:'+ statment.fieldValue(1)); 24 | console.log('value:'+ statment.fieldValue('ID')); 25 | console.log('value:'+ statment.fieldValue('name')); 26 | //console.log('value:'+ object2); 27 | //var object = statment.getFieldValueByName('ID'); 28 | //console.log('value:'+ object); 29 | } 30 | bret = statment.next(); 31 | 32 | } 33 | conn.close(); 34 | 35 | }); 36 | 37 | 38 | } 39 | }); 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/nodejs/NodeFunction.cpp: -------------------------------------------------------------------------------- 1 | #include"NodeFunction.h" 2 | 3 | 4 | namespace NodeFunc 5 | { 6 | const char* ToCString(const String::Utf8Value& value) 7 | { 8 | return *value ? *value: "string conversion failed"; 9 | } 10 | TSTRING Replace( const TSTRING& orignStr, const TSTRING& oldStr, const vector&vc ) 11 | { 12 | size_t pos = 0; 13 | TSTRING tempStr = orignStr; 14 | TSTRING::size_type newStrLen; 15 | TSTRING::size_type oldStrLen = oldStr.length(); 16 | int i=0; 17 | 18 | while(true) 19 | { 20 | pos = tempStr.find(oldStr, pos); 21 | if (pos == TSTRING::npos) break; 22 | TSTRING s=vc.at(i); 23 | s = _T("\'")+s +_T("\'"); 24 | newStrLen= s.length(); 25 | 26 | tempStr.replace(pos, oldStrLen, s); 27 | pos += newStrLen; 28 | i++; 29 | 30 | } 31 | 32 | return tempStr; 33 | 34 | } 35 | TSTRING MergeSql(const Arguments&args) 36 | { 37 | String::Utf8Value str(args[0]); 38 | const char * pstr = ToCString(str); 39 | TSTRING s1; 40 | #ifdef OS_WIN32 41 | s1 = encodeConv::CodingConv::Utf82Unicode(pstr); 42 | #elif defined OS_LINUX 43 | s1 = pstr; 44 | 45 | #endif 46 | 47 | vector vc; 48 | int length = args.Length(); 49 | if (args[length-1]->IsFunction()) 50 | { 51 | length -= 1; 52 | } 53 | 54 | for(int i = 1; i 4 | #include 5 | using namespace node; 6 | using namespace v8; 7 | #include "DbSqlite.h" 8 | 9 | 10 | class Sqlite3Connection : public ObjectWrap 11 | { 12 | 13 | public: 14 | static void Init(Handle target); 15 | static Handle New(const Arguments& args); 16 | static Persistent constructorTemplate; 17 | static HandleClose(const Arguments& args); 18 | static HandleQuery(const Arguments& args); 19 | static HandleExecute(const Arguments& args); 20 | static HandleExecuteSync(const Arguments& args); 21 | static HandleEnterKey(const Arguments& args); 22 | static HandleDelKey(const Arguments& args); 23 | static HandleChangeKey(const Arguments& args); 24 | static HandleBeginTrans(const Arguments& args); 25 | static HandleRollbackTrans(const Arguments& args); 26 | static HandleCommitTrans(const Arguments& args); 27 | static HandleIsOpen(const Arguments& args); 28 | static HandleGetLastError(const Arguments& args); 29 | void closeConnection(); 30 | Sqlite3Connection(); 31 | ~Sqlite3Connection(); 32 | void setConnection(CSqliteConn*connection); 33 | private: 34 | CSqliteConn* m_pConn; 35 | 36 | 37 | private: 38 | //static void query_asyn_thread_work_tempdata(void* arg); 39 | static void query_asyn_thread_work_histroy(void* arg); 40 | static void query_asyn_thread_callback(uv_async_t* req,int status); 41 | 42 | static void uv_close_func(uv_handle_t* handle); 43 | static void excute_asyn_callback(uv_async_t* handle, int status); 44 | static void uv_execute(uv_work_t* req); 45 | static void uv_execute_after(uv_work_t* req,int status); 46 | static void uv_query(uv_work_t* req); 47 | static void uv_query_after(uv_work_t* req,int status); 48 | 49 | 50 | }; 51 | 52 | #endif 53 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/sqlite3secure.c: -------------------------------------------------------------------------------- 1 | // To enable the extension functions define SQLITE_ENABLE_EXTFUNC on compiling this module 2 | #ifdef SQLITE_ENABLE_EXTFUNC 3 | #define sqlite3_open sqlite3_open_internal 4 | #define sqlite3_open16 sqlite3_open16_internal 5 | #define sqlite3_open_v2 sqlite3_open_v2_internal 6 | #endif 7 | 8 | #include "sqlite3.c" 9 | 10 | #ifdef SQLITE_ENABLE_EXTFUNC 11 | #undef sqlite3_open 12 | #undef sqlite3_open16 13 | #undef sqlite3_open_v2 14 | #endif 15 | 16 | #ifndef SQLITE_OMIT_DISKIO 17 | 18 | #ifdef SQLITE_HAS_CODEC 19 | 20 | /* 21 | ** Get the codec argument for this pager 22 | */ 23 | 24 | void* mySqlite3PagerGetCodec( 25 | Pager *pPager 26 | ){ 27 | #if (SQLITE_VERSION_NUMBER >= 3006016) 28 | return sqlite3PagerGetCodec(pPager); 29 | #else 30 | return (pPager->xCodec) ? pPager->pCodecArg : NULL; 31 | #endif 32 | } 33 | 34 | /* 35 | ** Set the codec argument for this pager 36 | */ 37 | 38 | void mySqlite3PagerSetCodec( 39 | Pager *pPager, 40 | void *(*xCodec)(void*,void*,Pgno,int), 41 | void (*xCodecSizeChng)(void*,int,int), 42 | void (*xCodecFree)(void*), 43 | void *pCodec 44 | ){ 45 | sqlite3PagerSetCodec(pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec); 46 | } 47 | 48 | #include "rijndael.c" 49 | #include "codec.c" 50 | #include "codecext.c" 51 | 52 | #endif 53 | 54 | #endif 55 | 56 | #ifdef SQLITE_ENABLE_EXTFUNC 57 | 58 | #include "extensionfunctions.c" 59 | 60 | SQLITE_API int sqlite3_open( 61 | const char *filename, /* Database filename (UTF-8) */ 62 | sqlite3 **ppDb /* OUT: SQLite db handle */ 63 | ) 64 | { 65 | int ret = sqlite3_open_internal(filename, ppDb); 66 | if (ret == 0) 67 | { 68 | RegisterExtensionFunctions(*ppDb); 69 | } 70 | return ret; 71 | } 72 | 73 | SQLITE_API int sqlite3_open16( 74 | const void *filename, /* Database filename (UTF-16) */ 75 | sqlite3 **ppDb /* OUT: SQLite db handle */ 76 | ) 77 | { 78 | int ret = sqlite3_open16_internal(filename, ppDb); 79 | if (ret == 0) 80 | { 81 | RegisterExtensionFunctions(*ppDb); 82 | } 83 | return ret; 84 | } 85 | 86 | SQLITE_API int sqlite3_open_v2( 87 | const char *filename, /* Database filename (UTF-8) */ 88 | sqlite3 **ppDb, /* OUT: SQLite db handle */ 89 | int flags, /* Flags */ 90 | const char *zVfs /* Name of VFS module to use */ 91 | ) 92 | { 93 | int ret = sqlite3_open_v2_internal(filename, ppDb, flags, zVfs); 94 | if (ret == 0) 95 | { 96 | RegisterExtensionFunctions(*ppDb); 97 | } 98 | return ret; 99 | } 100 | 101 | #endif 102 | -------------------------------------------------------------------------------- /lib/connection.js: -------------------------------------------------------------------------------- 1 | var Statment = require('./statment'); 2 | 3 | 4 | function Connection(conn){ 5 | this.conn_ = conn; 6 | } 7 | 8 | module.exports=Connection; 9 | 10 | function to_sql(sql,args){ 11 | 12 | var re =/\?/; //正则表达式 13 | var filter = args.shift(); 14 | while(filter){ 15 | sql=sql.replace(re,"'"+filter+"'"); 16 | filter = args.shift(); 17 | } 18 | return sql; 19 | } 20 | 21 | 22 | //callback (err,conn) 23 | 24 | //callback (err,statement) 25 | Connection.prototype.query = function(){ 26 | var args = Array.prototype.slice.call(arguments,0); 27 | var callback = args.pop(); 28 | var sql = args.shift();//sql 29 | if (sql.search(/\?/) != -1){ 30 | sql = to_sql(sql,args); 31 | } 32 | this.conn_.query(sql,function(err,statment){ 33 | if(err){ 34 | return callback(err,null); 35 | }else{ 36 | var statment_ = new Statment(statment); 37 | return callback(null,statment_); 38 | } 39 | }); 40 | }; 41 | //callback (err,null) 42 | Connection.prototype.execute = function(){ 43 | var args = Array.prototype.slice.call(arguments,0); 44 | var callback = args.pop(); 45 | var sql = args.shift();//sql 46 | if (sql.search(/\?/) != -1){ 47 | sql = to_sql(sql,args); 48 | } 49 | this.conn_.execute(sql,callback); 50 | }; 51 | //return true or false 52 | Connection.prototype.executesync = function(){ 53 | var args = Array.prototype.slice.call(arguments,0); 54 | //var callback = args.pop(); 55 | var sql = args.shift();//sql 56 | if (sql.search(/\?/) != -1){ 57 | sql = to_sql(sql,args); 58 | } 59 | //console.log(sql); 60 | this.conn_.executesync(sql); 61 | }; 62 | //return true or false 63 | Connection.prototype.beginTran = function(){ 64 | this.conn_.begin(); 65 | }; 66 | //return true or false 67 | Connection.prototype.commitTran = function(){ 68 | this.conn_.commit(); 69 | }; 70 | //return true or false 71 | Connection.prototype.rollbackTran = function(){ 72 | this.conn_.rollback(); 73 | }; 74 | //return true or false 75 | Connection.prototype.close = function(){ 76 | this.conn_.close(); 77 | }; 78 | //return true or false 79 | Connection.prototype.enterkey = function(key){ 80 | this.conn_.enterkey(key); 81 | }; 82 | 83 | //return true or false 84 | Connection.prototype.changekey = function(key){ 85 | this.conn_.changekey(key); 86 | }; 87 | //return true or false 88 | Connection.prototype.delkey = function(){ 89 | this.conn_.delkey(); 90 | }; 91 | 92 | //return true or false 93 | Connection.prototype.isopen = function(){ 94 | this.conn_.isopen(); 95 | }; 96 | 97 | //return string 98 | //调用该函数返回最后一次错误,针对同步的API 99 | Connection.prototype.getLastError = function(){ 100 | this.conn_.getLastError(); 101 | }; 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /src/nodejs/QueryJob.cc: -------------------------------------------------------------------------------- 1 | #include "QueryJob.h" 2 | //#include "../../third_party/CodingConv/encodeutil.h" 3 | 4 | // 5 | //struct _time_check 6 | //{ 7 | // DWORD _tstart; 8 | // DWORD _tend; 9 | //}; 10 | // 11 | //void tc_start (struct _time_check *tc) 12 | //{ 13 | // 14 | // memset (tc, 0, sizeof (struct _time_check)); 15 | // tc->_tstart = GetTickCount(); 16 | // 17 | // 18 | //} 19 | // 20 | ////----------------------------------------------------------------------------- 21 | //void tc_end (struct _time_check *tc) 22 | //{ 23 | // 24 | // tc->_tend = GetTickCount(); 25 | // 26 | //} 27 | // 28 | ////----------------------------------------------------------------------------- 29 | //double tc_val (struct _time_check *tc) 30 | //{ 31 | // 32 | // return (tc->_tend - tc->_tstart); 33 | // 34 | //} 35 | //void QueryJob::queryTempdata(QueryJob* query_job) 36 | //{ 37 | // 38 | // query_job->pConn->getTempdata(query_job->sql,query_job->result); 39 | // 40 | // ////_time_check tc; 41 | // ////tc_start(&tc); 42 | // //////uv_mutex_lock() 43 | // ////OCICursor cursor_(query_job->pConn); 44 | // ////bool bRet = cursor_.query((query_job->sql).c_str()); 45 | // ////if (!bRet) 46 | // ////{ 47 | // //// 48 | // //// query_job->error = OCIException::getErrorMsg(); 49 | // //// cout<<"connect error:"<error< record; 65 | // //// 66 | // //// for(int i=0;i< size;i++) 67 | // //// { 68 | // //// const char* pValue = cursor_.getFieldValue(i+1); 69 | // //// //cout<<"value"<result.push_back(record); 97 | // //// bRet = cursor_.moveNext(); 98 | // //// j++; 99 | // ////} 100 | // ////} 101 | // //// 102 | // ////catch (exception*e) 103 | // ////{ 104 | // //// cout<<"query:"<< e->what()<sql<result = result; 113 | // //// 114 | // 115 | // ////cursor_.close(); 116 | // //////conn.disconnect(); 117 | // ////tc_end(&tc); 118 | // ////cout<<"times"<pConn->getHistoryTricks(queryJob->sql,queryJob->result); 129 | // //QueryJob->result = result; 130 | // 131 | //} 132 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/codec.h: -------------------------------------------------------------------------------- 1 | /* 2 | /////////////////////////////////////////////////////////////////////////////// 3 | // Name: codec.h 4 | // Purpose: 5 | // Author: Ulrich Telle 6 | // Modified by: 7 | // Created: 2006-12-06 8 | // Copyright: (c) Ulrich Telle 9 | // Licence: wxWindows licence 10 | /////////////////////////////////////////////////////////////////////////////// 11 | 12 | /// \file codec.h Interface of the codec class 13 | */ 14 | 15 | #ifndef _CODEC_H_ 16 | #define _CODEC_H_ 17 | 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | #if defined(__BORLANDC__) 23 | #define __STDC__ 1 24 | #endif 25 | 26 | #if defined(__BORLANDC__) 27 | #undef __STDC__ 28 | #endif 29 | 30 | /* 31 | // ATTENTION: Macro similar to that in pager.c 32 | // TODO: Check in case of new version of SQLite 33 | */ 34 | #define WX_PAGER_MJ_PGNO(x) ((PENDING_BYTE/(x))+1) 35 | 36 | #ifdef __cplusplus 37 | } /* End of the 'extern "C"' block */ 38 | #endif 39 | 40 | #include "rijndael.h" 41 | 42 | #define CODEC_TYPE_AES128 1 43 | #define CODEC_TYPE_AES256 2 44 | 45 | #ifndef CODEC_TYPE 46 | #define CODEC_TYPE CODEC_TYPE_AES128 47 | #endif 48 | 49 | #if CODEC_TYPE == CODEC_TYPE_AES256 50 | #define KEYLENGTH 32 51 | #define CODEC_SHA_ITER 4001 52 | #else 53 | #define KEYLENGTH 16 54 | #endif 55 | 56 | typedef struct _Codec 57 | { 58 | int m_isEncrypted; 59 | int m_hasReadKey; 60 | unsigned char m_readKey[KEYLENGTH]; 61 | int m_hasWriteKey; 62 | unsigned char m_writeKey[KEYLENGTH]; 63 | Rijndael* m_aes; 64 | 65 | Btree* m_bt; /* Pointer to B-tree used by DB */ 66 | unsigned char m_page[SQLITE_MAX_PAGE_SIZE+8]; 67 | } Codec; 68 | 69 | void CodecInit(Codec* codec); 70 | void CodecTerm(Codec* codec); 71 | 72 | void CodecCopy(Codec* codec, Codec* other); 73 | 74 | void CodecGenerateReadKey(Codec* codec, char* userPassword, int passwordLength); 75 | 76 | void CodecGenerateWriteKey(Codec* codec, char* userPassword, int passwordLength); 77 | 78 | void CodecEncrypt(Codec* codec, int page, unsigned char* data, int len, int useWriteKey); 79 | 80 | void CodecDecrypt(Codec* codec, int page, unsigned char* data, int len); 81 | 82 | void CodecCopyKey(Codec* codec, int read2write); 83 | 84 | void CodecSetIsEncrypted(Codec* codec, int isEncrypted); 85 | void CodecSetHasReadKey(Codec* codec, int hasReadKey); 86 | void CodecSetHasWriteKey(Codec* codec, int hasWriteKey); 87 | void CodecSetBtree(Codec* codec, Btree* bt); 88 | 89 | int CodecIsEncrypted(Codec* codec); 90 | int CodecHasReadKey(Codec* codec); 91 | int CodecHasWriteKey(Codec* codec); 92 | Btree* CodecGetBtree(Codec* codec); 93 | unsigned char* CodecGetPageBuffer(Codec* codec); 94 | 95 | void CodecGenerateEncryptionKey(Codec* codec, char* userPassword, int passwordLength, 96 | unsigned char encryptionKey[KEYLENGTH]); 97 | 98 | void CodecPadPassword(Codec* codec, char* password, int pswdlen, unsigned char pswd[32]); 99 | 100 | void CodecRC4(Codec* codec, unsigned char* key, int keylen, 101 | unsigned char* textin, int textlen, 102 | unsigned char* textout); 103 | 104 | void CodecGetMD5Binary(Codec* codec, unsigned char* data, int length, unsigned char* digest); 105 | 106 | #if CODEC_TYPE == CODEC_TYPE_AES256 107 | void CodecGetSHABinary(Codec* codec, unsigned char* data, int length, unsigned char* digest); 108 | #endif 109 | 110 | void CodecGenerateInitialVector(Codec* codec, int seed, unsigned char iv[16]); 111 | 112 | void CodecAES(Codec* codec, int page, int encrypt, unsigned char encryptionKey[KEYLENGTH], 113 | unsigned char* datain, int datalen, unsigned char* dataout); 114 | 115 | #endif 116 | -------------------------------------------------------------------------------- /src/nodejs/Statement.cpp: -------------------------------------------------------------------------------- 1 | #include "Statement.h" 2 | #include "NodeFunction.h" 3 | using namespace NodeFunc; 4 | PersistentStatement::s_ct; 5 | 6 | 7 | 8 | void Statement::Init(Handle target) 9 | { 10 | HandleScope scope; 11 | Local t = FunctionTemplate::New(New); 12 | s_ct = Persistent::New(t); 13 | s_ct->InstanceTemplate()->SetInternalFieldCount(1); 14 | s_ct->SetClassName(String::NewSymbol("Statement")); 15 | NODE_SET_PROTOTYPE_METHOD(s_ct,"moveFirst",MoveFirst); 16 | NODE_SET_PROTOTYPE_METHOD(s_ct,"moveNext",MoveNext); 17 | NODE_SET_PROTOTYPE_METHOD(s_ct,"getFieldCount",GetFieldCount); 18 | NODE_SET_PROTOTYPE_METHOD(s_ct,"getRecordCount",GetRecordCount); 19 | NODE_SET_PROTOTYPE_METHOD(s_ct,"getFieldValueByIndex",GetFieldValueByIndex); 20 | NODE_SET_PROTOTYPE_METHOD(s_ct,"getFieldValueByName",GetFieldValueByName); 21 | NODE_SET_PROTOTYPE_METHOD(s_ct,"getFieldName",GetFieldName); 22 | target->Set(String::NewSymbol("Statement"),s_ct->GetFunction()); 23 | 24 | 25 | } 26 | 27 | HandleStatement::New(const Arguments& args) 28 | { 29 | HandleScope scope; 30 | Statement* statement = new Statement(); 31 | statement->Wrap(args.This()); 32 | return args.This(); 33 | } 34 | 35 | Handle Statement::MoveFirst(const Arguments& args) 36 | { 37 | 38 | Statement* pStatement = ObjectWrap::Unwrap(args.This()); 39 | HandleScope scope; 40 | BOOL bRet = pStatement->pRecord->MoveFirst(); 41 | return scope.Close(Boolean::New(bRet)); 42 | } 43 | Handle Statement::MoveNext(const Arguments& args) 44 | { 45 | Statement* pStatement = ObjectWrap::Unwrap(args.This()); 46 | HandleScope scope; 47 | BOOL bRet = pStatement->pRecord->MoveNext(); 48 | return scope.Close(Boolean::New(bRet)); 49 | 50 | } 51 | Handle Statement::MoveLast(const Arguments& args) 52 | { 53 | /* Statement* pStatement = ObjectWrap::Unwrap(args.This()); 54 | HandleScope scope; 55 | BOOL bRet = pStatement->pRecord->MoveLast(); 56 | return scope.Close(Boolean::New(bRet));*/ 57 | return Undefined(); 58 | } 59 | Handle Statement::GetFieldCount(const Arguments& args) 60 | { 61 | Statement* pStatement = ObjectWrap::Unwrap(args.This()); 62 | HandleScope scope; 63 | int field_count = pStatement->pRecord->GetFieldCount(); 64 | 65 | return scope.Close(Integer::New(field_count)); 66 | } 67 | Handle Statement::GetRecordCount(const Arguments& args) 68 | { 69 | 70 | Statement* pStatement = ObjectWrap::Unwrap(args.This()); 71 | HandleScope scope; 72 | int record_count = pStatement->pRecord->GetRecordCount(); 73 | 74 | return scope.Close(Integer::New(record_count)); 75 | } 76 | Handle Statement::GetFieldValueByIndex(const Arguments& args) 77 | { 78 | Statement* pStatement = ObjectWrap::Unwrap(args.This()); 79 | HandleScope scope; 80 | int index = args[0]->Int32Value(); 81 | Sqlite3_XX::VARIANT var = pStatement->pRecord->GetFieldValue(index); 82 | if (var.vt == Sqlite3_XX::VT_BSTR) 83 | { 84 | TSTRING value = var.bstrVal; 85 | #ifdef OS_WIN32 86 | return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(value.c_str()).c_str())); 87 | 88 | #elif defined OS_LINUX 89 | return scope.Close(String::New(value.c_str())); 90 | #endif 91 | 92 | } 93 | else if (var.vt == Sqlite3_XX::VT_I4) 94 | { 95 | return scope.Close(Integer::New(var.intVal)); 96 | } 97 | else if (var.vt == Sqlite3_XX::VT_R8) 98 | { 99 | return scope.Close(Number::New(var.dblVal)); 100 | } 101 | return Undefined(); 102 | 103 | } 104 | Handle Statement::GetFieldValueByName(const Arguments& args) 105 | { 106 | Statement* pStatement = ObjectWrap::Unwrap(args.This()); 107 | HandleScope scope; 108 | String::Utf8Value field_name(args[0]); 109 | // const char* pfield_name = ToCString(field_name); 110 | TSTRING name; 111 | #ifdef OS_WIN32 112 | 113 | name = encodeConv::CodingConv::s2ws(ToCString(field_name)); 114 | #elif defined OS_LINUX 115 | name = ToCString(field_name); 116 | #endif 117 | Sqlite3_XX::VARIANT var = pStatement->pRecord->GetFieldValue(name.c_str()); 118 | Local obj = Object::New(); 119 | if (var.vt == Sqlite3_XX::VT_BSTR) 120 | { 121 | TSTRING value = var.bstrVal; 122 | #ifdef OS_WIN32 123 | return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(value.c_str()).c_str())); 124 | 125 | #elif defined OS_LINUX 126 | return scope.Close(String::New(value.c_str())); 127 | #endif 128 | 129 | } 130 | else if (var.vt == Sqlite3_XX::VT_I4) 131 | { 132 | return scope.Close(Integer::New(var.intVal)); 133 | } 134 | else if (var.vt == Sqlite3_XX::VT_R8) 135 | { 136 | return scope.Close(Number::New(var.dblVal)); 137 | } 138 | return Undefined(); 139 | 140 | } 141 | 142 | 143 | Handle Statement::GetFieldName(const Arguments& args) 144 | { 145 | int index = args[0]->Int32Value(); 146 | HandleScope scope; 147 | Statement* pStatement = ObjectWrap::Unwrap(args.This()); 148 | TSTRING name = pStatement->pRecord->GetFieldName(index); 149 | 150 | #ifdef OS_WIN32 151 | return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(name.c_str()).c_str())); 152 | 153 | 154 | #elif defined OS_LINUX 155 | return scope.Close(String::New(name.c_str())); 156 | 157 | #endif 158 | return Undefined(); 159 | 160 | } 161 | 162 | 163 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/sha2.h: -------------------------------------------------------------------------------- 1 | /* 2 | * FIPS 180-2 SHA-224/256/384/512 implementation 3 | * Last update: 02/02/2007 4 | * Issue date: 04/30/2005 5 | * 6 | * Copyright (C) 2005, 2007 Olivier Gay 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without 10 | * modification, are permitted provided that the following conditions 11 | * are met: 12 | * 1. Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 2. Redistributions in binary form must reproduce the above copyright 15 | * notice, this list of conditions and the following disclaimer in the 16 | * documentation and/or other materials provided with the distribution. 17 | * 3. Neither the name of the project nor the names of its contributors 18 | * may be used to endorse or promote products derived from this software 19 | * without specific prior written permission. 20 | * 21 | * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND 22 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE 25 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 | * SUCH DAMAGE. 32 | */ 33 | 34 | #ifndef SHA2_H 35 | #define SHA2_H 36 | 37 | #define SHA224_DIGEST_SIZE ( 224 / 8) 38 | #define SHA256_DIGEST_SIZE ( 256 / 8) 39 | #define SHA384_DIGEST_SIZE ( 384 / 8) 40 | #define SHA512_DIGEST_SIZE ( 512 / 8) 41 | 42 | #define SHA256_BLOCK_SIZE ( 512 / 8) 43 | #define SHA512_BLOCK_SIZE (1024 / 8) 44 | #define SHA384_BLOCK_SIZE SHA512_BLOCK_SIZE 45 | #define SHA224_BLOCK_SIZE SHA256_BLOCK_SIZE 46 | 47 | #ifndef SHA2_TYPES 48 | #define SHA2_TYPES 49 | typedef unsigned char uint8; 50 | typedef unsigned int uint32; 51 | 52 | #if defined(_MSC_VER) 53 | #if _MSC_VER >= 1310 54 | typedef unsigned long long uint64; 55 | #define li_64(h) 0x##h##ull 56 | #else 57 | typedef unsigned __int64 uint64; 58 | #define li_64(h) 0x##h##ui64 59 | #endif 60 | #elif defined(__BORLANDC__) && !defined(__MSDOS__) 61 | #define li_64(h) 0x##h##ull 62 | typedef __int64 uint64; 63 | #elif defined(__sun) 64 | #if defined(ULONG_MAX) && ULONG_MAX == 0xfffffffful 65 | #define li_64(h) 0x##h##ull 66 | typedef unsigned long long uint64; 67 | #elif defined(ULONG_LONG_MAX) && ULONG_LONG_MAX == 0xfffffffffffffffful 68 | #define li_64(h) 0x##h##ul 69 | typedef unsigned long uint64; 70 | #endif 71 | #elif defined(__MVS__) 72 | #define li_64(h) 0x##h##ull 73 | typedef unsigned int long long uint64; 74 | #elif defined(ULLONG_MAX) && ULLONG_MAX > 4294967295 75 | #if ULLONG_MAX == 18446744073709551615ull 76 | #define li_64(h) 0x##h##ull 77 | typedef unsigned long long uint64; 78 | #endif 79 | #elif defined(ULONG_LONG_MAX) && ULONG_LONG_MAX > 4294967295 80 | #if ULONG_LONG_MAX == 18446744073709551615 81 | #define li_64(h) 0x##h##ull 82 | typedef unsigned long long uint64; 83 | #endif 84 | #elif defined(ULONG_MAX) && ULONG_MAX > 4294967295 85 | #if ULONG_MAX == 18446744073709551615 86 | #define li_64(h) 0x##h##ul 87 | typedef unsigned long uint64; 88 | #endif 89 | #elif defined(UINT_MAX) && UINT_MAX > 4294967295 90 | #if UINT_MAX == 18446744073709551615 91 | #define li_64(h) 0x##h##u 92 | typedef unsigned int uint64; 93 | #endif 94 | #endif 95 | #endif 96 | 97 | #ifdef __cplusplus 98 | extern "C" { 99 | #endif 100 | 101 | typedef struct { 102 | unsigned int tot_len; 103 | unsigned int len; 104 | unsigned char block[2 * SHA256_BLOCK_SIZE]; 105 | uint32 h[8]; 106 | } sha256_ctx; 107 | 108 | typedef struct { 109 | unsigned int tot_len; 110 | unsigned int len; 111 | unsigned char block[2 * SHA512_BLOCK_SIZE]; 112 | uint64 h[8]; 113 | } sha512_ctx; 114 | 115 | typedef sha512_ctx sha384_ctx; 116 | typedef sha256_ctx sha224_ctx; 117 | 118 | void sha224_init(sha224_ctx *ctx); 119 | void sha224_update(sha224_ctx *ctx, const unsigned char *message, 120 | unsigned int len); 121 | void sha224_final(sha224_ctx *ctx, unsigned char *digest); 122 | void sha224(const unsigned char *message, unsigned int len, 123 | unsigned char *digest); 124 | 125 | void sha256_init(sha256_ctx * ctx); 126 | void sha256_update(sha256_ctx *ctx, const unsigned char *message, 127 | unsigned int len); 128 | void sha256_final(sha256_ctx *ctx, unsigned char *digest); 129 | void sha256(const unsigned char *message, unsigned int len, 130 | unsigned char *digest); 131 | 132 | void sha384_init(sha384_ctx *ctx); 133 | void sha384_update(sha384_ctx *ctx, const unsigned char *message, 134 | unsigned int len); 135 | void sha384_final(sha384_ctx *ctx, unsigned char *digest); 136 | void sha384(const unsigned char *message, unsigned int len, 137 | unsigned char *digest); 138 | 139 | void sha512_init(sha512_ctx *ctx); 140 | void sha512_update(sha512_ctx *ctx, const unsigned char *message, 141 | unsigned int len); 142 | void sha512_final(sha512_ctx *ctx, unsigned char *digest); 143 | void sha512(const unsigned char *message, unsigned int len, 144 | unsigned char *digest); 145 | 146 | #ifdef __cplusplus 147 | } 148 | #endif 149 | 150 | #endif /* !SHA2_H */ 151 | 152 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/rijndael.h: -------------------------------------------------------------------------------- 1 | /* 2 | /////////////////////////////////////////////////////////////////////////////// 3 | // Name: rijndael.h 4 | // Purpose: 5 | // Author: Ulrich Telle 6 | // Modified by: 7 | // Created: 2006-12-06 8 | // Copyright: (c) Ulrich Telle (Copyright for original code see below) 9 | // Licence: wxWindows licence 10 | // 11 | // The original code is unchanged 12 | /////////////////////////////////////////////////////////////////////////////// 13 | 14 | /// \file rijndael.h Interface of the Rijndael cipher 15 | */ 16 | 17 | #ifndef _RIJNDAEL_H_ 18 | #define _RIJNDAEL_H_ 19 | 20 | /* 21 | // File : rijndael.h 22 | // Creation date : Sun Nov 5 2000 03:21:05 CEST 23 | // Author : Szymon Stefanek (stefanek@tin.it) 24 | // 25 | // Another implementation of the Rijndael cipher. 26 | // This is intended to be an easily usable library file. 27 | // This code is public domain. 28 | // Based on the Vincent Rijmen and K.U.Leuven implementation 2.4. 29 | // 30 | // Original Copyright notice: 31 | // 32 | // rijndael-alg-fst.c v2.4 April '2000 33 | // rijndael-alg-fst.h 34 | // rijndael-api-fst.c 35 | // rijndael-api-fst.h 36 | // 37 | // Optimised ANSI C code 38 | // 39 | // authors: v1.0: Antoon Bosselaers 40 | // v2.0: Vincent Rijmen, K.U.Leuven 41 | // v2.3: Paulo Barreto 42 | // v2.4: Vincent Rijmen, K.U.Leuven 43 | // 44 | // This code is placed in the public domain. 45 | // 46 | 47 | // 48 | // This implementation works on 128 , 192 , 256 bit keys 49 | // and on 128 bit blocks 50 | // 51 | 52 | // 53 | // Example of usage: 54 | // 55 | // // Input data 56 | // unsigned char key[32]; // The key 57 | // initializeYour256BitKey(); // Obviously initialized with sth 58 | // const unsigned char * plainText = getYourPlainText(); // Your plain text 59 | // int plainTextLen = strlen(plainText); // Plain text length 60 | // 61 | // // Encrypting 62 | // Rijndael rin; 63 | // unsigned char output[plainTextLen + 16]; 64 | // 65 | // rin.init(Rijndael::CBC,Rijndael::Encrypt,key,Rijndael::Key32Bytes); 66 | // // It is a good idea to check the error code 67 | // int len = rin.padEncrypt(plainText,len,output); 68 | // if(len >= 0)useYourEncryptedText(); 69 | // else encryptError(len); 70 | // 71 | // // Decrypting: we can reuse the same object 72 | // unsigned char output2[len]; 73 | // rin.init(Rijndael::CBC,Rijndael::Decrypt,key,Rijndael::Key32Bytes)); 74 | // len = rin.padDecrypt(output,len,output2); 75 | // if(len >= 0)useYourDecryptedText(); 76 | // else decryptError(len); 77 | // 78 | */ 79 | 80 | #define _MAX_KEY_COLUMNS (256/32) 81 | #define _MAX_ROUNDS 14 82 | #define MAX_IV_SIZE 16 83 | 84 | /* We assume that unsigned int is 32 bits long.... */ 85 | typedef unsigned char UINT8; 86 | typedef unsigned int UINT32; 87 | typedef unsigned short UINT16; 88 | 89 | /* Error codes */ 90 | #define RIJNDAEL_SUCCESS 0 91 | #define RIJNDAEL_UNSUPPORTED_MODE -1 92 | #define RIJNDAEL_UNSUPPORTED_DIRECTION -2 93 | #define RIJNDAEL_UNSUPPORTED_KEY_LENGTH -3 94 | #define RIJNDAEL_BAD_KEY -4 95 | #define RIJNDAEL_NOT_INITIALIZED -5 96 | #define RIJNDAEL_BAD_DIRECTION -6 97 | #define RIJNDAEL_CORRUPTED_DATA -7 98 | 99 | #define RIJNDAEL_Direction_Encrypt 0 100 | #define RIJNDAEL_Direction_Decrypt 1 101 | 102 | #define RIJNDAEL_Direction_Mode_ECB 0 103 | #define RIJNDAEL_Direction_Mode_CBC 1 104 | #define RIJNDAEL_Direction_Mode_CFB1 2 105 | 106 | #define RIJNDAEL_Direction_KeyLength_Key16Bytes 0 107 | #define RIJNDAEL_Direction_KeyLength_Key24Bytes 1 108 | #define RIJNDAEL_Direction_KeyLength_Key32Bytes 2 109 | 110 | #define RIJNDAEL_State_Valid 0 111 | #define RIJNDAEL_State_Invalid 1 112 | 113 | /* 114 | /// Class implementing the Rijndael cipher. (For internal use only) 115 | */ 116 | 117 | typedef struct _Rijndael 118 | { 119 | int m_state; 120 | int m_mode; 121 | int m_direction; 122 | UINT8 m_initVector[MAX_IV_SIZE]; 123 | UINT32 m_uRounds; 124 | UINT8 m_expandedKey[_MAX_ROUNDS+1][4][4]; 125 | } Rijndael; 126 | 127 | void RijndaelCreate(Rijndael* rijndael); 128 | 129 | /* 130 | ////////////////////////////////////////////////////////////////////////////////////////// 131 | // API 132 | ////////////////////////////////////////////////////////////////////////////////////////// 133 | 134 | // init(): Initializes the crypt session 135 | // Returns RIJNDAEL_SUCCESS or an error code 136 | // mode : Rijndael::ECB, Rijndael::CBC or Rijndael::CFB1 137 | // You have to use the same mode for encrypting and decrypting 138 | // dir : Rijndael::Encrypt or Rijndael::Decrypt 139 | // A cipher instance works only in one direction 140 | // (Well , it could be easily modified to work in both 141 | // directions with a single init() call, but it looks 142 | // useless to me...anyway , it is a matter of generating 143 | // two expanded keys) 144 | // key : array of unsigned octets , it can be 16 , 24 or 32 bytes long 145 | // this CAN be binary data (it is not expected to be null terminated) 146 | // keyLen : Rijndael::Key16Bytes , Rijndael::Key24Bytes or Rijndael::Key32Bytes 147 | // initVector: initialization vector, you will usually use 0 here 148 | */ 149 | int RijndaelInit(Rijndael* rijndael, int mode, int dir, UINT8* key, int keyLen, UINT8* initVector); 150 | 151 | /* 152 | // Encrypts the input array (can be binary data) 153 | // The input array length must be a multiple of 16 bytes, the remaining part 154 | // is DISCARDED. 155 | // so it actually encrypts inputLen / 128 blocks of input and puts it in outBuffer 156 | // Input len is in BITS! 157 | // outBuffer must be at least inputLen / 8 bytes long. 158 | // Returns the encrypted buffer length in BITS or an error code < 0 in case of error 159 | */ 160 | int RijndaelBlockEncrypt(Rijndael* rijndael, UINT8 *input, int inputLen, UINT8 *outBuffer); 161 | 162 | /* 163 | // Encrypts the input array (can be binary data) 164 | // The input array can be any length , it is automatically padded on a 16 byte boundary. 165 | // Input len is in BYTES! 166 | // outBuffer must be at least (inputLen + 16) bytes long 167 | // Returns the encrypted buffer length in BYTES or an error code < 0 in case of error 168 | */ 169 | int RijndaelPadEncrypt(Rijndael* rijndael, UINT8 *input, int inputOctets, UINT8 *outBuffer); 170 | 171 | /* 172 | // Decrypts the input vector 173 | // Input len is in BITS! 174 | // outBuffer must be at least inputLen / 8 bytes long 175 | // Returns the decrypted buffer length in BITS and an error code < 0 in case of error 176 | */ 177 | int RijndaelBlockDecrypt(Rijndael* rijndael, UINT8 *input, int inputLen, UINT8 *outBuffer); 178 | 179 | /* 180 | // Decrypts the input vector 181 | // Input len is in BYTES! 182 | // outBuffer must be at least inputLen bytes long 183 | // Returns the decrypted buffer length in BYTES and an error code < 0 in case of error 184 | */ 185 | int RijndaelPadDecrypt(Rijndael* rijndael, UINT8 *input, int inputOctets, UINT8 *outBuffer); 186 | 187 | void RijndaelInvalidate(Rijndael* rijndael); 188 | void RijndaelKeySched(Rijndael* rijndael, UINT8 key[_MAX_KEY_COLUMNS][4]); 189 | void RijndaelKeyEncToDec(Rijndael* rijndael); 190 | void RijndaelEncrypt(Rijndael* rijndael, UINT8 a[16], UINT8 b[16]); 191 | void RijndaelDecrypt(Rijndael* rijndael, UINT8 a[16], UINT8 b[16]); 192 | 193 | #endif /* _RIJNDAEL_H_ */ 194 | -------------------------------------------------------------------------------- /src/nodejs/Sqlite3Client.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Sqlite3Client.h" 3 | #include "Sqlite3Connection.h" 4 | #include "ConnJob.h" 5 | #include "Statement.h" 6 | #include "encodeutil.h" 7 | #include "NodeFunction.h" 8 | using namespace NodeFunc; 9 | 10 | Persistent Sqlite3Client::s_ct; 11 | 12 | 13 | 14 | 15 | Sqlite3Client::Sqlite3Client(){} 16 | Sqlite3Client::~Sqlite3Client(){} 17 | void Sqlite3Client::Init(Handle target) 18 | { 19 | HandleScope scope; 20 | 21 | Local t = FunctionTemplate::New(New); 22 | s_ct = Persistent::New(t); 23 | s_ct->InstanceTemplate()->SetInternalFieldCount(1); 24 | s_ct->SetClassName(String::NewSymbol("Sqlite3Client")); //名字就是以后new 的类型 25 | //NODE_SET_PROTOTYPE_METHOD(s_ct, "open", Open); 26 | //NODE_SET_PROTOTYPE_METHOD(s_ct, "open", Open); 27 | //只有一个函数的话在windows平台下会报错采用如下写法. 28 | t->PrototypeTemplate()->Set(String::NewSymbol("open"), 29 | FunctionTemplate::New(Open)->GetFunction()); 30 | t->PrototypeTemplate()->Set(String::NewSymbol("openSync"), 31 | FunctionTemplate::New(OpenSync)->GetFunction()); 32 | target->Set(String::NewSymbol("Sqlite3Client"), s_ct->GetFunction()); 33 | 34 | } 35 | 36 | Handle Sqlite3Client::New(const Arguments& args) { 37 | HandleScope scope; 38 | Sqlite3Client *client = new Sqlite3Client(); 39 | client->Wrap(args.This()); 40 | return args.This(); 41 | } 42 | 43 | 44 | Handle Sqlite3Client::Open(const Arguments& args) { 45 | Sqlite3Client* client = ObjectWrap::Unwrap(args.This()); 46 | HandleScope scope; 47 | String::Utf8Value strPath(args[0]); 48 | ConnJob* connJob = new ConnJob(); 49 | #ifdef OS_WIN32 50 | connJob->path = encodeConv::CodingConv::s2ws(ToCString(strPath)); 51 | #elif defined OS_LINUX 52 | connJob->path = ToCString(strPath); 53 | #endif 54 | 55 | connJob->js_obj = Persistent::New(args[args.Length()-1]->ToObject()); 56 | connJob->pClient = client; 57 | connJob->main_async.data = connJob; 58 | uv_async_init(uv_default_loop(),&connJob->main_async,open_asyn_callback); 59 | //client->Ref(); 60 | //uv_queue_work(uv_default_loop(), &connJob->req, EIO_Open, (uv_after_work_cb)EIO_AfterOpen); 61 | uv_async_send(&connJob->main_async); 62 | 63 | return Undefined(); 64 | } 65 | 66 | HandleSqlite3Client::OpenSync(const Arguments& args) 67 | { 68 | Sqlite3Client* client = ObjectWrap::Unwrap(args.This()); 69 | HandleScope scope; 70 | Handle argv[1]; 71 | String::Utf8Value strPath(args[0]); 72 | TSTRING path; 73 | #ifdef OS_WIN32 74 | path = encodeConv::CodingConv::s2ws(ToCString(strPath)); 75 | #elif defined OS_LINUX 76 | path = ToCString(strPath); 77 | #endif 78 | CSqliteConn* pConn = new CSqliteConn(); 79 | bool bRet = pConn->OpenSqlite(path.c_str()); 80 | if (bRet) 81 | { 82 | Handle connection = Sqlite3Connection::constructorTemplate->GetFunction()->NewInstance(); 83 | (node::ObjectWrap::Unwrap(connection))->setConnection(pConn); 84 | argv[0] = connection; 85 | 86 | } 87 | else 88 | { 89 | delete pConn; 90 | argv[0]=Undefined(); 91 | 92 | 93 | } 94 | return scope.Close(argv[0]); 95 | 96 | } 97 | 98 | void Sqlite3Client::open_asyn_callback(uv_async_t* handle, int status) 99 | { 100 | 101 | Handle argv[2]; 102 | HandleScope scope; 103 | ConnJob* connJob = static_cast(handle->data); 104 | BOOL bRet = false; 105 | try 106 | { 107 | CSqliteConn* pConn = new CSqliteConn(); 108 | bRet = pConn->OpenSqlite(connJob->path.c_str()); 109 | if (false == bRet) 110 | { 111 | 112 | connJob->error = pConn->GetLastError(); 113 | if (pConn) 114 | { 115 | delete pConn; 116 | pConn = NULL; 117 | } 118 | 119 | #ifdef OS_WIN32 120 | //connJob->error = encodeConv::CodingConv::Unicode2Utf8(connJob->error.c_str()); 121 | argv[0] = String::New(encodeConv::CodingConv::Unicode2Utf8(connJob->error.c_str()).c_str()); 122 | #elif defined OS_LINUX 123 | 124 | argv[0] = String::New(connJob->error.c_str()); 125 | #endif 126 | argv[1] = Undefined(); 127 | 128 | 129 | 130 | } 131 | else 132 | { 133 | connJob->pConnect = pConn; 134 | argv[0] = Undefined(); 135 | Handle connection = Sqlite3Connection::constructorTemplate->GetFunction()->NewInstance(); 136 | (node::ObjectWrap::Unwrap(connection))->setConnection(connJob->pConnect); 137 | argv[1] = connection; 138 | 139 | } 140 | 141 | 142 | } 143 | catch(std::exception e) 144 | { 145 | 146 | cout<<__FILE__<<__LINE__<error = encodeConv::CodingConv::s2ws(e.what()); 149 | #elif defined OS_LINUX 150 | connJob->error = e.what(); 151 | #endif 152 | 153 | 154 | } 155 | v8::TryCatch tryCatch; 156 | connJob->js_obj->CallAsFunction(Object::New(),2,argv); 157 | if (tryCatch.HasCaught()) 158 | { 159 | node::FatalException(tryCatch); 160 | } 161 | connJob->js_obj.Dispose(); 162 | uv_close((uv_handle_t*)&connJob->main_async,NULL); 163 | delete connJob; 164 | connJob = NULL; 165 | 166 | scope.Close(Undefined()); 167 | 168 | } 169 | 170 | void Sqlite3Client::EIO_Open(uv_work_t* req) { 171 | ConnJob* connJob = static_cast(req->data); 172 | BOOL bRet = false; 173 | try 174 | { 175 | CSqliteConn* pConn = new CSqliteConn(); 176 | if (pConn == NULL) 177 | { 178 | 179 | throw ("new sqlite3 fail"); 180 | } 181 | bRet = pConn->OpenSqlite(connJob->path.c_str()); 182 | if (false == bRet) 183 | { 184 | 185 | connJob->error = pConn->GetLastError(); 186 | 187 | } 188 | else 189 | { 190 | connJob->pConnect = pConn; 191 | } 192 | 193 | 194 | } 195 | catch(std::exception e) 196 | { 197 | cout<<__FILE__<<__LINE__<error = encodeConv::CodingConv::s2ws(e.what()); 200 | #elif defined OS_LINUX 201 | connJob->error = e.what(); 202 | #endif 203 | 204 | 205 | } 206 | 207 | 208 | 209 | 210 | 211 | } 212 | 213 | void Sqlite3Client::EIO_AfterOpen(uv_work_t* req, int status) { 214 | HandleScope scope; 215 | ConnJob* connJob = static_cast(req->data); 216 | connJob->pClient->Unref(); 217 | Handle argv[2]; 218 | if(!connJob->error.empty()) 219 | { 220 | if (connJob->pConnect) 221 | { 222 | delete connJob->pConnect; 223 | connJob->pConnect = NULL; 224 | } 225 | 226 | #ifdef OS_WIN32 227 | //connJob->error = encodeConv::CodingConv::Unicode2Utf8(connJob->error.c_str()); 228 | argv[0] = String::New(encodeConv::CodingConv::Unicode2Utf8(connJob->error.c_str()).c_str()); 229 | #elif defined OS_LINUX 230 | 231 | argv[0] = String::New(connJob->error.c_str()); 232 | #endif 233 | argv[1] = Undefined(); 234 | } 235 | else 236 | { 237 | argv[0] = Undefined(); 238 | Handle connection = Sqlite3Connection::constructorTemplate->GetFunction()->NewInstance(); 239 | (node::ObjectWrap::Unwrap(connection))->setConnection(connJob->pConnect); 240 | argv[1] = connection; 241 | 242 | 243 | } 244 | 245 | v8::TryCatch tryCatch; 246 | connJob->js_obj->CallAsFunction(Object::New(),2,argv); 247 | if (tryCatch.HasCaught()) 248 | { 249 | node::FatalException(tryCatch); 250 | } 251 | connJob->js_obj.Dispose(); 252 | delete connJob; 253 | connJob = NULL; 254 | scope.Close(Undefined()); 255 | } 256 | 257 | extern "C" 258 | { 259 | static void init(Handle target) 260 | { 261 | Sqlite3Client::Init(target); 262 | Sqlite3Connection::Init(target); 263 | Statement::Init(target); 264 | 265 | } 266 | 267 | NODE_MODULE(node_sqlite3, init); 268 | } 269 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/codecext.c: -------------------------------------------------------------------------------- 1 | #ifndef SQLITE_OMIT_DISKIO 2 | #ifdef SQLITE_HAS_CODEC 3 | 4 | #include "codec.h" 5 | 6 | void sqlite3_activate_see(const char *info) 7 | { 8 | } 9 | 10 | /* 11 | // Free the encryption data structure associated with a pager instance. 12 | // (called from the modified code in pager.c) 13 | */ 14 | void sqlite3CodecFree(void *pCodecArg) 15 | { 16 | if (pCodecArg) 17 | { 18 | CodecTerm(pCodecArg); 19 | sqlite3_free(pCodecArg); 20 | } 21 | } 22 | 23 | void sqlite3CodecSizeChange(void *pArg, int pageSize, int reservedSize) 24 | { 25 | } 26 | 27 | /* 28 | // Encrypt/Decrypt functionality, called by pager.c 29 | */ 30 | void* sqlite3Codec(void* pCodecArg, void* data, Pgno nPageNum, int nMode) 31 | { 32 | Codec* codec = NULL; 33 | int pageSize; 34 | if (pCodecArg == NULL) 35 | { 36 | return data; 37 | } 38 | codec = (Codec*) pCodecArg; 39 | if (!CodecIsEncrypted(codec)) 40 | { 41 | return data; 42 | } 43 | 44 | pageSize = sqlite3BtreeGetPageSize(CodecGetBtree(codec)); 45 | 46 | switch(nMode) 47 | { 48 | case 0: /* Undo a "case 7" journal file encryption */ 49 | case 2: /* Reload a page */ 50 | case 3: /* Load a page */ 51 | if (CodecHasReadKey(codec)) 52 | { 53 | CodecDecrypt(codec, nPageNum, (unsigned char*) data, pageSize); 54 | } 55 | break; 56 | 57 | case 6: /* Encrypt a page for the main database file */ 58 | if (CodecHasWriteKey(codec)) 59 | { 60 | unsigned char* pageBuffer = CodecGetPageBuffer(codec); 61 | memcpy(pageBuffer, data, pageSize); 62 | data = pageBuffer; 63 | CodecEncrypt(codec, nPageNum, (unsigned char*) data, pageSize, 1); 64 | } 65 | break; 66 | 67 | case 7: /* Encrypt a page for the journal file */ 68 | /* Under normal circumstances, the readkey is the same as the writekey. However, 69 | when the database is being rekeyed, the readkey is not the same as the writekey. 70 | The rollback journal must be written using the original key for the 71 | database file because it is, by nature, a rollback journal. 72 | Therefore, for case 7, when the rollback is being written, always encrypt using 73 | the database's readkey, which is guaranteed to be the same key that was used to 74 | read the original data. 75 | */ 76 | if (CodecHasReadKey(codec)) 77 | { 78 | unsigned char* pageBuffer = CodecGetPageBuffer(codec); 79 | memcpy(pageBuffer, data, pageSize); 80 | data = pageBuffer; 81 | CodecEncrypt(codec, nPageNum, (unsigned char*) data, pageSize, 0); 82 | } 83 | break; 84 | } 85 | return data; 86 | } 87 | 88 | void* mySqlite3PagerGetCodec( 89 | Pager *pPager 90 | ); 91 | 92 | void mySqlite3PagerSetCodec( 93 | Pager *pPager, 94 | void *(*xCodec)(void*,void*,Pgno,int), 95 | void (*xCodecSizeChng)(void*,int,int), 96 | void (*xCodecFree)(void*), 97 | void *pCodec 98 | ); 99 | 100 | int sqlite3CodecAttach(sqlite3* db, int nDb, const void* zKey, int nKey) 101 | { 102 | /* Attach a key to a database. */ 103 | Codec* codec = (Codec*) sqlite3_malloc(sizeof(Codec)); 104 | CodecInit(codec); 105 | 106 | /* No key specified, could mean either use the main db's encryption or no encryption */ 107 | if (zKey == NULL || nKey <= 0) 108 | { 109 | /* No key specified */ 110 | if (nDb != 0 && nKey < 0) 111 | { 112 | Codec* mainCodec = (Codec*) mySqlite3PagerGetCodec(sqlite3BtreePager(db->aDb[0].pBt)); 113 | /* Attached database, therefore use the key of main database, if main database is encrypted */ 114 | if (mainCodec != NULL && CodecIsEncrypted(mainCodec)) 115 | { 116 | CodecCopy(codec, mainCodec); 117 | CodecSetBtree(codec, db->aDb[nDb].pBt); 118 | #if (SQLITE_VERSION_NUMBER >= 3006016) 119 | mySqlite3PagerSetCodec(sqlite3BtreePager(db->aDb[nDb].pBt), sqlite3Codec, sqlite3CodecSizeChange, sqlite3CodecFree, codec); 120 | #else 121 | #if (SQLITE_VERSION_NUMBER >= 3003014) 122 | sqlite3PagerSetCodec(sqlite3BtreePager(db->aDb[nDb].pBt), sqlite3Codec, codec); 123 | #else 124 | sqlite3pager_set_codec(sqlite3BtreePager(db->aDb[nDb].pBt), sqlite3Codec, codec); 125 | #endif 126 | db->aDb[nDb].pAux = codec; 127 | db->aDb[nDb].xFreeAux = sqlite3CodecFree; 128 | #endif 129 | } 130 | else 131 | { 132 | CodecSetIsEncrypted(codec, 0); 133 | sqlite3_free(codec); 134 | } 135 | } 136 | } 137 | else 138 | { 139 | /* Key specified, setup encryption key for database */ 140 | CodecSetIsEncrypted(codec, 1); 141 | CodecSetHasReadKey(codec, 1); 142 | CodecSetHasWriteKey(codec, 1); 143 | CodecGenerateReadKey(codec, (char*) zKey, nKey); 144 | CodecCopyKey(codec, 1); 145 | CodecSetBtree(codec, db->aDb[nDb].pBt); 146 | #if (SQLITE_VERSION_NUMBER >= 3006016) 147 | mySqlite3PagerSetCodec(sqlite3BtreePager(db->aDb[nDb].pBt), sqlite3Codec, sqlite3CodecSizeChange, sqlite3CodecFree, codec); 148 | #else 149 | #if (SQLITE_VERSION_NUMBER >= 3003014) 150 | sqlite3PagerSetCodec(sqlite3BtreePager(db->aDb[nDb].pBt), sqlite3Codec, codec); 151 | #else 152 | sqlite3pager_set_codec(sqlite3BtreePager(db->aDb[nDb].pBt), sqlite3Codec, codec); 153 | #endif 154 | db->aDb[nDb].pAux = codec; 155 | db->aDb[nDb].xFreeAux = sqlite3CodecFree; 156 | #endif 157 | } 158 | return SQLITE_OK; 159 | } 160 | 161 | void sqlite3CodecGetKey(sqlite3* db, int nDb, void** zKey, int* nKey) 162 | { 163 | /* 164 | // The unencrypted password is not stored for security reasons 165 | // therefore always return NULL 166 | */ 167 | *zKey = NULL; 168 | *nKey = -1; 169 | } 170 | 171 | int sqlite3_key(sqlite3 *db, const void *zKey, int nKey) 172 | { 173 | /* The key is only set for the main database, not the temp database */ 174 | return sqlite3CodecAttach(db, 0, zKey, nKey); 175 | } 176 | 177 | int sqlite3_rekey(sqlite3 *db, const void *zKey, int nKey) 178 | { 179 | /* Changes the encryption key for an existing database. */ 180 | int rc = SQLITE_ERROR; 181 | Btree* pbt = db->aDb[0].pBt; 182 | Pager* pPager = sqlite3BtreePager(pbt); 183 | Codec* codec = (Codec*) mySqlite3PagerGetCodec(pPager); 184 | 185 | if ((zKey == NULL || nKey == 0) && (codec == NULL || !CodecIsEncrypted(codec))) 186 | { 187 | /* 188 | // Database not encrypted and key not specified 189 | // therefore do nothing 190 | */ 191 | return SQLITE_OK; 192 | } 193 | 194 | if (codec == NULL || !CodecIsEncrypted(codec)) 195 | { 196 | /* 197 | // Database not encrypted, but key specified 198 | // therefore encrypt database 199 | */ 200 | if (codec == NULL) 201 | { 202 | codec = (Codec*) sqlite3_malloc(sizeof(Codec)); 203 | CodecInit(codec); 204 | } 205 | 206 | CodecSetIsEncrypted(codec, 1); 207 | CodecSetHasReadKey(codec, 0); /* Original database is not encrypted */ 208 | CodecSetHasWriteKey(codec, 1); 209 | CodecGenerateWriteKey(codec, (char*) zKey, nKey); 210 | CodecSetBtree(codec, pbt); 211 | #if (SQLITE_VERSION_NUMBER >= 3006016) 212 | mySqlite3PagerSetCodec(pPager, sqlite3Codec, sqlite3CodecSizeChange, sqlite3CodecFree, codec); 213 | #else 214 | #if (SQLITE_VERSION_NUMBER >= 3003014) 215 | sqlite3PagerSetCodec(pPager, sqlite3Codec, codec); 216 | #else 217 | sqlite3pager_set_codec(pPager, sqlite3Codec, codec); 218 | #endif 219 | db->aDb[0].pAux = codec; 220 | db->aDb[0].xFreeAux = sqlite3CodecFree; 221 | #endif 222 | } 223 | else if (zKey == NULL || nKey == 0) 224 | { 225 | /* 226 | // Database encrypted, but key not specified 227 | // therefore decrypt database 228 | // Keep read key, drop write key 229 | */ 230 | CodecSetHasWriteKey(codec, 0); 231 | } 232 | else 233 | { 234 | /* 235 | // Database encrypted and key specified 236 | // therefore re-encrypt database with new key 237 | // Keep read key, change write key to new key 238 | */ 239 | CodecGenerateWriteKey(codec, (char*) zKey, nKey); 240 | CodecSetHasWriteKey(codec, 1); 241 | } 242 | 243 | /* Start transaction */ 244 | rc = sqlite3BtreeBeginTrans(pbt, 1); 245 | if (!rc) 246 | { 247 | int pageSize = sqlite3BtreeGetPageSize(pbt); 248 | Pgno nSkip = WX_PAGER_MJ_PGNO(pageSize); 249 | #if (SQLITE_VERSION_NUMBER >= 3003014) 250 | DbPage *pPage; 251 | #else 252 | void *pPage; 253 | #endif 254 | Pgno n; 255 | /* Rewrite all pages using the new encryption key (if specified) */ 256 | #if (SQLITE_VERSION_NUMBER >= 3007001) 257 | Pgno nPage; 258 | int nPageCount = -1; 259 | sqlite3PagerPagecount(pPager, &nPageCount); 260 | nPage = nPageCount; 261 | #elif (SQLITE_VERSION_NUMBER >= 3006000) 262 | int nPageCount = -1; 263 | int rc = sqlite3PagerPagecount(pPager, &nPageCount); 264 | Pgno nPage = (Pgno) nPageCount; 265 | #elif (SQLITE_VERSION_NUMBER >= 3003014) 266 | Pgno nPage = sqlite3PagerPagecount(pPager); 267 | #else 268 | Pgno nPage = sqlite3pager_pagecount(pPager); 269 | #endif 270 | 271 | for (n = 1; rc == SQLITE_OK && n <= nPage; n++) 272 | { 273 | if (n == nSkip) continue; 274 | #if (SQLITE_VERSION_NUMBER >= 3003014) 275 | rc = sqlite3PagerGet(pPager, n, &pPage); 276 | #else 277 | rc = sqlite3pager_get(pPager, n, &pPage); 278 | #endif 279 | if (!rc) 280 | { 281 | #if (SQLITE_VERSION_NUMBER >= 3003014) 282 | rc = sqlite3PagerWrite(pPage); 283 | sqlite3PagerUnref(pPage); 284 | #else 285 | rc = sqlite3pager_write(pPage); 286 | sqlite3pager_unref(pPage); 287 | #endif 288 | } 289 | } 290 | } 291 | 292 | if (rc == SQLITE_OK) 293 | { 294 | /* Commit transaction if all pages could be rewritten */ 295 | rc = sqlite3BtreeCommit(pbt); 296 | } 297 | if (rc != SQLITE_OK) 298 | { 299 | /* Rollback in case of error */ 300 | sqlite3BtreeRollback(pbt); 301 | } 302 | 303 | if (rc == SQLITE_OK) 304 | { 305 | /* Set read key equal to write key if necessary */ 306 | if (CodecHasWriteKey(codec)) 307 | { 308 | CodecCopyKey(codec, 0); 309 | CodecSetHasReadKey(codec, 1); 310 | } 311 | else 312 | { 313 | CodecSetIsEncrypted(codec, 0); 314 | } 315 | } 316 | else 317 | { 318 | /* Restore write key if necessary */ 319 | if (CodecHasReadKey(codec)) 320 | { 321 | CodecCopyKey(codec, 1); 322 | } 323 | else 324 | { 325 | CodecSetIsEncrypted(codec, 0); 326 | } 327 | } 328 | 329 | if (!CodecIsEncrypted(codec)) 330 | { 331 | /* Remove codec for unencrypted database */ 332 | #if (SQLITE_VERSION_NUMBER >= 3006016) 333 | mySqlite3PagerSetCodec(pPager, NULL, NULL, NULL, NULL); 334 | #else 335 | #if (SQLITE_VERSION_NUMBER >= 3003014) 336 | sqlite3PagerSetCodec(pPager, NULL, NULL); 337 | #else 338 | sqlite3pager_set_codec(pPager, NULL, NULL); 339 | #endif 340 | db->aDb[0].pAux = NULL; 341 | db->aDb[0].xFreeAux = NULL; 342 | sqlite3CodecFree(codec); 343 | #endif 344 | } 345 | return rc; 346 | } 347 | 348 | #endif /* SQLITE_HAS_CODEC */ 349 | 350 | #endif /* SQLITE_OMIT_DISKIO */ 351 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3_def.h: -------------------------------------------------------------------------------- 1 | #ifndef _SQLITE3_UNICODE_AWARE_ 2 | #define _SQLITE3_UNICODE_AWARE_ 3 | 4 | #include "./sqlite3/sqlite3.h" 5 | #if defined(_UNICODE) || defined(UNICODE) 6 | #pragma message("Unicode Selected") 7 | #define _sqlite3_aggregate_context sqlite3_aggregate_context 8 | #define _sqlite3_aggregate_count sqlite3_aggregate_count 9 | #define _sqlite3_bind_blob sqlite3_bind_blob 10 | #define _sqlite3_bind_double sqlite3_bind_double 11 | #define _sqlite3_bind_int sqlite3_bind_int 12 | #define _sqlite3_bind_int64 sqlite3_bind_int64 13 | #define _sqlite3_bind_null sqlite3_bind_null 14 | #define _sqlite3_bind_parameter_count sqlite3_bind_parameter_count 15 | #define _sqlite3_bind_parameter_index sqlite3_bind_parameter_index 16 | #define _sqlite3_bind_parameter_name sqlite3_bind_parameter_name 17 | #define _sqlite3_bind_text sqlite3_bind_text16 18 | #define _sqlite3_bind_text16 sqlite3_bind_text16 19 | #define _sqlite3_busy_handler sqlite3_busy_handler 20 | #define _sqlite3_busy_timeout sqlite3_busy_timeout 21 | #define _sqlite3_changes sqlite3_changes 22 | #define _sqlite3_close sqlite3_close 23 | #define _sqlite3_collation_needed sqlite3_collation_needed16 24 | #define _sqlite3_collation_needed16 sqlite3_collation_needed16 25 | #define _sqlite3_column_blob sqlite3_column_blob 26 | #define _sqlite3_column_bytes sqlite3_column_bytes16 27 | #define _sqlite3_column_bytes16 sqlite3_column_bytes16 28 | #define _sqlite3_column_count sqlite3_column_count 29 | #define _sqlite3_column_decltype sqlite3_column_decltype16 30 | #define _sqlite3_column_decltype16 sqlite3_column_decltype16 31 | #define _sqlite3_column_double sqlite3_column_double 32 | #define _sqlite3_column_int sqlite3_column_int 33 | #define _sqlite3_column_int64 sqlite3_column_int64 34 | #define _sqlite3_column_name sqlite3_column_name16 35 | #define _sqlite3_column_name16 sqlite3_column_name16 36 | #define _sqlite3_column_text sqlite3_column_text16 37 | #define _sqlite3_column_text16 sqlite3_column_text16 38 | #define _sqlite3_column_type sqlite3_column_type 39 | #define _sqlite3_commit_hook sqlite3_commit_hook 40 | #define _sqlite3_complete sqlite3_complete16 41 | #define _sqlite3_complete16 sqlite3_complete16 42 | #define _sqlite3_create_collation sqlite3_create_collation16 43 | #define _sqlite3_create_collation16 sqlite3_create_collation16 44 | #define _sqlite3_create_function sqlite3_create_function16 45 | #define _sqlite3_create_function16 sqlite3_create_function16 46 | #define _sqlite3_data_count sqlite3_data_count 47 | #define _sqlite3_errcode sqlite3_errcode 48 | #define _sqlite3_errmsg sqlite3_errmsg16 49 | #define _sqlite3_errmsg16 sqlite3_errmsg16 50 | #define _sqlite3_exec sqlite3_exec 51 | #define _sqlite3_finalize sqlite3_finalize 52 | #define _sqlite3_free sqlite3_free 53 | #define _sqlite3_free_table sqlite3_free_table 54 | #define _sqlite3_get_table sqlite3_get_table 55 | #define _sqlite3_interrupt sqlite3_interrupt 56 | #define _sqlite3_last_insert_rowid sqlite3_last_insert_rowid 57 | #define _sqlite3_libversion sqlite3_libversion 58 | #define _sqlite3_mprintf sqlite3_mprintf 59 | #define _sqlite3_open sqlite3_open16 60 | #define _sqlite3_open16 sqlite3_open16 61 | #define _sqlite3_prepare sqlite3_prepare16 62 | #define _sqlite3_prepare16 sqlite3_prepare16 63 | #define _sqlite3_progress_handler sqlite3_progress_handler 64 | #define _sqlite3_reset sqlite3_reset 65 | #define _sqlite3_result_blob sqlite3_result_blob 66 | #define _sqlite3_result_double sqlite3_result_double 67 | #define _sqlite3_result_error sqlite3_result_error16 68 | #define _sqlite3_result_error16 sqlite3_result_error16 69 | #define _sqlite3_result_int sqlite3_result_int 70 | #define _sqlite3_result_int64 sqlite3_result_int64 71 | #define _sqlite3_result_null sqlite3_result_null 72 | #define _sqlite3_result_text sqlite3_result_text16 73 | #define _sqlite3_result_text16 sqlite3_result_text16 74 | #define _sqlite3_result_text16be sqlite3_result_text16be 75 | #define _sqlite3_result_text16le sqlite3_result_text16le 76 | #define _sqlite3_result_value sqlite3_result_value 77 | #define _sqlite3_set_authorizer sqlite3_set_authorizer 78 | #define _sqlite3_step sqlite3_step 79 | #define _sqlite3_total_changes sqlite3_total_changes 80 | #define _sqlite3_trace sqlite3_trace 81 | #define _sqlite3_user_data sqlite3_user_data 82 | #define _sqlite3_value_blob sqlite3_value_blob 83 | #define _sqlite3_value_bytes sqlite3_value_bytes16 84 | #define _sqlite3_value_bytes16 sqlite3_value_bytes16 85 | #define _sqlite3_value_double sqlite3_value_double 86 | #define _sqlite3_value_int sqlite3_value_int 87 | #define _sqlite3_value_int64 sqlite3_value_int64 88 | #define _sqlite3_value_text sqlite3_value_text16 89 | #define _sqlite3_value_text16 sqlite3_value_text16 90 | #define _sqlite3_value_text16be sqlite3_value_text16be 91 | #define _sqlite3_value_text16le sqlite3_value_text16le 92 | #define _sqlite3_value_type sqlite3_value_type 93 | #define _sqlite3_vmprintf sqlite3_vmprintf 94 | #else 95 | #pragma message("MCBS Selected") 96 | #define _sqlite3_aggregate_context sqlite3_aggregate_context 97 | #define _sqlite3_aggregate_count sqlite3_aggregate_count 98 | #define _sqlite3_bind_blob sqlite3_bind_blob 99 | #define _sqlite3_bind_double sqlite3_bind_double 100 | #define _sqlite3_bind_int sqlite3_bind_int 101 | #define _sqlite3_bind_int64 sqlite3_bind_int64 102 | #define _sqlite3_bind_null sqlite3_bind_null 103 | #define _sqlite3_bind_parameter_count sqlite3_bind_parameter_count 104 | #define _sqlite3_bind_parameter_index sqlite3_bind_parameter_index 105 | #define _sqlite3_bind_parameter_name sqlite3_bind_parameter_name 106 | #define _sqlite3_bind_text sqlite3_bind_text 107 | #define _sqlite3_bind_text16 sqlite3_bind_text16 108 | #define _sqlite3_busy_handler sqlite3_busy_handler 109 | #define _sqlite3_busy_timeout sqlite3_busy_timeout 110 | #define _sqlite3_changes sqlite3_changes 111 | #define _sqlite3_close sqlite3_close 112 | #define _sqlite3_collation_needed sqlite3_collation_needed 113 | #define _sqlite3_collation_needed16 sqlite3_collation_needed16 114 | #define _sqlite3_column_blob sqlite3_column_blob 115 | #define _sqlite3_column_bytes sqlite3_column_bytes 116 | #define _sqlite3_column_bytes16 sqlite3_column_bytes16 117 | #define _sqlite3_column_count sqlite3_column_count 118 | #define _sqlite3_column_decltype sqlite3_column_decltype 119 | #define _sqlite3_column_decltype16 sqlite3_column_decltype16 120 | #define _sqlite3_column_double sqlite3_column_double 121 | #define _sqlite3_column_int sqlite3_column_int 122 | #define _sqlite3_column_int64 sqlite3_column_int64 123 | #define _sqlite3_column_name sqlite3_column_name 124 | #define _sqlite3_column_name16 sqlite3_column_name16 125 | #define _sqlite3_column_text sqlite3_column_text 126 | #define _sqlite3_column_text16 sqlite3_column_text16 127 | #define _sqlite3_column_type sqlite3_column_type 128 | #define _sqlite3_commit_hook sqlite3_commit_hook 129 | #define _sqlite3_complete sqlite3_complete 130 | #define _sqlite3_complete16 sqlite3_complete16 131 | #define _sqlite3_create_collation sqlite3_create_collation 132 | #define _sqlite3_create_collation16 sqlite3_create_collation16 133 | #define _sqlite3_create_function sqlite3_create_function 134 | #define _sqlite3_create_function16 sqlite3_create_function16 135 | #define _sqlite3_data_count sqlite3_data_count 136 | #define _sqlite3_errcode sqlite3_errcode 137 | #define _sqlite3_errmsg sqlite3_errmsg 138 | #define _sqlite3_errmsg16 sqlite3_errmsg16 139 | #define _sqlite3_exec sqlite3_exec 140 | #define _sqlite3_finalize sqlite3_finalize 141 | #define _sqlite3_free sqlite3_free 142 | #define _sqlite3_free_table sqlite3_free_table 143 | #define _sqlite3_get_table sqlite3_get_table 144 | #define _sqlite3_interrupt sqlite3_interrupt 145 | #define _sqlite3_last_insert_rowid sqlite3_last_insert_rowid 146 | #define _sqlite3_libversion sqlite3_libversion 147 | #define _sqlite3_mprintf sqlite3_mprintf 148 | #define _sqlite3_open sqlite3_open 149 | #define _sqlite3_open16 sqlite3_open16 150 | #define _sqlite3_prepare sqlite3_prepare 151 | #define _sqlite3_prepare16 sqlite3_prepare16 152 | #define _sqlite3_progress_handler sqlite3_progress_handler 153 | #define _sqlite3_reset sqlite3_reset 154 | #define _sqlite3_result_blob sqlite3_result_blob 155 | #define _sqlite3_result_double sqlite3_result_double 156 | #define _sqlite3_result_error sqlite3_result_error 157 | #define _sqlite3_result_error16 sqlite3_result_error16 158 | #define _sqlite3_result_int sqlite3_result_int 159 | #define _sqlite3_result_int64 sqlite3_result_int64 160 | #define _sqlite3_result_null sqlite3_result_null 161 | #define _sqlite3_result_text sqlite3_result_text 162 | #define _sqlite3_result_text16 sqlite3_result_text16 163 | #define _sqlite3_result_text16be sqlite3_result_text16be 164 | #define _sqlite3_result_text16le sqlite3_result_text16le 165 | #define _sqlite3_result_value sqlite3_result_value 166 | #define _sqlite3_set_authorizer sqlite3_set_authorizer 167 | #define _sqlite3_step sqlite3_step 168 | #define _sqlite3_total_changes sqlite3_total_changes 169 | #define _sqlite3_trace sqlite3_trace 170 | #define _sqlite3_user_data sqlite3_user_data 171 | #define _sqlite3_value_blob sqlite3_value_blob 172 | #define _sqlite3_value_bytes sqlite3_value_bytes 173 | #define _sqlite3_value_bytes16 sqlite3_value_bytes16 174 | #define _sqlite3_value_double sqlite3_value_double 175 | #define _sqlite3_value_int sqlite3_value_int 176 | #define _sqlite3_value_int64 sqlite3_value_int64 177 | #define _sqlite3_value_text sqlite3_value_text 178 | #define _sqlite3_value_text16 sqlite3_value_text16 179 | #define _sqlite3_value_text16be sqlite3_value_text16be 180 | #define _sqlite3_value_text16le sqlite3_value_text16le 181 | #define _sqlite3_value_type sqlite3_value_type 182 | #define _sqlite3_vmprintf sqlite3_vmprintf 183 | #endif 184 | 185 | #endif 186 | -------------------------------------------------------------------------------- /src/nodejs/Sqlite3Connection.cpp: -------------------------------------------------------------------------------- 1 | #include "Sqlite3Connection.h" 2 | #include "QueryJob.h" 3 | #include "ExcuteJob.h" 4 | #include 5 | #include "NodeFunction.h" 6 | using namespace NodeFunc; 7 | 8 | 9 | 10 | Persistent Sqlite3Connection::constructorTemplate; 11 | 12 | void Sqlite3Connection::Init(Handle target) 13 | { 14 | HandleScope scope; 15 | Local t = FunctionTemplate::New(New); 16 | constructorTemplate = Persistent::New(t); 17 | constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1); 18 | constructorTemplate->SetClassName(String::NewSymbol("Connection")); 19 | 20 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "execute", Execute); 21 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate,"executesync",ExecuteSync); 22 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "close", Close); 23 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate,"getLastError",GetLastError); 24 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate,"begin",BeginTrans); 25 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "commit", CommitTrans); 26 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "rollback", RollbackTrans); 27 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "close", Close); 28 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "query", Query); 29 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate,"isopen",IsOpen); 30 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate,"enterkey",EnterKey); 31 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate,"changekey",ChangeKey); 32 | NODE_SET_PROTOTYPE_METHOD(constructorTemplate,"delkey",DelKey); 33 | target->Set(String::NewSymbol("Connection"), constructorTemplate->GetFunction()); 34 | } 35 | 36 | Handle Sqlite3Connection::New(const Arguments& args) 37 | { 38 | HandleScope scope; 39 | 40 | Sqlite3Connection *pConn = new Sqlite3Connection(); 41 | pConn->Wrap(args.This()); 42 | return args.This(); 43 | } 44 | 45 | Sqlite3Connection::Sqlite3Connection() 46 | { 47 | } 48 | 49 | Sqlite3Connection::~Sqlite3Connection() 50 | { 51 | closeConnection(); 52 | } 53 | 54 | 55 | 56 | HandleSqlite3Connection::ExecuteSync(const Arguments& args) 57 | { 58 | TSTRING sql = MergeSql(args); 59 | Sqlite3Connection *pConn = ObjectWrap::Unwrap(args.This()); 60 | HandleScope scope; 61 | BOOL bRet = pConn->m_pConn->Excute(sql.c_str()); 62 | return scope.Close(Boolean::New(bRet)); 63 | 64 | } 65 | 66 | HandleSqlite3Connection::Execute(const Arguments& args) 67 | { 68 | TSTRING sql = MergeSql(args); 69 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 70 | ExcuteJob* excute_job = new ExcuteJob(); 71 | excute_job->sql = sql; 72 | excute_job->pClient = connection; 73 | excute_job->js_obj = Persistent::New(args[args.Length()-1]->ToObject()); 74 | excute_job->type = excute_job->EXCUTE; 75 | excute_job->req.data = excute_job; 76 | //uv_async_init(uv_default_loop(),&excute_job->main_async,excute_asyn_callback); 77 | connection->Ref(); 78 | uv_queue_work(uv_default_loop(),&excute_job->req,uv_execute,uv_execute_after); 79 | //uv_async_send(&excute_job->main_async); 80 | return Undefined(); 81 | 82 | } 83 | void Sqlite3Connection::uv_execute(uv_work_t* req) 84 | { 85 | ExcuteJob* excute_job = static_cast(req->data); 86 | BOOL bret = excute_job->pClient->m_pConn->Excute(excute_job->sql.c_str()); 87 | if (FALSE == bret) 88 | { 89 | excute_job->error = excute_job->pClient->m_pConn->GetLastError(); 90 | 91 | } 92 | 93 | } 94 | void Sqlite3Connection::uv_execute_after(uv_work_t* req,int status) 95 | { 96 | ExcuteJob* excute_job = static_cast(req->data); 97 | excute_job->pClient->Unref(); 98 | HandleScope scope; 99 | Handle argv[1]; 100 | if (!excute_job->error.empty()) 101 | { 102 | #ifdef OS_WIN32 103 | argv[0] = String::New(encodeConv::CodingConv::Unicode2Utf8(excute_job->error.c_str()).c_str()); 104 | #elif defined OS_LINUX 105 | argv[0] = String::New(excute_job->error.c_str()); 106 | #endif 107 | 108 | } 109 | else 110 | { 111 | argv[0] = Undefined(); 112 | } 113 | v8::TryCatch tryCatch; 114 | excute_job->js_obj->CallAsFunction(Object::New(),1,argv); 115 | if (tryCatch.HasCaught()) 116 | { 117 | node::FatalException(tryCatch); 118 | } 119 | excute_job->js_obj.Dispose(); 120 | delete excute_job; 121 | excute_job = NULL; 122 | scope.Close(Undefined()); 123 | } 124 | void Sqlite3Connection::excute_asyn_callback(uv_async_t* handle, int status) 125 | { 126 | /* 127 | 128 | Handle argv[1]; 129 | HandleScope scope; 130 | 131 | BOOL bRet = false; 132 | ExcuteJob* excute_job = static_cast(handle->data); 133 | 134 | 135 | switch(excute_job->type) 136 | { 137 | case excute_job->BEGIN: 138 | bRet = excute_job->pClient->m_pConn->BeginTrans(); 139 | break; 140 | case excute_job->COMMIT: 141 | bRet = excute_job->pClient->m_pConn->CommitTrans(); 142 | break; 143 | case excute_job->ROLLBACK: 144 | bRet = excute_job->pClient->m_pConn->RollbackTrans(); 145 | break; 146 | ; 147 | case excute_job->CLOSE: 148 | bRet = excute_job->pClient->m_pConn->CloseSqlite(); 149 | break; 150 | default: 151 | excute_job->error = _T("unknow type"); 152 | } 153 | if (false == bRet) 154 | { 155 | #ifdef OS_WIN32 156 | argv[0] = String::New(encodeConv::CodingConv::Unicode2Utf8(excute_job->pClient->m_pConn->GetLastError().c_str()).c_str()); 157 | #elif defined OS_LINUX 158 | argv[0] = String::New(query_job->pConn->GetLastError().c_str()); 159 | #endif 160 | 161 | } 162 | else 163 | { 164 | argv[0] = Undefined(); 165 | } 166 | v8::TryCatch tryCatch; 167 | excute_job->js_obj->CallAsFunction(Object::New(),1,argv); 168 | if (tryCatch.HasCaught()) 169 | { 170 | node::FatalException(tryCatch); 171 | } 172 | excute_job->js_obj.Dispose(); 173 | 174 | uv_close((uv_handle_t*)&excute_job->main_async,NULL); 175 | cout<<"close"<Sqlite3Connection::BeginTrans(const Arguments& args) 182 | { 183 | Sqlite3Connection *pConn = ObjectWrap::Unwrap(args.This()); 184 | HandleScope scope; 185 | BOOL bRet = pConn->m_pConn->BeginTrans(); 186 | return scope.Close(Boolean::New(bRet)); 187 | //ExcuteJob* excute_job = new ExcuteJob(); 188 | //excute_job->js_obj = Persistent::New(args[args.Length()-1]->ToObject()); 189 | //excute_job->pClient = pConn; 190 | //excute_job->main_async.data = excute_job; 191 | //excute_job->type = excute_job->BEGIN; 192 | //uv_async_init(uv_default_loop(),&excute_job->main_async,excute_asyn_callback); 193 | //uv_async_send(&excute_job->main_async); 194 | //return Undefined(); 195 | 196 | } 197 | 198 | HandleSqlite3Connection::RollbackTrans(const Arguments& args) 199 | { 200 | Sqlite3Connection *pConn = ObjectWrap::Unwrap(args.This()); 201 | HandleScope scope; 202 | BOOL bRet = pConn->m_pConn->RollbackTrans(); 203 | return scope.Close(Boolean::New(bRet)); 204 | /* ExcuteJob* excute_job = new ExcuteJob(); 205 | excute_job->js_obj = Persistent::New(args[args.Length()-1]->ToObject()); 206 | excute_job->pClient = pConn; 207 | excute_job->main_async.data = excute_job; 208 | excute_job->type = excute_job->ROLLBACK; 209 | uv_async_init(uv_default_loop(),&excute_job->main_async,excute_asyn_callback); 210 | uv_async_send(&excute_job->main_async); 211 | return Undefined();*/ 212 | 213 | } 214 | HandleSqlite3Connection::CommitTrans(const Arguments& args) 215 | { 216 | Sqlite3Connection *pConn = ObjectWrap::Unwrap(args.This()); 217 | HandleScope scope; 218 | BOOL bRet = pConn->m_pConn->CommitTrans(); 219 | return scope.Close(Boolean::New(bRet)); 220 | /* ExcuteJob* excute_job = new ExcuteJob(); 221 | excute_job->js_obj = Persistent::New(args[args.Length()-1]->ToObject()); 222 | excute_job->pClient = pConn;; 223 | excute_job->main_async.data = excute_job; 224 | excute_job->type = excute_job->COMMIT; 225 | uv_async_init(uv_default_loop(),&excute_job->main_async,excute_asyn_callback); 226 | uv_async_send(&excute_job->main_async); 227 | return Undefined();*/ 228 | 229 | } 230 | //HandleSqlite3Connection::Close(const Arguments& args) 231 | //{ 232 | // Sqlite3Connection *pConn = ObjectWrap::Unwrap(args.This()); 233 | // ExcuteJob* excute_job = new ExcuteJob(); 234 | // excute_job->js_obj = Persistent::New(args[args.Length()-1]->ToObject()); 235 | // excute_job->pConn = pConn->m_pConn; 236 | // excute_job->main_async.data = excute_job; 237 | // excute_job->type = excute_job->CLOSE; 238 | // uv_async_init(uv_default_loop(),&excute_job->main_async,excute_asyn_callback); 239 | // uv_async_send(&excute_job->main_async); 240 | // return Undefined(); 241 | 242 | //} 243 | HandleSqlite3Connection::Query(const Arguments& args) 244 | { 245 | TSTRING sql = MergeSql(args); 246 | 247 | HandleScope scope; 248 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 249 | QueryJob* queryjob = new QueryJob(); 250 | queryjob->sql = sql; 251 | queryjob->js_obj =Persistent::New(args[args.Length()-1]->ToObject()); 252 | queryjob->pClient = connection; 253 | connection->Ref(); 254 | queryjob->work_pool.data = queryjob; 255 | uv_queue_work(uv_default_loop(),&queryjob->work_pool,uv_query,uv_query_after); 256 | return Undefined(); 257 | 258 | 259 | } 260 | 261 | void Sqlite3Connection::uv_query(uv_work_t* req) 262 | { 263 | QueryJob* query_job = static_cast(req->data); 264 | BOOL bRet = FALSE; 265 | try 266 | { 267 | 268 | CSqliteRecordsetPtr ptr = query_job->pClient->m_pConn->Query(query_job->sql.c_str(),bRet); 269 | if (bRet == FALSE) 270 | { 271 | query_job->error = query_job->pClient->m_pConn->GetLastError(); 272 | return; 273 | } 274 | query_job->ptr = ptr; 275 | } 276 | catch(std::exception e) 277 | { 278 | cout<<"exception"<(req->data); 287 | Handleargv[2]; 288 | HandleScope scope; 289 | query_job->pClient->Unref(); 290 | 291 | if (!query_job->error.empty()) // error 292 | { 293 | #ifdef OS_WIN32 294 | //connJob->error = encodeConv::CodingConv::Unicode2Utf8(connJob->error.c_str()); 295 | argv[0] = String::New(encodeConv::CodingConv::Unicode2Utf8(query_job->error.c_str()).c_str()); 296 | #elif defined OS_LINUX 297 | 298 | argv[0] = String::New(query_job->error.c_str()); 299 | #endif 300 | 301 | argv[1] = Undefined(); 302 | 303 | } 304 | else 305 | { 306 | argv[0] = Undefined(); 307 | Handle statement = Statement::s_ct->GetFunction()->NewInstance(); 308 | (node::ObjectWrap::Unwrap(statement))->SetRecordsetPtr(query_job->ptr); 309 | argv[1] = statement; 310 | 311 | } 312 | 313 | v8::TryCatch tryCatch; 314 | query_job->js_obj->CallAsFunction(Object::New(),2,argv); 315 | if (tryCatch.HasCaught()) 316 | { 317 | node::FatalException(tryCatch); 318 | } 319 | query_job->js_obj.Dispose(); 320 | delete query_job; 321 | query_job = NULL; 322 | 323 | 324 | 325 | } 326 | void Sqlite3Connection::query_asyn_thread_work_histroy(void* arg) 327 | { 328 | QueryJob* query_job = static_cast(arg); 329 | //uv_sem_wait(&sem); 330 | //query_job->queryHistoryTricks(query_job); 331 | //uv_sem_post(&sem); 332 | query_job->main_async.data = query_job; 333 | uv_async_send(&query_job->main_async); 334 | 335 | } 336 | 337 | 338 | 339 | void Sqlite3Connection::query_asyn_thread_callback(uv_async_t* req,int status) 340 | { 341 | HandleScope scope; 342 | QueryJob* query_job = static_cast(req->data); 343 | Localargv[2]; 344 | if(query_job->error !=_T("")) 345 | { 346 | //#ifdef OS_WIN32 347 | // argv[0] = String::New(encodeConv::CodingConv::ascii2Utf8(query_job->error.c_str()).c_str()); 348 | //#else 349 | // argv[0] = String::New(query_job->error.c_str()); 350 | //#endif 351 | 352 | #ifdef OS_WIN32 353 | //connJob->error = encodeConv::CodingConv::Unicode2Utf8(connJob->error.c_str()); 354 | argv[0] = String::New(encodeConv::CodingConv::Unicode2Utf8(query_job->error.c_str()).c_str()); 355 | #elif defined OS_LINUX 356 | 357 | argv[0] = String::New(query_job->error.c_str()); 358 | #endif 359 | argv[1] = *Undefined(); 360 | 361 | 362 | } 363 | else{ 364 | //vector >&result = query_job->result; 365 | //typedef vector >::iterator const_it; 366 | //Localarray = Array::New(result.size()); 367 | //int j = 0; 368 | //for (const_it it = result.begin();it != result.end();++it) 369 | //{ 370 | 371 | // map::iterator map_it; 372 | // Localobj = Object::New(); 373 | // for (map_it =it->begin();map_it!= it->end();++map_it) 374 | // { 375 | // //cout<first<<":"<second<Set(String::NewSymbol(map_it->first.c_str()), 377 | // String::New(encodeConv::CodingConv::ascii2Utf8(map_it->second.c_str()).c_str())); 378 | 379 | // } 380 | // array->Set(j,obj); 381 | // j++; 382 | //} 383 | 384 | 385 | argv[0]=*Undefined(); 386 | #ifdef OS_WIN32 387 | //cout<<"win 32"<result<error.c_str()).c_str()); 389 | #elif defined OS_LINUX 390 | argv[1] = String::New(query_job->error.c_str()); 391 | #endif 392 | 393 | 394 | 395 | 396 | } 397 | query_job->js_obj->CallAsFunction(Object::New(),2,argv); 398 | query_job->js_obj.Dispose(); 399 | uv_close((uv_handle_t*)&query_job->main_async,uv_close_func); 400 | 401 | scope.Close(Undefined()); 402 | 403 | } 404 | 405 | void Sqlite3Connection::uv_close_func(uv_handle_t* handle) 406 | { 407 | 408 | QueryJob* job_ptr= (QueryJob *)handle->data; 409 | delete job_ptr; 410 | job_ptr = NULL; 411 | 412 | }; 413 | 414 | Handle Sqlite3Connection::Close(const Arguments& args) 415 | { 416 | try 417 | { 418 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 419 | 420 | connection->closeConnection(); 421 | 422 | return Undefined(); 423 | } 424 | catch (const std::exception& ex) 425 | { 426 | cout<Sqlite3Connection::IsOpen(const Arguments& args) 431 | { 432 | HandleScope scope; 433 | BOOL bRet ; 434 | try 435 | { 436 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 437 | if (connection->m_pConn == NULL) //close 时候会delete m_pConn 438 | { 439 | bRet = FALSE; 440 | } 441 | else 442 | { 443 | bRet = connection->m_pConn->IsOpen(); 444 | } 445 | 446 | } 447 | 448 | catch (const std::exception& ex) 449 | { 450 | cout<Sqlite3Connection::EnterKey(const Arguments& args) 460 | { 461 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 462 | HandleScope scope; 463 | String::Utf8Value strPath(args[0]); 464 | const char* key = ToCString(strPath); 465 | BOOL bRet = connection->m_pConn->EnterKey(key); 466 | return scope.Close(Boolean::New(bRet)); 467 | 468 | } 469 | HandleSqlite3Connection::DelKey(const Arguments& args) 470 | { 471 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 472 | HandleScope scope; 473 | BOOL bRet = connection->m_pConn->DelKey(); 474 | return scope.Close(Boolean::New(bRet)); 475 | 476 | } 477 | HandleSqlite3Connection::ChangeKey(const Arguments& args) 478 | { 479 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 480 | HandleScope scope; 481 | String::Utf8Value strPath(args[0]); 482 | const char* key = ToCString(strPath); 483 | BOOL bRet = connection->m_pConn->ChangeKey(key); 484 | return scope.Close(Boolean::New(bRet)); 485 | } 486 | HandleSqlite3Connection::GetLastError(const Arguments& args) 487 | { 488 | Sqlite3Connection* connection = ObjectWrap::Unwrap(args.This()); 489 | HandleScope scope; 490 | TSTRING error = connection->m_pConn->GetLastError(); 491 | if (error.empty()) 492 | { 493 | return Undefined(); 494 | } 495 | else 496 | { 497 | #ifdef OS_WIN32 498 | return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(error.c_str()).c_str())); 499 | #elif defined OS_LINUX 500 | return scope.Close(String::New(error.c_str())); 501 | #endif 502 | } 503 | 504 | 505 | } 506 | void Sqlite3Connection::setConnection(CSqliteConn* connection) 507 | { 508 | 509 | m_pConn = connection; 510 | } 511 | 512 | 513 | void Sqlite3Connection::closeConnection() { 514 | 515 | 516 | if( m_pConn) 517 | { 518 | m_pConn->CloseSqlite(); 519 | delete m_pConn; 520 | m_pConn = NULL; 521 | 522 | } 523 | 524 | 525 | } 526 | 527 | 528 | 529 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/codec.c: -------------------------------------------------------------------------------- 1 | /* 2 | /////////////////////////////////////////////////////////////////////////////// 3 | /////////////////////////////////////////////////////////////////////////////// 4 | // Name: codec.cpp 5 | // Purpose: 6 | // Author: Ulrich Telle 7 | // Modified by: 8 | // Created: 2006-12-06 9 | // RCS-ID: $$ 10 | // Copyright: (c) Ulrich Telle 11 | // Licence: wxWindows licence + RSA Data Security license 12 | /////////////////////////////////////////////////////////////////////////////// 13 | 14 | /// \file codec.cpp Implementation of MD5, RC4 and AES algorithms 15 | */ 16 | /* 17 | ********************************************************************** 18 | ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. ** 19 | ** ** 20 | ** License to copy and use this software is granted provided that ** 21 | ** it is identified as the "RSA Data Security, Inc. MD5 Message ** 22 | ** Digest Algorithm" in all material mentioning or referencing this ** 23 | ** software or this function. ** 24 | ** ** 25 | ** License is also granted to make and use derivative works ** 26 | ** provided that such works are identified as "derived from the RSA ** 27 | ** Data Security, Inc. MD5 Message Digest Algorithm" in all ** 28 | ** material mentioning or referencing the derived work. ** 29 | ** ** 30 | ** RSA Data Security, Inc. makes no representations concerning ** 31 | ** either the merchantability of this software or the suitability ** 32 | ** of this software for any particular purpose. It is provided "as ** 33 | ** is" without express or implied warranty of any kind. ** 34 | ** ** 35 | ** These notices must be retained in any copies of any part of this ** 36 | ** documentation and/or software. ** 37 | ********************************************************************** 38 | */ 39 | 40 | #include "codec.h" 41 | 42 | #if CODEC_TYPE == CODEC_TYPE_AES256 43 | #include "sha2.h" 44 | #include "sha2.c" 45 | #endif 46 | 47 | /* 48 | // ---------------- 49 | // MD5 by RSA 50 | // ---------------- 51 | 52 | // C headers for MD5 53 | */ 54 | #include 55 | #include 56 | #include 57 | #include 58 | 59 | #define MD5_HASHBYTES 16 60 | 61 | /* 62 | /// Structure representing an MD5 context while ecrypting. (For internal use only) 63 | */ 64 | typedef struct MD5Context 65 | { 66 | unsigned int buf[4]; 67 | unsigned int bits[2]; 68 | unsigned char in[64]; 69 | } MD5_CTX; 70 | 71 | static void MD5Init(MD5_CTX *context); 72 | static void MD5Update(MD5_CTX *context, unsigned char *buf, unsigned len); 73 | static void MD5Final(unsigned char digest[MD5_HASHBYTES], MD5_CTX *context); 74 | static void MD5Transform(unsigned int buf[4], unsigned int in[16]); 75 | 76 | static void byteReverse(unsigned char *buf, unsigned longs); 77 | 78 | /* 79 | * Note: this code is harmless on little-endian machines. 80 | */ 81 | static void byteReverse(unsigned char *buf, unsigned longs) 82 | { 83 | static int littleEndian = -1; 84 | if (littleEndian < 0) 85 | { 86 | /* Are we little or big endian? This method is from Harbison & Steele. */ 87 | union 88 | { 89 | long l; 90 | char c[sizeof(long)]; 91 | } u; 92 | u.l = 1; 93 | littleEndian = (u.c[0] == 1) ? 1 : 0; 94 | } 95 | 96 | if (littleEndian != 1) 97 | { 98 | unsigned int t; 99 | do 100 | { 101 | t = (unsigned int) ((unsigned) buf[3] << 8 | buf[2]) << 16 | 102 | ((unsigned) buf[1] << 8 | buf[0]); 103 | *(unsigned int *) buf = t; 104 | buf += 4; 105 | } 106 | while (--longs); 107 | } 108 | } 109 | 110 | #if 0 111 | static char* MD5End(MD5_CTX *, char *); 112 | 113 | static char* MD5End(MD5_CTX *ctx, char *buf) 114 | { 115 | int i; 116 | unsigned char digest[MD5_HASHBYTES]; 117 | char hex[]="0123456789abcdef"; 118 | 119 | if (!buf) 120 | { 121 | buf = (char *)malloc(33); 122 | } 123 | 124 | if (!buf) 125 | { 126 | return 0; 127 | } 128 | 129 | MD5Final(digest,ctx); 130 | for (i=0;i> 4]; 133 | buf[i+i+1] = hex[digest[i] & 0x0f]; 134 | } 135 | buf[i+i] = '\0'; 136 | return buf; 137 | } 138 | #endif 139 | 140 | /* 141 | * Final wrapup - pad to 64-byte boundary with the bit pattern 142 | * 1 0* (64-bit count of bits processed, MSB-first) 143 | */ 144 | static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) 145 | { 146 | unsigned count; 147 | unsigned char *p; 148 | 149 | /* Compute number of bytes mod 64 */ 150 | count = (ctx->bits[0] >> 3) & 0x3F; 151 | 152 | /* Set the first char of padding to 0x80. This is safe since there is 153 | always at least one byte free */ 154 | p = ctx->in + count; 155 | *p++ = 0x80; 156 | 157 | /* Bytes of padding needed to make 64 bytes */ 158 | count = 64 - 1 - count; 159 | 160 | /* Pad out to 56 mod 64 */ 161 | if (count < 8) 162 | { 163 | /* Two lots of padding: Pad the first block to 64 bytes */ 164 | memset(p, 0, count); 165 | byteReverse(ctx->in, 16); 166 | MD5Transform(ctx->buf, (unsigned int *) ctx->in); 167 | 168 | /* Now fill the next block with 56 bytes */ 169 | memset(ctx->in, 0, 56); 170 | } 171 | else 172 | { 173 | /* Pad block to 56 bytes */ 174 | memset(p, 0, count - 8); 175 | } 176 | byteReverse(ctx->in, 14); 177 | 178 | /* Append length in bits and transform */ 179 | ((unsigned int *) ctx->in)[14] = ctx->bits[0]; 180 | ((unsigned int *) ctx->in)[15] = ctx->bits[1]; 181 | 182 | MD5Transform(ctx->buf, (unsigned int *) ctx->in); 183 | byteReverse((unsigned char *) ctx->buf, 4); 184 | memcpy(digest, ctx->buf, 16); 185 | memset((char *) ctx, 0, sizeof(ctx)); /* In case it's sensitive */ 186 | } 187 | 188 | static void MD5Init(MD5_CTX *ctx) 189 | { 190 | ctx->buf[0] = 0x67452301; 191 | ctx->buf[1] = 0xefcdab89; 192 | ctx->buf[2] = 0x98badcfe; 193 | ctx->buf[3] = 0x10325476; 194 | 195 | ctx->bits[0] = 0; 196 | ctx->bits[1] = 0; 197 | } 198 | 199 | static void MD5Update(MD5_CTX *ctx, unsigned char *buf, unsigned len) 200 | { 201 | unsigned int t; 202 | 203 | /* Update bitcount */ 204 | 205 | t = ctx->bits[0]; 206 | if ((ctx->bits[0] = t + ((unsigned int) len << 3)) < t) 207 | { 208 | ctx->bits[1]++; /* Carry from low to high */ 209 | } 210 | ctx->bits[1] += len >> 29; 211 | 212 | t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ 213 | 214 | /* Handle any leading odd-sized chunks */ 215 | 216 | if (t) 217 | { 218 | unsigned char *p = (unsigned char *) ctx->in + t; 219 | 220 | t = 64 - t; 221 | if (len < t) 222 | { 223 | memcpy(p, buf, len); 224 | return; 225 | } 226 | memcpy(p, buf, t); 227 | byteReverse(ctx->in, 16); 228 | MD5Transform(ctx->buf, (unsigned int *) ctx->in); 229 | buf += t; 230 | len -= t; 231 | } 232 | /* Process data in 64-byte chunks */ 233 | 234 | while (len >= 64) 235 | { 236 | memcpy(ctx->in, buf, 64); 237 | byteReverse(ctx->in, 16); 238 | MD5Transform(ctx->buf, (unsigned int *) ctx->in); 239 | buf += 64; 240 | len -= 64; 241 | } 242 | 243 | /* Handle any remaining bytes of data. */ 244 | 245 | memcpy(ctx->in, buf, len); 246 | } 247 | 248 | 249 | /* #define F1(x, y, z) (x & y | ~x & z) */ 250 | #define F1(x, y, z) (z ^ (x & (y ^ z))) 251 | #define F2(x, y, z) F1(z, x, y) 252 | #define F3(x, y, z) (x ^ y ^ z) 253 | #define F4(x, y, z) (y ^ (x | ~z)) 254 | 255 | /* This is the central step in the MD5 algorithm. */ 256 | #define MD5STEP(f, w, x, y, z, data, s) \ 257 | ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) 258 | 259 | /* 260 | * The core of the MD5 algorithm, this alters an existing MD5 hash to 261 | * reflect the addition of 16 longwords of new data. MD5Update blocks 262 | * the data and converts bytes into longwords for this routine. 263 | */ 264 | static void MD5Transform(unsigned int buf[4], unsigned int in[16]) 265 | { 266 | register unsigned int a, b, c, d; 267 | 268 | a = buf[0]; 269 | b = buf[1]; 270 | c = buf[2]; 271 | d = buf[3]; 272 | 273 | MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); 274 | MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); 275 | MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); 276 | MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); 277 | MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); 278 | MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); 279 | MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); 280 | MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); 281 | MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); 282 | MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); 283 | MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); 284 | MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); 285 | MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); 286 | MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); 287 | MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); 288 | MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); 289 | 290 | MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); 291 | MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); 292 | MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); 293 | MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); 294 | MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); 295 | MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); 296 | MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); 297 | MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); 298 | MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); 299 | MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); 300 | MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); 301 | MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); 302 | MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); 303 | MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); 304 | MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); 305 | MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); 306 | 307 | MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); 308 | MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); 309 | MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); 310 | MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); 311 | MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); 312 | MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); 313 | MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); 314 | MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); 315 | MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); 316 | MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); 317 | MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); 318 | MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); 319 | MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); 320 | MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); 321 | MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); 322 | MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); 323 | 324 | MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); 325 | MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); 326 | MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); 327 | MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); 328 | MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); 329 | MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); 330 | MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); 331 | MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); 332 | MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); 333 | MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); 334 | MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); 335 | MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); 336 | MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); 337 | MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); 338 | MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); 339 | MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); 340 | 341 | buf[0] += a; 342 | buf[1] += b; 343 | buf[2] += c; 344 | buf[3] += d; 345 | } 346 | 347 | /* 348 | // --------------------------- 349 | // RC4 implementation 350 | // --------------------------- 351 | */ 352 | 353 | /** 354 | * RC4 is the standard encryption algorithm used in PDF format 355 | */ 356 | 357 | void 358 | CodecRC4(Codec* codec, unsigned char* key, int keylen, 359 | unsigned char* textin, int textlen, 360 | unsigned char* textout) 361 | { 362 | int i; 363 | int j; 364 | int t; 365 | unsigned char rc4[256]; 366 | 367 | int a = 0; 368 | int b = 0; 369 | unsigned char k; 370 | 371 | for (i = 0; i < 256; i++) 372 | { 373 | rc4[i] = i; 374 | } 375 | j = 0; 376 | for (i = 0; i < 256; i++) 377 | { 378 | t = rc4[i]; 379 | j = (j + t + key[i % keylen]) % 256; 380 | rc4[i] = rc4[j]; 381 | rc4[j] = t; 382 | } 383 | 384 | for (i = 0; i < textlen; i++) 385 | { 386 | a = (a + 1) % 256; 387 | t = rc4[a]; 388 | b = (b + t) % 256; 389 | rc4[a] = rc4[b]; 390 | rc4[b] = t; 391 | k = rc4[(rc4[a] + rc4[b]) % 256]; 392 | textout[i] = textin[i] ^ k; 393 | } 394 | } 395 | 396 | void 397 | CodecGetMD5Binary(Codec* codec, unsigned char* data, int length, unsigned char* digest) 398 | { 399 | MD5_CTX ctx; 400 | MD5Init(&ctx); 401 | MD5Update(&ctx, data, length); 402 | MD5Final(digest,&ctx); 403 | } 404 | 405 | #if CODEC_TYPE == CODEC_TYPE_AES256 406 | void 407 | CodecGetSHABinary(Codec* codec, unsigned char* data, int length, unsigned char* digest) 408 | { 409 | sha256(data, (unsigned int) length, digest); 410 | } 411 | #endif 412 | 413 | #define MODMULT(a, b, c, m, s) q = s / a; s = b * (s - a * q) - c * q; if (s < 0) s += m 414 | 415 | void 416 | CodecGenerateInitialVector(Codec* codec, int seed, unsigned char iv[16]) 417 | { 418 | unsigned char initkey[16]; 419 | int j, q; 420 | int z = seed + 1; 421 | for (j = 0; j < 4; j++) 422 | { 423 | MODMULT(52774, 40692, 3791, 2147483399L, z); 424 | initkey[4*j+0] = 0xff & z; 425 | initkey[4*j+1] = 0xff & (z >> 8); 426 | initkey[4*j+2] = 0xff & (z >> 16); 427 | initkey[4*j+3] = 0xff & (z >> 24); 428 | } 429 | CodecGetMD5Binary(codec, (unsigned char*) initkey, 16, iv); 430 | } 431 | 432 | void 433 | CodecAES(Codec* codec, int page, int encrypt, unsigned char encryptionKey[KEYLENGTH], 434 | unsigned char* datain, int datalen, unsigned char* dataout) 435 | { 436 | unsigned char initial[16]; 437 | unsigned char pagekey[KEYLENGTH]; 438 | unsigned char nkey[KEYLENGTH+4+4]; 439 | int keyLength = KEYLENGTH; 440 | int nkeylen = keyLength + 4 + 4; 441 | int j; 442 | int direction = (encrypt) ? RIJNDAEL_Direction_Encrypt : RIJNDAEL_Direction_Decrypt; 443 | int len = 0; 444 | 445 | for (j = 0; j < keyLength; j++) 446 | { 447 | nkey[j] = encryptionKey[j]; 448 | } 449 | nkey[keyLength+0] = 0xff & page; 450 | nkey[keyLength+1] = 0xff & (page >> 8); 451 | nkey[keyLength+2] = 0xff & (page >> 16); 452 | nkey[keyLength+3] = 0xff & (page >> 24); 453 | 454 | /* AES encryption needs some 'salt' */ 455 | nkey[keyLength+4] = 0x73; 456 | nkey[keyLength+5] = 0x41; 457 | nkey[keyLength+6] = 0x6c; 458 | nkey[keyLength+7] = 0x54; 459 | 460 | #if CODEC_TYPE == CODEC_TYPE_AES256 461 | CodecGetSHABinary(codec, nkey, nkeylen, pagekey); 462 | #else 463 | CodecGetMD5Binary(codec, nkey, nkeylen, pagekey); 464 | #endif 465 | CodecGenerateInitialVector(codec, page, initial); 466 | 467 | #if CODEC_TYPE == CODEC_TYPE_AES256 468 | RijndaelInit(codec->m_aes, RIJNDAEL_Direction_Mode_CBC, direction, pagekey, RIJNDAEL_Direction_KeyLength_Key32Bytes, initial); 469 | #else 470 | RijndaelInit(codec->m_aes, RIJNDAEL_Direction_Mode_CBC, direction, pagekey, RIJNDAEL_Direction_KeyLength_Key16Bytes, initial); 471 | #endif 472 | if (encrypt) 473 | { 474 | len = RijndaelBlockEncrypt(codec->m_aes, datain, datalen*8, dataout); 475 | } 476 | else 477 | { 478 | len = RijndaelBlockDecrypt(codec->m_aes, datain, datalen*8, dataout); 479 | } 480 | 481 | /* It is a good idea to check the error code */ 482 | if (len < 0) 483 | { 484 | /* AES: Error on encrypting. */ 485 | } 486 | } 487 | 488 | static unsigned char padding[] = 489 | "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A"; 490 | 491 | void 492 | CodecInit(Codec* codec) 493 | { 494 | codec->m_isEncrypted = 0; 495 | codec->m_hasReadKey = 0; 496 | codec->m_hasWriteKey = 0; 497 | codec->m_aes = (Rijndael*) sqlite3_malloc(sizeof(Rijndael)); 498 | RijndaelCreate(codec->m_aes); 499 | } 500 | 501 | void 502 | CodecTerm(Codec* codec) 503 | { 504 | sqlite3_free(codec->m_aes); 505 | } 506 | 507 | void 508 | CodecSetIsEncrypted(Codec* codec, int isEncrypted) 509 | { 510 | codec->m_isEncrypted = isEncrypted; 511 | } 512 | 513 | void 514 | CodecSetHasReadKey(Codec* codec, int hasReadKey) 515 | { 516 | codec->m_hasReadKey = hasReadKey; 517 | } 518 | 519 | void 520 | CodecSetHasWriteKey(Codec* codec, int hasWriteKey) 521 | { 522 | codec->m_hasWriteKey = hasWriteKey; 523 | } 524 | 525 | void 526 | CodecSetBtree(Codec* codec, Btree* bt) 527 | { 528 | codec->m_bt = bt; 529 | } 530 | 531 | int 532 | CodecIsEncrypted(Codec* codec) 533 | { 534 | return codec->m_isEncrypted; 535 | } 536 | 537 | int 538 | CodecHasReadKey(Codec* codec) 539 | { 540 | return codec->m_hasReadKey; 541 | } 542 | 543 | int 544 | CodecHasWriteKey(Codec* codec) 545 | { 546 | return codec->m_hasWriteKey; 547 | } 548 | 549 | Btree* 550 | CodecGetBtree(Codec* codec) 551 | { 552 | return codec->m_bt; 553 | } 554 | 555 | unsigned char* 556 | CodecGetPageBuffer(Codec* codec) 557 | { 558 | return &codec->m_page[4]; 559 | } 560 | 561 | void 562 | CodecCopy(Codec* codec, Codec* other) 563 | { 564 | int j; 565 | codec->m_isEncrypted = other->m_isEncrypted; 566 | codec->m_hasReadKey = other->m_hasReadKey; 567 | codec->m_hasWriteKey = other->m_hasWriteKey; 568 | for (j = 0; j < KEYLENGTH; j++) 569 | { 570 | codec->m_readKey[j] = other->m_readKey[j]; 571 | codec->m_writeKey[j] = other->m_writeKey[j]; 572 | } 573 | codec->m_bt = other->m_bt; 574 | RijndaelInvalidate(codec->m_aes); 575 | } 576 | 577 | void 578 | CodecCopyKey(Codec* codec, int read2write) 579 | { 580 | int j; 581 | if (read2write) 582 | { 583 | for (j = 0; j < KEYLENGTH; j++) 584 | { 585 | codec->m_writeKey[j] = codec->m_readKey[j]; 586 | } 587 | } 588 | else 589 | { 590 | for (j = 0; j < KEYLENGTH; j++) 591 | { 592 | codec->m_readKey[j] = codec->m_writeKey[j]; 593 | } 594 | } 595 | } 596 | 597 | void 598 | CodecPadPassword(Codec* codec, char* password, int pswdlen, unsigned char pswd[32]) 599 | { 600 | int j; 601 | int p = 0; 602 | int m = pswdlen; 603 | if (m > 32) m = 32; 604 | 605 | for (j = 0; j < m; j++) 606 | { 607 | pswd[p++] = (unsigned char) password[j]; 608 | } 609 | for (j = 0; p < 32 && j < 32; j++) 610 | { 611 | pswd[p++] = padding[j]; 612 | } 613 | } 614 | 615 | void 616 | CodecGenerateReadKey(Codec* codec, char* userPassword, int passwordLength) 617 | { 618 | CodecGenerateEncryptionKey(codec, userPassword, passwordLength, codec->m_readKey); 619 | } 620 | 621 | void 622 | CodecGenerateWriteKey(Codec* codec, char* userPassword, int passwordLength) 623 | { 624 | CodecGenerateEncryptionKey(codec, userPassword, passwordLength, codec->m_writeKey); 625 | } 626 | 627 | void 628 | CodecGenerateEncryptionKey(Codec* codec, char* userPassword, int passwordLength, 629 | unsigned char encryptionKey[KEYLENGTH]) 630 | { 631 | #if CODEC_TYPE == CODEC_TYPE_AES256 632 | unsigned char userPad[32]; 633 | unsigned char digest[KEYLENGTH]; 634 | int keyLength = KEYLENGTH; 635 | int k; 636 | 637 | /* Pad password */ 638 | CodecPadPassword(codec, userPassword, passwordLength, userPad); 639 | 640 | sha256(userPad, 32, digest); 641 | for (k = 0; k < CODEC_SHA_ITER; ++k) 642 | { 643 | sha256(digest, KEYLENGTH, digest); 644 | } 645 | memcpy(encryptionKey, digest, keyLength); 646 | #else 647 | unsigned char userPad[32]; 648 | unsigned char ownerPad[32]; 649 | unsigned char ownerKey[32]; 650 | 651 | unsigned char mkey[MD5_HASHBYTES]; 652 | unsigned char digest[MD5_HASHBYTES]; 653 | int keyLength = MD5_HASHBYTES; 654 | int i, j, k; 655 | MD5_CTX ctx; 656 | 657 | /* Pad passwords */ 658 | CodecPadPassword(codec, userPassword, passwordLength, userPad); 659 | CodecPadPassword(codec, "", 0, ownerPad); 660 | 661 | /* Compute owner key */ 662 | 663 | MD5Init(&ctx); 664 | MD5Update(&ctx, ownerPad, 32); 665 | MD5Final(digest,&ctx); 666 | 667 | /* only use for the input as many bit as the key consists of */ 668 | for (k = 0; k < 50; ++k) 669 | { 670 | MD5Init(&ctx); 671 | MD5Update(&ctx, digest, keyLength); 672 | MD5Final(digest,&ctx); 673 | } 674 | memcpy(ownerKey, userPad, 32); 675 | for (i = 0; i < 20; ++i) 676 | { 677 | for (j = 0; j < keyLength ; ++j) 678 | { 679 | mkey[j] = (digest[j] ^ i); 680 | } 681 | CodecRC4(codec, mkey, keyLength, ownerKey, 32, ownerKey); 682 | } 683 | 684 | /* Compute encryption key */ 685 | 686 | MD5Init(&ctx); 687 | MD5Update(&ctx, userPad, 32); 688 | MD5Update(&ctx, ownerKey, 32); 689 | MD5Final(digest,&ctx); 690 | 691 | /* only use the really needed bits as input for the hash */ 692 | for (k = 0; k < 50; ++k) 693 | { 694 | MD5Init(&ctx); 695 | MD5Update(&ctx, digest, keyLength); 696 | MD5Final(digest, &ctx); 697 | } 698 | memcpy(encryptionKey, digest, keyLength); 699 | #endif 700 | } 701 | 702 | void 703 | CodecEncrypt(Codec* codec, int page, unsigned char* data, int len, int useWriteKey) 704 | { 705 | unsigned char* key = (useWriteKey) ? codec->m_writeKey : codec->m_readKey; 706 | CodecAES(codec, page, 1, key, data, len, data); 707 | 708 | } 709 | 710 | void 711 | CodecDecrypt(Codec* codec, int page, unsigned char* data, int len) 712 | { 713 | CodecAES(codec, page, 0, codec->m_readKey, data, len, data); 714 | } 715 | 716 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/sqlite3ext.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** 2006 June 7 3 | ** 4 | ** The author disclaims copyright to this source code. In place of 5 | ** a legal notice, here is a blessing: 6 | ** 7 | ** May you do good and not evil. 8 | ** May you find forgiveness for yourself and forgive others. 9 | ** May you share freely, never taking more than you give. 10 | ** 11 | ************************************************************************* 12 | ** This header file defines the SQLite interface for use by 13 | ** shared libraries that want to be imported as extensions into 14 | ** an SQLite instance. Shared libraries that intend to be loaded 15 | ** as extensions by SQLite should #include this file instead of 16 | ** sqlite3.h. 17 | */ 18 | #ifndef _SQLITE3EXT_H_ 19 | #define _SQLITE3EXT_H_ 20 | #include "sqlite3.h" 21 | 22 | typedef struct sqlite3_api_routines sqlite3_api_routines; 23 | 24 | /* 25 | ** The following structure holds pointers to all of the SQLite API 26 | ** routines. 27 | ** 28 | ** WARNING: In order to maintain backwards compatibility, add new 29 | ** interfaces to the end of this structure only. If you insert new 30 | ** interfaces in the middle of this structure, then older different 31 | ** versions of SQLite will not be able to load each others' shared 32 | ** libraries! 33 | */ 34 | struct sqlite3_api_routines { 35 | void * (*aggregate_context)(sqlite3_context*,int nBytes); 36 | int (*aggregate_count)(sqlite3_context*); 37 | int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); 38 | int (*bind_double)(sqlite3_stmt*,int,double); 39 | int (*bind_int)(sqlite3_stmt*,int,int); 40 | int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); 41 | int (*bind_null)(sqlite3_stmt*,int); 42 | int (*bind_parameter_count)(sqlite3_stmt*); 43 | int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); 44 | const char * (*bind_parameter_name)(sqlite3_stmt*,int); 45 | int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); 46 | int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); 47 | int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); 48 | int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); 49 | int (*busy_timeout)(sqlite3*,int ms); 50 | int (*changes)(sqlite3*); 51 | int (*close)(sqlite3*); 52 | int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*)); 53 | int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*)); 54 | const void * (*column_blob)(sqlite3_stmt*,int iCol); 55 | int (*column_bytes)(sqlite3_stmt*,int iCol); 56 | int (*column_bytes16)(sqlite3_stmt*,int iCol); 57 | int (*column_count)(sqlite3_stmt*pStmt); 58 | const char * (*column_database_name)(sqlite3_stmt*,int); 59 | const void * (*column_database_name16)(sqlite3_stmt*,int); 60 | const char * (*column_decltype)(sqlite3_stmt*,int i); 61 | const void * (*column_decltype16)(sqlite3_stmt*,int); 62 | double (*column_double)(sqlite3_stmt*,int iCol); 63 | int (*column_int)(sqlite3_stmt*,int iCol); 64 | sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); 65 | const char * (*column_name)(sqlite3_stmt*,int); 66 | const void * (*column_name16)(sqlite3_stmt*,int); 67 | const char * (*column_origin_name)(sqlite3_stmt*,int); 68 | const void * (*column_origin_name16)(sqlite3_stmt*,int); 69 | const char * (*column_table_name)(sqlite3_stmt*,int); 70 | const void * (*column_table_name16)(sqlite3_stmt*,int); 71 | const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); 72 | const void * (*column_text16)(sqlite3_stmt*,int iCol); 73 | int (*column_type)(sqlite3_stmt*,int iCol); 74 | sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); 75 | void * (*commit_hook)(sqlite3*,int(*)(void*),void*); 76 | int (*complete)(const char*sql); 77 | int (*complete16)(const void*sql); 78 | int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*)); 79 | int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*)); 80 | int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); 81 | int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); 82 | int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); 83 | int (*data_count)(sqlite3_stmt*pStmt); 84 | sqlite3 * (*db_handle)(sqlite3_stmt*); 85 | int (*declare_vtab)(sqlite3*,const char*); 86 | int (*enable_shared_cache)(int); 87 | int (*errcode)(sqlite3*db); 88 | const char * (*errmsg)(sqlite3*); 89 | const void * (*errmsg16)(sqlite3*); 90 | int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); 91 | int (*expired)(sqlite3_stmt*); 92 | int (*finalize)(sqlite3_stmt*pStmt); 93 | void (*free)(void*); 94 | void (*free_table)(char**result); 95 | int (*get_autocommit)(sqlite3*); 96 | void * (*get_auxdata)(sqlite3_context*,int); 97 | int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); 98 | int (*global_recover)(void); 99 | void (*interruptx)(sqlite3*); 100 | sqlite_int64 (*last_insert_rowid)(sqlite3*); 101 | const char * (*libversion)(void); 102 | int (*libversion_number)(void); 103 | void *(*malloc)(int); 104 | char * (*mprintf)(const char*,...); 105 | int (*open)(const char*,sqlite3**); 106 | int (*open16)(const void*,sqlite3**); 107 | int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); 108 | int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); 109 | void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); 110 | void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); 111 | void *(*realloc)(void*,int); 112 | int (*reset)(sqlite3_stmt*pStmt); 113 | void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); 114 | void (*result_double)(sqlite3_context*,double); 115 | void (*result_error)(sqlite3_context*,const char*,int); 116 | void (*result_error16)(sqlite3_context*,const void*,int); 117 | void (*result_int)(sqlite3_context*,int); 118 | void (*result_int64)(sqlite3_context*,sqlite_int64); 119 | void (*result_null)(sqlite3_context*); 120 | void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); 121 | void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); 122 | void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); 123 | void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); 124 | void (*result_value)(sqlite3_context*,sqlite3_value*); 125 | void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); 126 | int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*); 127 | void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); 128 | char * (*snprintf)(int,char*,const char*,...); 129 | int (*step)(sqlite3_stmt*); 130 | int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*); 131 | void (*thread_cleanup)(void); 132 | int (*total_changes)(sqlite3*); 133 | void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); 134 | int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); 135 | void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*); 136 | void * (*user_data)(sqlite3_context*); 137 | const void * (*value_blob)(sqlite3_value*); 138 | int (*value_bytes)(sqlite3_value*); 139 | int (*value_bytes16)(sqlite3_value*); 140 | double (*value_double)(sqlite3_value*); 141 | int (*value_int)(sqlite3_value*); 142 | sqlite_int64 (*value_int64)(sqlite3_value*); 143 | int (*value_numeric_type)(sqlite3_value*); 144 | const unsigned char * (*value_text)(sqlite3_value*); 145 | const void * (*value_text16)(sqlite3_value*); 146 | const void * (*value_text16be)(sqlite3_value*); 147 | const void * (*value_text16le)(sqlite3_value*); 148 | int (*value_type)(sqlite3_value*); 149 | char *(*vmprintf)(const char*,va_list); 150 | /* Added ??? */ 151 | int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); 152 | /* Added by 3.3.13 */ 153 | int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); 154 | int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); 155 | int (*clear_bindings)(sqlite3_stmt*); 156 | /* Added by 3.4.1 */ 157 | int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *)); 158 | /* Added by 3.5.0 */ 159 | int (*bind_zeroblob)(sqlite3_stmt*,int,int); 160 | int (*blob_bytes)(sqlite3_blob*); 161 | int (*blob_close)(sqlite3_blob*); 162 | int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**); 163 | int (*blob_read)(sqlite3_blob*,void*,int,int); 164 | int (*blob_write)(sqlite3_blob*,const void*,int,int); 165 | int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*)); 166 | int (*file_control)(sqlite3*,const char*,int,void*); 167 | sqlite3_int64 (*memory_highwater)(int); 168 | sqlite3_int64 (*memory_used)(void); 169 | sqlite3_mutex *(*mutex_alloc)(int); 170 | void (*mutex_enter)(sqlite3_mutex*); 171 | void (*mutex_free)(sqlite3_mutex*); 172 | void (*mutex_leave)(sqlite3_mutex*); 173 | int (*mutex_try)(sqlite3_mutex*); 174 | int (*open_v2)(const char*,sqlite3**,int,const char*); 175 | int (*release_memory)(int); 176 | void (*result_error_nomem)(sqlite3_context*); 177 | void (*result_error_toobig)(sqlite3_context*); 178 | int (*sleep)(int); 179 | void (*soft_heap_limit)(int); 180 | sqlite3_vfs *(*vfs_find)(const char*); 181 | int (*vfs_register)(sqlite3_vfs*,int); 182 | int (*vfs_unregister)(sqlite3_vfs*); 183 | int (*xthreadsafe)(void); 184 | void (*result_zeroblob)(sqlite3_context*,int); 185 | void (*result_error_code)(sqlite3_context*,int); 186 | int (*test_control)(int, ...); 187 | void (*randomness)(int,void*); 188 | sqlite3 *(*context_db_handle)(sqlite3_context*); 189 | int (*extended_result_codes)(sqlite3*,int); 190 | int (*limit)(sqlite3*,int,int); 191 | sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); 192 | const char *(*sql)(sqlite3_stmt*); 193 | int (*status)(int,int*,int*,int); 194 | int (*backup_finish)(sqlite3_backup*); 195 | sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); 196 | int (*backup_pagecount)(sqlite3_backup*); 197 | int (*backup_remaining)(sqlite3_backup*); 198 | int (*backup_step)(sqlite3_backup*,int); 199 | const char *(*compileoption_get)(int); 200 | int (*compileoption_used)(const char*); 201 | int (*create_function_v2)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*),void(*xDestroy)(void*)); 202 | int (*db_config)(sqlite3*,int,...); 203 | sqlite3_mutex *(*db_mutex)(sqlite3*); 204 | int (*db_status)(sqlite3*,int,int*,int*,int); 205 | int (*extended_errcode)(sqlite3*); 206 | void (*log)(int,const char*,...); 207 | sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); 208 | const char *(*sourceid)(void); 209 | int (*stmt_status)(sqlite3_stmt*,int,int); 210 | int (*strnicmp)(const char*,const char*,int); 211 | int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); 212 | int (*wal_autocheckpoint)(sqlite3*,int); 213 | int (*wal_checkpoint)(sqlite3*,const char*); 214 | void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); 215 | }; 216 | 217 | /* 218 | ** The following macros redefine the API routines so that they are 219 | ** redirected throught the global sqlite3_api structure. 220 | ** 221 | ** This header file is also used by the loadext.c source file 222 | ** (part of the main SQLite library - not an extension) so that 223 | ** it can get access to the sqlite3_api_routines structure 224 | ** definition. But the main library does not want to redefine 225 | ** the API. So the redefinition macros are only valid if the 226 | ** SQLITE_CORE macros is undefined. 227 | */ 228 | #ifndef SQLITE_CORE 229 | #define sqlite3_aggregate_context sqlite3_api->aggregate_context 230 | #ifndef SQLITE_OMIT_DEPRECATED 231 | #define sqlite3_aggregate_count sqlite3_api->aggregate_count 232 | #endif 233 | #define sqlite3_bind_blob sqlite3_api->bind_blob 234 | #define sqlite3_bind_double sqlite3_api->bind_double 235 | #define sqlite3_bind_int sqlite3_api->bind_int 236 | #define sqlite3_bind_int64 sqlite3_api->bind_int64 237 | #define sqlite3_bind_null sqlite3_api->bind_null 238 | #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count 239 | #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index 240 | #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name 241 | #define sqlite3_bind_text sqlite3_api->bind_text 242 | #define sqlite3_bind_text16 sqlite3_api->bind_text16 243 | #define sqlite3_bind_value sqlite3_api->bind_value 244 | #define sqlite3_busy_handler sqlite3_api->busy_handler 245 | #define sqlite3_busy_timeout sqlite3_api->busy_timeout 246 | #define sqlite3_changes sqlite3_api->changes 247 | #define sqlite3_close sqlite3_api->close 248 | #define sqlite3_collation_needed sqlite3_api->collation_needed 249 | #define sqlite3_collation_needed16 sqlite3_api->collation_needed16 250 | #define sqlite3_column_blob sqlite3_api->column_blob 251 | #define sqlite3_column_bytes sqlite3_api->column_bytes 252 | #define sqlite3_column_bytes16 sqlite3_api->column_bytes16 253 | #define sqlite3_column_count sqlite3_api->column_count 254 | #define sqlite3_column_database_name sqlite3_api->column_database_name 255 | #define sqlite3_column_database_name16 sqlite3_api->column_database_name16 256 | #define sqlite3_column_decltype sqlite3_api->column_decltype 257 | #define sqlite3_column_decltype16 sqlite3_api->column_decltype16 258 | #define sqlite3_column_double sqlite3_api->column_double 259 | #define sqlite3_column_int sqlite3_api->column_int 260 | #define sqlite3_column_int64 sqlite3_api->column_int64 261 | #define sqlite3_column_name sqlite3_api->column_name 262 | #define sqlite3_column_name16 sqlite3_api->column_name16 263 | #define sqlite3_column_origin_name sqlite3_api->column_origin_name 264 | #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 265 | #define sqlite3_column_table_name sqlite3_api->column_table_name 266 | #define sqlite3_column_table_name16 sqlite3_api->column_table_name16 267 | #define sqlite3_column_text sqlite3_api->column_text 268 | #define sqlite3_column_text16 sqlite3_api->column_text16 269 | #define sqlite3_column_type sqlite3_api->column_type 270 | #define sqlite3_column_value sqlite3_api->column_value 271 | #define sqlite3_commit_hook sqlite3_api->commit_hook 272 | #define sqlite3_complete sqlite3_api->complete 273 | #define sqlite3_complete16 sqlite3_api->complete16 274 | #define sqlite3_create_collation sqlite3_api->create_collation 275 | #define sqlite3_create_collation16 sqlite3_api->create_collation16 276 | #define sqlite3_create_function sqlite3_api->create_function 277 | #define sqlite3_create_function16 sqlite3_api->create_function16 278 | #define sqlite3_create_module sqlite3_api->create_module 279 | #define sqlite3_create_module_v2 sqlite3_api->create_module_v2 280 | #define sqlite3_data_count sqlite3_api->data_count 281 | #define sqlite3_db_handle sqlite3_api->db_handle 282 | #define sqlite3_declare_vtab sqlite3_api->declare_vtab 283 | #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache 284 | #define sqlite3_errcode sqlite3_api->errcode 285 | #define sqlite3_errmsg sqlite3_api->errmsg 286 | #define sqlite3_errmsg16 sqlite3_api->errmsg16 287 | #define sqlite3_exec sqlite3_api->exec 288 | #ifndef SQLITE_OMIT_DEPRECATED 289 | #define sqlite3_expired sqlite3_api->expired 290 | #endif 291 | #define sqlite3_finalize sqlite3_api->finalize 292 | #define sqlite3_free sqlite3_api->free 293 | #define sqlite3_free_table sqlite3_api->free_table 294 | #define sqlite3_get_autocommit sqlite3_api->get_autocommit 295 | #define sqlite3_get_auxdata sqlite3_api->get_auxdata 296 | #define sqlite3_get_table sqlite3_api->get_table 297 | #ifndef SQLITE_OMIT_DEPRECATED 298 | #define sqlite3_global_recover sqlite3_api->global_recover 299 | #endif 300 | #define sqlite3_interrupt sqlite3_api->interruptx 301 | #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid 302 | #define sqlite3_libversion sqlite3_api->libversion 303 | #define sqlite3_libversion_number sqlite3_api->libversion_number 304 | #define sqlite3_malloc sqlite3_api->malloc 305 | #define sqlite3_mprintf sqlite3_api->mprintf 306 | #define sqlite3_open sqlite3_api->open 307 | #define sqlite3_open16 sqlite3_api->open16 308 | #define sqlite3_prepare sqlite3_api->prepare 309 | #define sqlite3_prepare16 sqlite3_api->prepare16 310 | #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 311 | #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 312 | #define sqlite3_profile sqlite3_api->profile 313 | #define sqlite3_progress_handler sqlite3_api->progress_handler 314 | #define sqlite3_realloc sqlite3_api->realloc 315 | #define sqlite3_reset sqlite3_api->reset 316 | #define sqlite3_result_blob sqlite3_api->result_blob 317 | #define sqlite3_result_double sqlite3_api->result_double 318 | #define sqlite3_result_error sqlite3_api->result_error 319 | #define sqlite3_result_error16 sqlite3_api->result_error16 320 | #define sqlite3_result_int sqlite3_api->result_int 321 | #define sqlite3_result_int64 sqlite3_api->result_int64 322 | #define sqlite3_result_null sqlite3_api->result_null 323 | #define sqlite3_result_text sqlite3_api->result_text 324 | #define sqlite3_result_text16 sqlite3_api->result_text16 325 | #define sqlite3_result_text16be sqlite3_api->result_text16be 326 | #define sqlite3_result_text16le sqlite3_api->result_text16le 327 | #define sqlite3_result_value sqlite3_api->result_value 328 | #define sqlite3_rollback_hook sqlite3_api->rollback_hook 329 | #define sqlite3_set_authorizer sqlite3_api->set_authorizer 330 | #define sqlite3_set_auxdata sqlite3_api->set_auxdata 331 | #define sqlite3_snprintf sqlite3_api->snprintf 332 | #define sqlite3_step sqlite3_api->step 333 | #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata 334 | #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup 335 | #define sqlite3_total_changes sqlite3_api->total_changes 336 | #define sqlite3_trace sqlite3_api->trace 337 | #ifndef SQLITE_OMIT_DEPRECATED 338 | #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings 339 | #endif 340 | #define sqlite3_update_hook sqlite3_api->update_hook 341 | #define sqlite3_user_data sqlite3_api->user_data 342 | #define sqlite3_value_blob sqlite3_api->value_blob 343 | #define sqlite3_value_bytes sqlite3_api->value_bytes 344 | #define sqlite3_value_bytes16 sqlite3_api->value_bytes16 345 | #define sqlite3_value_double sqlite3_api->value_double 346 | #define sqlite3_value_int sqlite3_api->value_int 347 | #define sqlite3_value_int64 sqlite3_api->value_int64 348 | #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type 349 | #define sqlite3_value_text sqlite3_api->value_text 350 | #define sqlite3_value_text16 sqlite3_api->value_text16 351 | #define sqlite3_value_text16be sqlite3_api->value_text16be 352 | #define sqlite3_value_text16le sqlite3_api->value_text16le 353 | #define sqlite3_value_type sqlite3_api->value_type 354 | #define sqlite3_vmprintf sqlite3_api->vmprintf 355 | #define sqlite3_overload_function sqlite3_api->overload_function 356 | #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 357 | #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 358 | #define sqlite3_clear_bindings sqlite3_api->clear_bindings 359 | #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob 360 | #define sqlite3_blob_bytes sqlite3_api->blob_bytes 361 | #define sqlite3_blob_close sqlite3_api->blob_close 362 | #define sqlite3_blob_open sqlite3_api->blob_open 363 | #define sqlite3_blob_read sqlite3_api->blob_read 364 | #define sqlite3_blob_write sqlite3_api->blob_write 365 | #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 366 | #define sqlite3_file_control sqlite3_api->file_control 367 | #define sqlite3_memory_highwater sqlite3_api->memory_highwater 368 | #define sqlite3_memory_used sqlite3_api->memory_used 369 | #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc 370 | #define sqlite3_mutex_enter sqlite3_api->mutex_enter 371 | #define sqlite3_mutex_free sqlite3_api->mutex_free 372 | #define sqlite3_mutex_leave sqlite3_api->mutex_leave 373 | #define sqlite3_mutex_try sqlite3_api->mutex_try 374 | #define sqlite3_open_v2 sqlite3_api->open_v2 375 | #define sqlite3_release_memory sqlite3_api->release_memory 376 | #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem 377 | #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig 378 | #define sqlite3_sleep sqlite3_api->sleep 379 | #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit 380 | #define sqlite3_vfs_find sqlite3_api->vfs_find 381 | #define sqlite3_vfs_register sqlite3_api->vfs_register 382 | #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister 383 | #define sqlite3_threadsafe sqlite3_api->xthreadsafe 384 | #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob 385 | #define sqlite3_result_error_code sqlite3_api->result_error_code 386 | #define sqlite3_test_control sqlite3_api->test_control 387 | #define sqlite3_randomness sqlite3_api->randomness 388 | #define sqlite3_context_db_handle sqlite3_api->context_db_handle 389 | #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes 390 | #define sqlite3_limit sqlite3_api->limit 391 | #define sqlite3_next_stmt sqlite3_api->next_stmt 392 | #define sqlite3_sql sqlite3_api->sql 393 | #define sqlite3_status sqlite3_api->status 394 | #define sqlite3_backup_finish sqlite3_api->backup_finish 395 | #define sqlite3_backup_init sqlite3_api->backup_init 396 | #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount 397 | #define sqlite3_backup_remaining sqlite3_api->backup_remaining 398 | #define sqlite3_backup_step sqlite3_api->backup_step 399 | #define sqlite3_compileoption_get sqlite3_api->compileoption_get 400 | #define sqlite3_compileoption_used sqlite3_api->compileoption_used 401 | #define sqlite3_create_function_v2 sqlite3_api->create_function_v2 402 | #define sqlite3_db_config sqlite3_api->db_config 403 | #define sqlite3_db_mutex sqlite3_api->db_mutex 404 | #define sqlite3_db_status sqlite3_api->db_status 405 | #define sqlite3_extended_errcode sqlite3_api->extended_errcode 406 | #define sqlite3_log sqlite3_api->log 407 | #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 408 | #define sqlite3_sourceid sqlite3_api->sourceid 409 | #define sqlite3_stmt_status sqlite3_api->stmt_status 410 | #define sqlite3_strnicmp sqlite3_api->strnicmp 411 | #define sqlite3_unlock_notify sqlite3_api->unlock_notify 412 | #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint 413 | #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint 414 | #define sqlite3_wal_hook sqlite3_api->wal_hook 415 | #endif /* SQLITE_CORE */ 416 | 417 | #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0; 418 | #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v; 419 | 420 | #endif /* _SQLITE3EXT_H_ */ 421 | -------------------------------------------------------------------------------- /src/sqlite3_encrypt/sqlite3/sha2.c: -------------------------------------------------------------------------------- 1 | /* 2 | * FIPS 180-2 SHA-224/256/384/512 implementation 3 | * Last update: 02/02/2007 4 | * Issue date: 04/30/2005 5 | * 6 | * Copyright (C) 2005, 2007 Olivier Gay 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without 10 | * modification, are permitted provided that the following conditions 11 | * are met: 12 | * 1. Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 2. Redistributions in binary form must reproduce the above copyright 15 | * notice, this list of conditions and the following disclaimer in the 16 | * documentation and/or other materials provided with the distribution. 17 | * 3. Neither the name of the project nor the names of its contributors 18 | * may be used to endorse or promote products derived from this software 19 | * without specific prior written permission. 20 | * 21 | * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND 22 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE 25 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 | * SUCH DAMAGE. 32 | */ 33 | 34 | #if 0 35 | #define UNROLL_LOOPS /* Enable loops unrolling */ 36 | #endif 37 | 38 | #include 39 | 40 | #include "sha2.h" 41 | 42 | #define SHFR(x, n) (x >> n) 43 | #define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) 44 | #define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) 45 | #define CH(x, y, z) ((x & y) ^ (~x & z)) 46 | #define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) 47 | 48 | #define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) 49 | #define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) 50 | #define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3)) 51 | #define SHA256_F4(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10)) 52 | 53 | #define SHA512_F1(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39)) 54 | #define SHA512_F2(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41)) 55 | #define SHA512_F3(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHFR(x, 7)) 56 | #define SHA512_F4(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHFR(x, 6)) 57 | 58 | #define UNPACK32(x, str) \ 59 | { \ 60 | *((str) + 3) = (uint8) ((x) ); \ 61 | *((str) + 2) = (uint8) ((x) >> 8); \ 62 | *((str) + 1) = (uint8) ((x) >> 16); \ 63 | *((str) + 0) = (uint8) ((x) >> 24); \ 64 | } 65 | 66 | #define PACK32(str, x) \ 67 | { \ 68 | *(x) = ((uint32) *((str) + 3) ) \ 69 | | ((uint32) *((str) + 2) << 8) \ 70 | | ((uint32) *((str) + 1) << 16) \ 71 | | ((uint32) *((str) + 0) << 24); \ 72 | } 73 | 74 | #define UNPACK64(x, str) \ 75 | { \ 76 | *((str) + 7) = (uint8) ((x) ); \ 77 | *((str) + 6) = (uint8) ((x) >> 8); \ 78 | *((str) + 5) = (uint8) ((x) >> 16); \ 79 | *((str) + 4) = (uint8) ((x) >> 24); \ 80 | *((str) + 3) = (uint8) ((x) >> 32); \ 81 | *((str) + 2) = (uint8) ((x) >> 40); \ 82 | *((str) + 1) = (uint8) ((x) >> 48); \ 83 | *((str) + 0) = (uint8) ((x) >> 56); \ 84 | } 85 | 86 | #define PACK64(str, x) \ 87 | { \ 88 | *(x) = ((uint64) *((str) + 7) ) \ 89 | | ((uint64) *((str) + 6) << 8) \ 90 | | ((uint64) *((str) + 5) << 16) \ 91 | | ((uint64) *((str) + 4) << 24) \ 92 | | ((uint64) *((str) + 3) << 32) \ 93 | | ((uint64) *((str) + 2) << 40) \ 94 | | ((uint64) *((str) + 1) << 48) \ 95 | | ((uint64) *((str) + 0) << 56); \ 96 | } 97 | 98 | /* Macros used for loops unrolling */ 99 | 100 | #define SHA256_SCR(i) \ 101 | { \ 102 | w[i] = SHA256_F4(w[i - 2]) + w[i - 7] \ 103 | + SHA256_F3(w[i - 15]) + w[i - 16]; \ 104 | } 105 | 106 | #define SHA512_SCR(i) \ 107 | { \ 108 | w[i] = SHA512_F4(w[i - 2]) + w[i - 7] \ 109 | + SHA512_F3(w[i - 15]) + w[i - 16]; \ 110 | } 111 | 112 | #define SHA256_EXP(a, b, c, d, e, f, g, h, j) \ 113 | { \ 114 | t1 = wv[h] + SHA256_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \ 115 | + sha256_k[j] + w[j]; \ 116 | t2 = SHA256_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ 117 | wv[d] += t1; \ 118 | wv[h] = t1 + t2; \ 119 | } 120 | 121 | #define SHA512_EXP(a, b, c, d, e, f, g ,h, j) \ 122 | { \ 123 | t1 = wv[h] + SHA512_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \ 124 | + sha512_k[j] + w[j]; \ 125 | t2 = SHA512_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ 126 | wv[d] += t1; \ 127 | wv[h] = t1 + t2; \ 128 | } 129 | 130 | uint32 sha224_h0[8] = 131 | {0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 132 | 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4}; 133 | 134 | uint32 sha256_h0[8] = 135 | {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 136 | 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; 137 | 138 | uint64 sha384_h0[8] = 139 | {li_64(cbbb9d5dc1059ed8), li_64(629a292a367cd507), 140 | li_64(9159015a3070dd17), li_64(152fecd8f70e5939), 141 | li_64(67332667ffc00b31), li_64(8eb44a8768581511), 142 | li_64(db0c2e0d64f98fa7), li_64(47b5481dbefa4fa4)}; 143 | 144 | uint64 sha512_h0[8] = 145 | {li_64(6a09e667f3bcc908), li_64(bb67ae8584caa73b), 146 | li_64(3c6ef372fe94f82b), li_64(a54ff53a5f1d36f1), 147 | li_64(510e527fade682d1), li_64(9b05688c2b3e6c1f), 148 | li_64(1f83d9abfb41bd6b), li_64(5be0cd19137e2179)}; 149 | 150 | uint32 sha256_k[64] = 151 | {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 152 | 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 153 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 154 | 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 155 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 156 | 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 157 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 158 | 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 159 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 160 | 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 161 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 162 | 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 163 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 164 | 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 165 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 166 | 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; 167 | 168 | uint64 sha512_k[80] = 169 | {li_64(428a2f98d728ae22), li_64(7137449123ef65cd), 170 | li_64(b5c0fbcfec4d3b2f), li_64(e9b5dba58189dbbc), 171 | li_64(3956c25bf348b538), li_64(59f111f1b605d019), 172 | li_64(923f82a4af194f9b), li_64(ab1c5ed5da6d8118), 173 | li_64(d807aa98a3030242), li_64(12835b0145706fbe), 174 | li_64(243185be4ee4b28c), li_64(550c7dc3d5ffb4e2), 175 | li_64(72be5d74f27b896f), li_64(80deb1fe3b1696b1), 176 | li_64(9bdc06a725c71235), li_64(c19bf174cf692694), 177 | li_64(e49b69c19ef14ad2), li_64(efbe4786384f25e3), 178 | li_64(0fc19dc68b8cd5b5), li_64(240ca1cc77ac9c65), 179 | li_64(2de92c6f592b0275), li_64(4a7484aa6ea6e483), 180 | li_64(5cb0a9dcbd41fbd4), li_64(76f988da831153b5), 181 | li_64(983e5152ee66dfab), li_64(a831c66d2db43210), 182 | li_64(b00327c898fb213f), li_64(bf597fc7beef0ee4), 183 | li_64(c6e00bf33da88fc2), li_64(d5a79147930aa725), 184 | li_64(06ca6351e003826f), li_64(142929670a0e6e70), 185 | li_64(27b70a8546d22ffc), li_64(2e1b21385c26c926), 186 | li_64(4d2c6dfc5ac42aed), li_64(53380d139d95b3df), 187 | li_64(650a73548baf63de), li_64(766a0abb3c77b2a8), 188 | li_64(81c2c92e47edaee6), li_64(92722c851482353b), 189 | li_64(a2bfe8a14cf10364), li_64(a81a664bbc423001), 190 | li_64(c24b8b70d0f89791), li_64(c76c51a30654be30), 191 | li_64(d192e819d6ef5218), li_64(d69906245565a910), 192 | li_64(f40e35855771202a), li_64(106aa07032bbd1b8), 193 | li_64(19a4c116b8d2d0c8), li_64(1e376c085141ab53), 194 | li_64(2748774cdf8eeb99), li_64(34b0bcb5e19b48a8), 195 | li_64(391c0cb3c5c95a63), li_64(4ed8aa4ae3418acb), 196 | li_64(5b9cca4f7763e373), li_64(682e6ff3d6b2b8a3), 197 | li_64(748f82ee5defb2fc), li_64(78a5636f43172f60), 198 | li_64(84c87814a1f0ab72), li_64(8cc702081a6439ec), 199 | li_64(90befffa23631e28), li_64(a4506cebde82bde9), 200 | li_64(bef9a3f7b2c67915), li_64(c67178f2e372532b), 201 | li_64(ca273eceea26619c), li_64(d186b8c721c0c207), 202 | li_64(eada7dd6cde0eb1e), li_64(f57d4f7fee6ed178), 203 | li_64(06f067aa72176fba), li_64(0a637dc5a2c898a6), 204 | li_64(113f9804bef90dae), li_64(1b710b35131c471b), 205 | li_64(28db77f523047d84), li_64(32caab7b40c72493), 206 | li_64(3c9ebe0a15c9bebc), li_64(431d67c49c100d4c), 207 | li_64(4cc5d4becb3e42b6), li_64(597f299cfc657e2a), 208 | li_64(5fcb6fab3ad6faec), li_64(6c44198c4a475817)}; 209 | 210 | /* SHA-256 functions */ 211 | 212 | void sha256_transf(sha256_ctx *ctx, const unsigned char *message, 213 | unsigned int block_nb) 214 | { 215 | uint32 w[64]; 216 | uint32 wv[8]; 217 | uint32 t1, t2; 218 | const unsigned char *sub_block; 219 | int i; 220 | 221 | #ifndef UNROLL_LOOPS 222 | int j; 223 | #endif 224 | 225 | for (i = 0; i < (int) block_nb; i++) { 226 | sub_block = message + (i << 6); 227 | 228 | #ifndef UNROLL_LOOPS 229 | for (j = 0; j < 16; j++) { 230 | PACK32(&sub_block[j << 2], &w[j]); 231 | } 232 | 233 | for (j = 16; j < 64; j++) { 234 | SHA256_SCR(j); 235 | } 236 | 237 | for (j = 0; j < 8; j++) { 238 | wv[j] = ctx->h[j]; 239 | } 240 | 241 | for (j = 0; j < 64; j++) { 242 | t1 = wv[7] + SHA256_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) 243 | + sha256_k[j] + w[j]; 244 | t2 = SHA256_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]); 245 | wv[7] = wv[6]; 246 | wv[6] = wv[5]; 247 | wv[5] = wv[4]; 248 | wv[4] = wv[3] + t1; 249 | wv[3] = wv[2]; 250 | wv[2] = wv[1]; 251 | wv[1] = wv[0]; 252 | wv[0] = t1 + t2; 253 | } 254 | 255 | for (j = 0; j < 8; j++) { 256 | ctx->h[j] += wv[j]; 257 | } 258 | #else 259 | PACK32(&sub_block[ 0], &w[ 0]); PACK32(&sub_block[ 4], &w[ 1]); 260 | PACK32(&sub_block[ 8], &w[ 2]); PACK32(&sub_block[12], &w[ 3]); 261 | PACK32(&sub_block[16], &w[ 4]); PACK32(&sub_block[20], &w[ 5]); 262 | PACK32(&sub_block[24], &w[ 6]); PACK32(&sub_block[28], &w[ 7]); 263 | PACK32(&sub_block[32], &w[ 8]); PACK32(&sub_block[36], &w[ 9]); 264 | PACK32(&sub_block[40], &w[10]); PACK32(&sub_block[44], &w[11]); 265 | PACK32(&sub_block[48], &w[12]); PACK32(&sub_block[52], &w[13]); 266 | PACK32(&sub_block[56], &w[14]); PACK32(&sub_block[60], &w[15]); 267 | 268 | SHA256_SCR(16); SHA256_SCR(17); SHA256_SCR(18); SHA256_SCR(19); 269 | SHA256_SCR(20); SHA256_SCR(21); SHA256_SCR(22); SHA256_SCR(23); 270 | SHA256_SCR(24); SHA256_SCR(25); SHA256_SCR(26); SHA256_SCR(27); 271 | SHA256_SCR(28); SHA256_SCR(29); SHA256_SCR(30); SHA256_SCR(31); 272 | SHA256_SCR(32); SHA256_SCR(33); SHA256_SCR(34); SHA256_SCR(35); 273 | SHA256_SCR(36); SHA256_SCR(37); SHA256_SCR(38); SHA256_SCR(39); 274 | SHA256_SCR(40); SHA256_SCR(41); SHA256_SCR(42); SHA256_SCR(43); 275 | SHA256_SCR(44); SHA256_SCR(45); SHA256_SCR(46); SHA256_SCR(47); 276 | SHA256_SCR(48); SHA256_SCR(49); SHA256_SCR(50); SHA256_SCR(51); 277 | SHA256_SCR(52); SHA256_SCR(53); SHA256_SCR(54); SHA256_SCR(55); 278 | SHA256_SCR(56); SHA256_SCR(57); SHA256_SCR(58); SHA256_SCR(59); 279 | SHA256_SCR(60); SHA256_SCR(61); SHA256_SCR(62); SHA256_SCR(63); 280 | 281 | wv[0] = ctx->h[0]; wv[1] = ctx->h[1]; 282 | wv[2] = ctx->h[2]; wv[3] = ctx->h[3]; 283 | wv[4] = ctx->h[4]; wv[5] = ctx->h[5]; 284 | wv[6] = ctx->h[6]; wv[7] = ctx->h[7]; 285 | 286 | SHA256_EXP(0,1,2,3,4,5,6,7, 0); SHA256_EXP(7,0,1,2,3,4,5,6, 1); 287 | SHA256_EXP(6,7,0,1,2,3,4,5, 2); SHA256_EXP(5,6,7,0,1,2,3,4, 3); 288 | SHA256_EXP(4,5,6,7,0,1,2,3, 4); SHA256_EXP(3,4,5,6,7,0,1,2, 5); 289 | SHA256_EXP(2,3,4,5,6,7,0,1, 6); SHA256_EXP(1,2,3,4,5,6,7,0, 7); 290 | SHA256_EXP(0,1,2,3,4,5,6,7, 8); SHA256_EXP(7,0,1,2,3,4,5,6, 9); 291 | SHA256_EXP(6,7,0,1,2,3,4,5,10); SHA256_EXP(5,6,7,0,1,2,3,4,11); 292 | SHA256_EXP(4,5,6,7,0,1,2,3,12); SHA256_EXP(3,4,5,6,7,0,1,2,13); 293 | SHA256_EXP(2,3,4,5,6,7,0,1,14); SHA256_EXP(1,2,3,4,5,6,7,0,15); 294 | SHA256_EXP(0,1,2,3,4,5,6,7,16); SHA256_EXP(7,0,1,2,3,4,5,6,17); 295 | SHA256_EXP(6,7,0,1,2,3,4,5,18); SHA256_EXP(5,6,7,0,1,2,3,4,19); 296 | SHA256_EXP(4,5,6,7,0,1,2,3,20); SHA256_EXP(3,4,5,6,7,0,1,2,21); 297 | SHA256_EXP(2,3,4,5,6,7,0,1,22); SHA256_EXP(1,2,3,4,5,6,7,0,23); 298 | SHA256_EXP(0,1,2,3,4,5,6,7,24); SHA256_EXP(7,0,1,2,3,4,5,6,25); 299 | SHA256_EXP(6,7,0,1,2,3,4,5,26); SHA256_EXP(5,6,7,0,1,2,3,4,27); 300 | SHA256_EXP(4,5,6,7,0,1,2,3,28); SHA256_EXP(3,4,5,6,7,0,1,2,29); 301 | SHA256_EXP(2,3,4,5,6,7,0,1,30); SHA256_EXP(1,2,3,4,5,6,7,0,31); 302 | SHA256_EXP(0,1,2,3,4,5,6,7,32); SHA256_EXP(7,0,1,2,3,4,5,6,33); 303 | SHA256_EXP(6,7,0,1,2,3,4,5,34); SHA256_EXP(5,6,7,0,1,2,3,4,35); 304 | SHA256_EXP(4,5,6,7,0,1,2,3,36); SHA256_EXP(3,4,5,6,7,0,1,2,37); 305 | SHA256_EXP(2,3,4,5,6,7,0,1,38); SHA256_EXP(1,2,3,4,5,6,7,0,39); 306 | SHA256_EXP(0,1,2,3,4,5,6,7,40); SHA256_EXP(7,0,1,2,3,4,5,6,41); 307 | SHA256_EXP(6,7,0,1,2,3,4,5,42); SHA256_EXP(5,6,7,0,1,2,3,4,43); 308 | SHA256_EXP(4,5,6,7,0,1,2,3,44); SHA256_EXP(3,4,5,6,7,0,1,2,45); 309 | SHA256_EXP(2,3,4,5,6,7,0,1,46); SHA256_EXP(1,2,3,4,5,6,7,0,47); 310 | SHA256_EXP(0,1,2,3,4,5,6,7,48); SHA256_EXP(7,0,1,2,3,4,5,6,49); 311 | SHA256_EXP(6,7,0,1,2,3,4,5,50); SHA256_EXP(5,6,7,0,1,2,3,4,51); 312 | SHA256_EXP(4,5,6,7,0,1,2,3,52); SHA256_EXP(3,4,5,6,7,0,1,2,53); 313 | SHA256_EXP(2,3,4,5,6,7,0,1,54); SHA256_EXP(1,2,3,4,5,6,7,0,55); 314 | SHA256_EXP(0,1,2,3,4,5,6,7,56); SHA256_EXP(7,0,1,2,3,4,5,6,57); 315 | SHA256_EXP(6,7,0,1,2,3,4,5,58); SHA256_EXP(5,6,7,0,1,2,3,4,59); 316 | SHA256_EXP(4,5,6,7,0,1,2,3,60); SHA256_EXP(3,4,5,6,7,0,1,2,61); 317 | SHA256_EXP(2,3,4,5,6,7,0,1,62); SHA256_EXP(1,2,3,4,5,6,7,0,63); 318 | 319 | ctx->h[0] += wv[0]; ctx->h[1] += wv[1]; 320 | ctx->h[2] += wv[2]; ctx->h[3] += wv[3]; 321 | ctx->h[4] += wv[4]; ctx->h[5] += wv[5]; 322 | ctx->h[6] += wv[6]; ctx->h[7] += wv[7]; 323 | #endif /* !UNROLL_LOOPS */ 324 | } 325 | } 326 | 327 | void sha256(const unsigned char *message, unsigned int len, unsigned char *digest) 328 | { 329 | sha256_ctx ctx; 330 | 331 | sha256_init(&ctx); 332 | sha256_update(&ctx, message, len); 333 | sha256_final(&ctx, digest); 334 | } 335 | 336 | void sha256_init(sha256_ctx *ctx) 337 | { 338 | #ifndef UNROLL_LOOPS 339 | int i; 340 | for (i = 0; i < 8; i++) { 341 | ctx->h[i] = sha256_h0[i]; 342 | } 343 | #else 344 | ctx->h[0] = sha256_h0[0]; ctx->h[1] = sha256_h0[1]; 345 | ctx->h[2] = sha256_h0[2]; ctx->h[3] = sha256_h0[3]; 346 | ctx->h[4] = sha256_h0[4]; ctx->h[5] = sha256_h0[5]; 347 | ctx->h[6] = sha256_h0[6]; ctx->h[7] = sha256_h0[7]; 348 | #endif /* !UNROLL_LOOPS */ 349 | 350 | ctx->len = 0; 351 | ctx->tot_len = 0; 352 | } 353 | 354 | void sha256_update(sha256_ctx *ctx, const unsigned char *message, 355 | unsigned int len) 356 | { 357 | unsigned int block_nb; 358 | unsigned int new_len, rem_len, tmp_len; 359 | const unsigned char *shifted_message; 360 | 361 | tmp_len = SHA256_BLOCK_SIZE - ctx->len; 362 | rem_len = len < tmp_len ? len : tmp_len; 363 | 364 | memcpy(&ctx->block[ctx->len], message, rem_len); 365 | 366 | if (ctx->len + len < SHA256_BLOCK_SIZE) { 367 | ctx->len += len; 368 | return; 369 | } 370 | 371 | new_len = len - rem_len; 372 | block_nb = new_len / SHA256_BLOCK_SIZE; 373 | 374 | shifted_message = message + rem_len; 375 | 376 | sha256_transf(ctx, ctx->block, 1); 377 | sha256_transf(ctx, shifted_message, block_nb); 378 | 379 | rem_len = new_len % SHA256_BLOCK_SIZE; 380 | 381 | memcpy(ctx->block, &shifted_message[block_nb << 6], 382 | rem_len); 383 | 384 | ctx->len = rem_len; 385 | ctx->tot_len += (block_nb + 1) << 6; 386 | } 387 | 388 | void sha256_final(sha256_ctx *ctx, unsigned char *digest) 389 | { 390 | unsigned int block_nb; 391 | unsigned int pm_len; 392 | unsigned int len_b; 393 | 394 | #ifndef UNROLL_LOOPS 395 | int i; 396 | #endif 397 | 398 | block_nb = (1 + ((SHA256_BLOCK_SIZE - 9) 399 | < (ctx->len % SHA256_BLOCK_SIZE))); 400 | 401 | len_b = (ctx->tot_len + ctx->len) << 3; 402 | pm_len = block_nb << 6; 403 | 404 | memset(ctx->block + ctx->len, 0, pm_len - ctx->len); 405 | ctx->block[ctx->len] = 0x80; 406 | UNPACK32(len_b, ctx->block + pm_len - 4); 407 | 408 | sha256_transf(ctx, ctx->block, block_nb); 409 | 410 | #ifndef UNROLL_LOOPS 411 | for (i = 0 ; i < 8; i++) { 412 | UNPACK32(ctx->h[i], &digest[i << 2]); 413 | } 414 | #else 415 | UNPACK32(ctx->h[0], &digest[ 0]); 416 | UNPACK32(ctx->h[1], &digest[ 4]); 417 | UNPACK32(ctx->h[2], &digest[ 8]); 418 | UNPACK32(ctx->h[3], &digest[12]); 419 | UNPACK32(ctx->h[4], &digest[16]); 420 | UNPACK32(ctx->h[5], &digest[20]); 421 | UNPACK32(ctx->h[6], &digest[24]); 422 | UNPACK32(ctx->h[7], &digest[28]); 423 | #endif /* !UNROLL_LOOPS */ 424 | } 425 | 426 | /* SHA-512 functions */ 427 | 428 | void sha512_transf(sha512_ctx *ctx, const unsigned char *message, 429 | unsigned int block_nb) 430 | { 431 | uint64 w[80]; 432 | uint64 wv[8]; 433 | uint64 t1, t2; 434 | const unsigned char *sub_block; 435 | int i, j; 436 | 437 | for (i = 0; i < (int) block_nb; i++) { 438 | sub_block = message + (i << 7); 439 | 440 | #ifndef UNROLL_LOOPS 441 | for (j = 0; j < 16; j++) { 442 | PACK64(&sub_block[j << 3], &w[j]); 443 | } 444 | 445 | for (j = 16; j < 80; j++) { 446 | SHA512_SCR(j); 447 | } 448 | 449 | for (j = 0; j < 8; j++) { 450 | wv[j] = ctx->h[j]; 451 | } 452 | 453 | for (j = 0; j < 80; j++) { 454 | t1 = wv[7] + SHA512_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) 455 | + sha512_k[j] + w[j]; 456 | t2 = SHA512_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]); 457 | wv[7] = wv[6]; 458 | wv[6] = wv[5]; 459 | wv[5] = wv[4]; 460 | wv[4] = wv[3] + t1; 461 | wv[3] = wv[2]; 462 | wv[2] = wv[1]; 463 | wv[1] = wv[0]; 464 | wv[0] = t1 + t2; 465 | } 466 | 467 | for (j = 0; j < 8; j++) { 468 | ctx->h[j] += wv[j]; 469 | } 470 | #else 471 | PACK64(&sub_block[ 0], &w[ 0]); PACK64(&sub_block[ 8], &w[ 1]); 472 | PACK64(&sub_block[ 16], &w[ 2]); PACK64(&sub_block[ 24], &w[ 3]); 473 | PACK64(&sub_block[ 32], &w[ 4]); PACK64(&sub_block[ 40], &w[ 5]); 474 | PACK64(&sub_block[ 48], &w[ 6]); PACK64(&sub_block[ 56], &w[ 7]); 475 | PACK64(&sub_block[ 64], &w[ 8]); PACK64(&sub_block[ 72], &w[ 9]); 476 | PACK64(&sub_block[ 80], &w[10]); PACK64(&sub_block[ 88], &w[11]); 477 | PACK64(&sub_block[ 96], &w[12]); PACK64(&sub_block[104], &w[13]); 478 | PACK64(&sub_block[112], &w[14]); PACK64(&sub_block[120], &w[15]); 479 | 480 | SHA512_SCR(16); SHA512_SCR(17); SHA512_SCR(18); SHA512_SCR(19); 481 | SHA512_SCR(20); SHA512_SCR(21); SHA512_SCR(22); SHA512_SCR(23); 482 | SHA512_SCR(24); SHA512_SCR(25); SHA512_SCR(26); SHA512_SCR(27); 483 | SHA512_SCR(28); SHA512_SCR(29); SHA512_SCR(30); SHA512_SCR(31); 484 | SHA512_SCR(32); SHA512_SCR(33); SHA512_SCR(34); SHA512_SCR(35); 485 | SHA512_SCR(36); SHA512_SCR(37); SHA512_SCR(38); SHA512_SCR(39); 486 | SHA512_SCR(40); SHA512_SCR(41); SHA512_SCR(42); SHA512_SCR(43); 487 | SHA512_SCR(44); SHA512_SCR(45); SHA512_SCR(46); SHA512_SCR(47); 488 | SHA512_SCR(48); SHA512_SCR(49); SHA512_SCR(50); SHA512_SCR(51); 489 | SHA512_SCR(52); SHA512_SCR(53); SHA512_SCR(54); SHA512_SCR(55); 490 | SHA512_SCR(56); SHA512_SCR(57); SHA512_SCR(58); SHA512_SCR(59); 491 | SHA512_SCR(60); SHA512_SCR(61); SHA512_SCR(62); SHA512_SCR(63); 492 | SHA512_SCR(64); SHA512_SCR(65); SHA512_SCR(66); SHA512_SCR(67); 493 | SHA512_SCR(68); SHA512_SCR(69); SHA512_SCR(70); SHA512_SCR(71); 494 | SHA512_SCR(72); SHA512_SCR(73); SHA512_SCR(74); SHA512_SCR(75); 495 | SHA512_SCR(76); SHA512_SCR(77); SHA512_SCR(78); SHA512_SCR(79); 496 | 497 | wv[0] = ctx->h[0]; wv[1] = ctx->h[1]; 498 | wv[2] = ctx->h[2]; wv[3] = ctx->h[3]; 499 | wv[4] = ctx->h[4]; wv[5] = ctx->h[5]; 500 | wv[6] = ctx->h[6]; wv[7] = ctx->h[7]; 501 | 502 | j = 0; 503 | 504 | do { 505 | SHA512_EXP(0,1,2,3,4,5,6,7,j); j++; 506 | SHA512_EXP(7,0,1,2,3,4,5,6,j); j++; 507 | SHA512_EXP(6,7,0,1,2,3,4,5,j); j++; 508 | SHA512_EXP(5,6,7,0,1,2,3,4,j); j++; 509 | SHA512_EXP(4,5,6,7,0,1,2,3,j); j++; 510 | SHA512_EXP(3,4,5,6,7,0,1,2,j); j++; 511 | SHA512_EXP(2,3,4,5,6,7,0,1,j); j++; 512 | SHA512_EXP(1,2,3,4,5,6,7,0,j); j++; 513 | } while (j < 80); 514 | 515 | ctx->h[0] += wv[0]; ctx->h[1] += wv[1]; 516 | ctx->h[2] += wv[2]; ctx->h[3] += wv[3]; 517 | ctx->h[4] += wv[4]; ctx->h[5] += wv[5]; 518 | ctx->h[6] += wv[6]; ctx->h[7] += wv[7]; 519 | #endif /* !UNROLL_LOOPS */ 520 | } 521 | } 522 | 523 | void sha512(const unsigned char *message, unsigned int len, 524 | unsigned char *digest) 525 | { 526 | sha512_ctx ctx; 527 | 528 | sha512_init(&ctx); 529 | sha512_update(&ctx, message, len); 530 | sha512_final(&ctx, digest); 531 | } 532 | 533 | void sha512_init(sha512_ctx *ctx) 534 | { 535 | #ifndef UNROLL_LOOPS 536 | int i; 537 | for (i = 0; i < 8; i++) { 538 | ctx->h[i] = sha512_h0[i]; 539 | } 540 | #else 541 | ctx->h[0] = sha512_h0[0]; ctx->h[1] = sha512_h0[1]; 542 | ctx->h[2] = sha512_h0[2]; ctx->h[3] = sha512_h0[3]; 543 | ctx->h[4] = sha512_h0[4]; ctx->h[5] = sha512_h0[5]; 544 | ctx->h[6] = sha512_h0[6]; ctx->h[7] = sha512_h0[7]; 545 | #endif /* !UNROLL_LOOPS */ 546 | 547 | ctx->len = 0; 548 | ctx->tot_len = 0; 549 | } 550 | 551 | void sha512_update(sha512_ctx *ctx, const unsigned char *message, 552 | unsigned int len) 553 | { 554 | unsigned int block_nb; 555 | unsigned int new_len, rem_len, tmp_len; 556 | const unsigned char *shifted_message; 557 | 558 | tmp_len = SHA512_BLOCK_SIZE - ctx->len; 559 | rem_len = len < tmp_len ? len : tmp_len; 560 | 561 | memcpy(&ctx->block[ctx->len], message, rem_len); 562 | 563 | if (ctx->len + len < SHA512_BLOCK_SIZE) { 564 | ctx->len += len; 565 | return; 566 | } 567 | 568 | new_len = len - rem_len; 569 | block_nb = new_len / SHA512_BLOCK_SIZE; 570 | 571 | shifted_message = message + rem_len; 572 | 573 | sha512_transf(ctx, ctx->block, 1); 574 | sha512_transf(ctx, shifted_message, block_nb); 575 | 576 | rem_len = new_len % SHA512_BLOCK_SIZE; 577 | 578 | memcpy(ctx->block, &shifted_message[block_nb << 7], 579 | rem_len); 580 | 581 | ctx->len = rem_len; 582 | ctx->tot_len += (block_nb + 1) << 7; 583 | } 584 | 585 | void sha512_final(sha512_ctx *ctx, unsigned char *digest) 586 | { 587 | unsigned int block_nb; 588 | unsigned int pm_len; 589 | unsigned int len_b; 590 | 591 | #ifndef UNROLL_LOOPS 592 | int i; 593 | #endif 594 | 595 | block_nb = 1 + ((SHA512_BLOCK_SIZE - 17) 596 | < (ctx->len % SHA512_BLOCK_SIZE)); 597 | 598 | len_b = (ctx->tot_len + ctx->len) << 3; 599 | pm_len = block_nb << 7; 600 | 601 | memset(ctx->block + ctx->len, 0, pm_len - ctx->len); 602 | ctx->block[ctx->len] = 0x80; 603 | UNPACK32(len_b, ctx->block + pm_len - 4); 604 | 605 | sha512_transf(ctx, ctx->block, block_nb); 606 | 607 | #ifndef UNROLL_LOOPS 608 | for (i = 0 ; i < 8; i++) { 609 | UNPACK64(ctx->h[i], &digest[i << 3]); 610 | } 611 | #else 612 | UNPACK64(ctx->h[0], &digest[ 0]); 613 | UNPACK64(ctx->h[1], &digest[ 8]); 614 | UNPACK64(ctx->h[2], &digest[16]); 615 | UNPACK64(ctx->h[3], &digest[24]); 616 | UNPACK64(ctx->h[4], &digest[32]); 617 | UNPACK64(ctx->h[5], &digest[40]); 618 | UNPACK64(ctx->h[6], &digest[48]); 619 | UNPACK64(ctx->h[7], &digest[56]); 620 | #endif /* !UNROLL_LOOPS */ 621 | } 622 | 623 | /* SHA-384 functions */ 624 | 625 | void sha384(const unsigned char *message, unsigned int len, 626 | unsigned char *digest) 627 | { 628 | sha384_ctx ctx; 629 | 630 | sha384_init(&ctx); 631 | sha384_update(&ctx, message, len); 632 | sha384_final(&ctx, digest); 633 | } 634 | 635 | void sha384_init(sha384_ctx *ctx) 636 | { 637 | #ifndef UNROLL_LOOPS 638 | int i; 639 | for (i = 0; i < 8; i++) { 640 | ctx->h[i] = sha384_h0[i]; 641 | } 642 | #else 643 | ctx->h[0] = sha384_h0[0]; ctx->h[1] = sha384_h0[1]; 644 | ctx->h[2] = sha384_h0[2]; ctx->h[3] = sha384_h0[3]; 645 | ctx->h[4] = sha384_h0[4]; ctx->h[5] = sha384_h0[5]; 646 | ctx->h[6] = sha384_h0[6]; ctx->h[7] = sha384_h0[7]; 647 | #endif /* !UNROLL_LOOPS */ 648 | 649 | ctx->len = 0; 650 | ctx->tot_len = 0; 651 | } 652 | 653 | void sha384_update(sha384_ctx *ctx, const unsigned char *message, 654 | unsigned int len) 655 | { 656 | unsigned int block_nb; 657 | unsigned int new_len, rem_len, tmp_len; 658 | const unsigned char *shifted_message; 659 | 660 | tmp_len = SHA384_BLOCK_SIZE - ctx->len; 661 | rem_len = len < tmp_len ? len : tmp_len; 662 | 663 | memcpy(&ctx->block[ctx->len], message, rem_len); 664 | 665 | if (ctx->len + len < SHA384_BLOCK_SIZE) { 666 | ctx->len += len; 667 | return; 668 | } 669 | 670 | new_len = len - rem_len; 671 | block_nb = new_len / SHA384_BLOCK_SIZE; 672 | 673 | shifted_message = message + rem_len; 674 | 675 | sha512_transf(ctx, ctx->block, 1); 676 | sha512_transf(ctx, shifted_message, block_nb); 677 | 678 | rem_len = new_len % SHA384_BLOCK_SIZE; 679 | 680 | memcpy(ctx->block, &shifted_message[block_nb << 7], 681 | rem_len); 682 | 683 | ctx->len = rem_len; 684 | ctx->tot_len += (block_nb + 1) << 7; 685 | } 686 | 687 | void sha384_final(sha384_ctx *ctx, unsigned char *digest) 688 | { 689 | unsigned int block_nb; 690 | unsigned int pm_len; 691 | unsigned int len_b; 692 | 693 | #ifndef UNROLL_LOOPS 694 | int i; 695 | #endif 696 | 697 | block_nb = (1 + ((SHA384_BLOCK_SIZE - 17) 698 | < (ctx->len % SHA384_BLOCK_SIZE))); 699 | 700 | len_b = (ctx->tot_len + ctx->len) << 3; 701 | pm_len = block_nb << 7; 702 | 703 | memset(ctx->block + ctx->len, 0, pm_len - ctx->len); 704 | ctx->block[ctx->len] = 0x80; 705 | UNPACK32(len_b, ctx->block + pm_len - 4); 706 | 707 | sha512_transf(ctx, ctx->block, block_nb); 708 | 709 | #ifndef UNROLL_LOOPS 710 | for (i = 0 ; i < 6; i++) { 711 | UNPACK64(ctx->h[i], &digest[i << 3]); 712 | } 713 | #else 714 | UNPACK64(ctx->h[0], &digest[ 0]); 715 | UNPACK64(ctx->h[1], &digest[ 8]); 716 | UNPACK64(ctx->h[2], &digest[16]); 717 | UNPACK64(ctx->h[3], &digest[24]); 718 | UNPACK64(ctx->h[4], &digest[32]); 719 | UNPACK64(ctx->h[5], &digest[40]); 720 | #endif /* !UNROLL_LOOPS */ 721 | } 722 | 723 | /* SHA-224 functions */ 724 | 725 | void sha224(const unsigned char *message, unsigned int len, 726 | unsigned char *digest) 727 | { 728 | sha224_ctx ctx; 729 | 730 | sha224_init(&ctx); 731 | sha224_update(&ctx, message, len); 732 | sha224_final(&ctx, digest); 733 | } 734 | 735 | void sha224_init(sha224_ctx *ctx) 736 | { 737 | #ifndef UNROLL_LOOPS 738 | int i; 739 | for (i = 0; i < 8; i++) { 740 | ctx->h[i] = sha224_h0[i]; 741 | } 742 | #else 743 | ctx->h[0] = sha224_h0[0]; ctx->h[1] = sha224_h0[1]; 744 | ctx->h[2] = sha224_h0[2]; ctx->h[3] = sha224_h0[3]; 745 | ctx->h[4] = sha224_h0[4]; ctx->h[5] = sha224_h0[5]; 746 | ctx->h[6] = sha224_h0[6]; ctx->h[7] = sha224_h0[7]; 747 | #endif /* !UNROLL_LOOPS */ 748 | 749 | ctx->len = 0; 750 | ctx->tot_len = 0; 751 | } 752 | 753 | void sha224_update(sha224_ctx *ctx, const unsigned char *message, 754 | unsigned int len) 755 | { 756 | unsigned int block_nb; 757 | unsigned int new_len, rem_len, tmp_len; 758 | const unsigned char *shifted_message; 759 | 760 | tmp_len = SHA224_BLOCK_SIZE - ctx->len; 761 | rem_len = len < tmp_len ? len : tmp_len; 762 | 763 | memcpy(&ctx->block[ctx->len], message, rem_len); 764 | 765 | if (ctx->len + len < SHA224_BLOCK_SIZE) { 766 | ctx->len += len; 767 | return; 768 | } 769 | 770 | new_len = len - rem_len; 771 | block_nb = new_len / SHA224_BLOCK_SIZE; 772 | 773 | shifted_message = message + rem_len; 774 | 775 | sha256_transf(ctx, ctx->block, 1); 776 | sha256_transf(ctx, shifted_message, block_nb); 777 | 778 | rem_len = new_len % SHA224_BLOCK_SIZE; 779 | 780 | memcpy(ctx->block, &shifted_message[block_nb << 6], 781 | rem_len); 782 | 783 | ctx->len = rem_len; 784 | ctx->tot_len += (block_nb + 1) << 6; 785 | } 786 | 787 | void sha224_final(sha224_ctx *ctx, unsigned char *digest) 788 | { 789 | unsigned int block_nb; 790 | unsigned int pm_len; 791 | unsigned int len_b; 792 | 793 | #ifndef UNROLL_LOOPS 794 | int i; 795 | #endif 796 | 797 | block_nb = (1 + ((SHA224_BLOCK_SIZE - 9) 798 | < (ctx->len % SHA224_BLOCK_SIZE))); 799 | 800 | len_b = (ctx->tot_len + ctx->len) << 3; 801 | pm_len = block_nb << 6; 802 | 803 | memset(ctx->block + ctx->len, 0, pm_len - ctx->len); 804 | ctx->block[ctx->len] = 0x80; 805 | UNPACK32(len_b, ctx->block + pm_len - 4); 806 | 807 | sha256_transf(ctx, ctx->block, block_nb); 808 | 809 | #ifndef UNROLL_LOOPS 810 | for (i = 0 ; i < 7; i++) { 811 | UNPACK32(ctx->h[i], &digest[i << 2]); 812 | } 813 | #else 814 | UNPACK32(ctx->h[0], &digest[ 0]); 815 | UNPACK32(ctx->h[1], &digest[ 4]); 816 | UNPACK32(ctx->h[2], &digest[ 8]); 817 | UNPACK32(ctx->h[3], &digest[12]); 818 | UNPACK32(ctx->h[4], &digest[16]); 819 | UNPACK32(ctx->h[5], &digest[20]); 820 | UNPACK32(ctx->h[6], &digest[24]); 821 | #endif /* !UNROLL_LOOPS */ 822 | } 823 | 824 | #ifdef TEST_VECTORS 825 | 826 | /* FIPS 180-2 Validation tests */ 827 | 828 | #include 829 | #include 830 | 831 | void test(const unsigned char *vector, unsigned char *digest, 832 | unsigned int digest_size) 833 | { 834 | unsigned char output[2 * SHA512_DIGEST_SIZE + 1]; 835 | int i; 836 | 837 | output[2 * digest_size] = '\0'; 838 | 839 | for (i = 0; i < (int) digest_size ; i++) { 840 | sprintf((char *) output + 2 * i, "%02x", digest[i]); 841 | } 842 | 843 | printf("H: %s\n", output); 844 | if (strcmp((char *) vector, (char *) output)) { 845 | fprintf(stderr, "Test failed.\n"); 846 | exit(EXIT_FAILURE); 847 | } 848 | } 849 | 850 | int main() 851 | { 852 | static const unsigned char *vectors[4][3] = 853 | { /* SHA-224 */ 854 | { 855 | "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", 856 | "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525", 857 | "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67", 858 | }, 859 | /* SHA-256 */ 860 | { 861 | "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", 862 | "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", 863 | "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0", 864 | }, 865 | /* SHA-384 */ 866 | { 867 | "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed" 868 | "8086072ba1e7cc2358baeca134c825a7", 869 | "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712" 870 | "fcc7c71a557e2db966c3e9fa91746039", 871 | "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b" 872 | "07b8b3dc38ecc4ebae97ddd87f3d8985", 873 | }, 874 | /* SHA-512 */ 875 | { 876 | "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" 877 | "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", 878 | "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" 879 | "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909", 880 | "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" 881 | "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b" 882 | } 883 | }; 884 | 885 | static const unsigned char message1[] = "abc"; 886 | static const unsigned char message2a[] = "abcdbcdecdefdefgefghfghighijhi" 887 | "jkijkljklmklmnlmnomnopnopq"; 888 | static const unsigned char message2b[] = 889 | "abcdefghbcdefghicdefghijdefghijkefghij" 890 | "klfghijklmghijklmnhijklmnoijklmnopjklm" 891 | "nopqklmnopqrlmnopqrsmnopqrstnopqrstu"; 892 | unsigned char *message3; 893 | unsigned int message3_len = 1000000; 894 | unsigned char digest[SHA512_DIGEST_SIZE]; 895 | 896 | message3 = malloc(message3_len); 897 | if (message3 == NULL) { 898 | fprintf(stderr, "Can't allocate memory\n"); 899 | return -1; 900 | } 901 | memset(message3, 'a', message3_len); 902 | 903 | printf("SHA-2 FIPS 180-2 Validation tests\n\n"); 904 | printf("SHA-224 Test vectors\n"); 905 | 906 | sha224(message1, strlen((char *) message1), digest); 907 | test(vectors[0][0], digest, SHA224_DIGEST_SIZE); 908 | sha224(message2a, strlen((char *) message2a), digest); 909 | test(vectors[0][1], digest, SHA224_DIGEST_SIZE); 910 | sha224(message3, message3_len, digest); 911 | test(vectors[0][2], digest, SHA224_DIGEST_SIZE); 912 | printf("\n"); 913 | 914 | printf("SHA-256 Test vectors\n"); 915 | 916 | sha256(message1, strlen((char *) message1), digest); 917 | test(vectors[1][0], digest, SHA256_DIGEST_SIZE); 918 | sha256(message2a, strlen((char *) message2a), digest); 919 | test(vectors[1][1], digest, SHA256_DIGEST_SIZE); 920 | sha256(message3, message3_len, digest); 921 | test(vectors[1][2], digest, SHA256_DIGEST_SIZE); 922 | printf("\n"); 923 | 924 | printf("SHA-384 Test vectors\n"); 925 | 926 | sha384(message1, strlen((char *) message1), digest); 927 | test(vectors[2][0], digest, SHA384_DIGEST_SIZE); 928 | sha384(message2b, strlen((char *) message2b), digest); 929 | test(vectors[2][1], digest, SHA384_DIGEST_SIZE); 930 | sha384(message3, message3_len, digest); 931 | test(vectors[2][2], digest, SHA384_DIGEST_SIZE); 932 | printf("\n"); 933 | 934 | printf("SHA-512 Test vectors\n"); 935 | 936 | sha512(message1, strlen((char *) message1), digest); 937 | test(vectors[3][0], digest, SHA512_DIGEST_SIZE); 938 | sha512(message2b, strlen((char *) message2b), digest); 939 | test(vectors[3][1], digest, SHA512_DIGEST_SIZE); 940 | sha512(message3, message3_len, digest); 941 | test(vectors[3][2], digest, SHA512_DIGEST_SIZE); 942 | printf("\n"); 943 | 944 | printf("All tests passed.\n"); 945 | 946 | return 0; 947 | } 948 | 949 | #endif /* TEST_VECTORS */ 950 | 951 | --------------------------------------------------------------------------------