mutecomm / go-sqlcipher Goto Github PK
View Code? Open in Web Editor NEWSelf-contained Go sqlite3 driver with an AES-256 encrypted sqlite3 database
License: Other
Self-contained Go sqlite3 driver with an AES-256 encrypted sqlite3 database
License: Other
it can build on win7 ,but exit with exit status -1073741515
I've tried:
env GOOS=linux GOARCH=amd64 go build
but it shows:
go build github.com/mutecomm/go-sqlcipher: no buildable Go source files in /Users/asd/MEGA/go/src/github.com/mutecomm/go-sqlcipher
OS: Mac OSX latest
Arch: amd64
but it works fine if not using mutecomm/go-sqlcipher
Installing github.com/gobuffalo/buffalo/buffalo and I got this warning.
# github.com/mutecomm/go-sqlcipher
../../go/src/github.com/mutecomm/go-sqlcipher/sqlite3.c:20897:17: warning: 'OSAtomicCompareAndSwapPtrBarrier' is deprecated: first deprecated in macOS 10.12 - Use atomic_compare_exchange_strong() from <stdatomic.h> instead [-Wdeprecated-declarations]
/usr/include/libkern/OSAtomicDeprecated.h:547:6: note: 'OSAtomicCompareAndSwapPtrBarrier' has been explicitly marked deprecated here
Hi, @frankbraun , thanks for your awesome library!
A newer version of SQLite and SQLCipher has been released. Could you upgrade it to latest version?
Can someone please provide steps or mechanism to migrate existing SQLCipher 3.x databases to SQLCipher 4.x
we are getting below errors "file is not a database" when trying to read old database files with new package code.
I'm leveraging golang-migrate to do database schema init & update.
Aligned with go-sqlcipher, it always pops up the following error:
# command-line-arguments c:\go\pkg\tool\windows_amd64\link.exe: running gcc failed: exit status 1 C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000053.o: in function
sqlite3_status64':
C:\Users\Administrator\go\pkg\mod\github.com\mattn\[email protected]/sqlite3-binding.c:20370: multiple definition of sqlite3_status64'; C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000033.o:C:\Users\Administrator\go\pkg\mod\github.com\mutecomm\go-sqlcipher\[email protected]/sqlite3.c:26352: first defined here C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000053.o: in function
sqlite3_status':
C:\Users\Administrator\go\pkg\mod\github.com\mattn\[email protected]/sqlite3-binding.c:20390: multiple definition of sqlite3_status'; C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000033.o:C:\Users\Administrator\go\pkg\mod\github.com\mutecomm\go-sqlcipher\[email protected]/sqlite3.c:26372: first defined here C...
Hi, thanks for this nice module, I had trouble using other sqlite encryption modules, this simply works.
One question: Is the package safe to be used by multiple goroutines? i. e.: I use the sqlite file as the database for a small webservice that could potentially handle many requests at once. Therefore I have to assume that database writes may happen concurrently.
Thanks in advance
Noticed there has a macro SQLITE_WIN32_HAS_WIDE
, and also define in sqlite3.c, but seems not works. What to do to make the database longer than 260?
I change MAX_PATH
to another value, also not works.
Thanks.
I am unable to open an encrypted database file that was created using this library with sqlcipher's CLI.
This is my example Go program that creates a database and inserts a record in a table:
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/mutecomm/go-sqlcipher/v4"
)
func wrapErr(err, deferErr error) error {
if err == nil {
return deferErr
}
if deferErr == nil {
return err
}
return fmt.Errorf("%s: %w", err.Error(), deferErr)
}
func run(ctx context.Context) (err error) {
if len(os.Args) != 2 {
err = fmt.Errorf("Usage: %s <password>", os.Args[0])
return
}
password := os.Args[1]
// https://www.zetetic.net/sqlcipher/sqlcipher-api/#PRAGMA_key
urn := fmt.Sprintf("file:%s?_pragma_key='%s'&_pragma_cipher_page_size=4096", "example.sqlite3", password)
db, err := sql.Open("sqlite3", urn)
if err != nil {
return
}
defer func() {
err = wrapErr(err, db.Close())
}()
_, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS example_table (id INTEGER PRIMARY KEY, foo TEXT NOT NULL)`)
if err != nil {
return
}
res, err := db.ExecContext(ctx, `INSERT INTO example_table (foo) VALUES (?)`, fmt.Sprintf("some record inserted at %s", time.Now()))
if err != nil {
return
}
id, err := res.LastInsertId()
if err != nil {
return
}
log.Println("inserted record with ID:", id)
return
}
func main() {
err := run(context.TODO())
if err != nil {
log.Fatal(err)
}
}
And here's how to reproduce the issue:
$ go version
go version go1.15 linux/amd64
$ go run main.go thisismypassword
2020/08/21 17:19:35 inserted record with ID: 1
$ sqlcipher -version
3.31.0 2020-01-22 18:38:59 f6affdd41608946fcfcea914ece149038a8b25a62bbe719ed2561c649b86alt1 (SQLCipher 4.4.0 community)
$ sqlcipher
> PRAGMA key='thisismypassword';
> PRAGMA cipher_page_size=4096;
> .open 'example.sqlite3';
> SELECT * FROM example_table;
Error: file is not a database
I hpoe support multy pragam just like add code bellow:
pragmaMap := map[string]string{}
pragmaKey := ""
pragmaCipherPageSize := -1
pos := strings.IndexRune(dsn, '?')
if pos >= 1 {
params, err := url.ParseQuery(dsn[pos+1:])
if err != nil {
return nil, err
}
// support multi pragma
for key, strArr := range params {
if strings.Contains(key, "_pragma_") {
pragmaMap[key[8:]] = strArr[0]
}
}
.....
}
// _pragma_key
if pragmaKey != "" {
query := fmt.Sprintf("PRAGMA key = \"%s\";", pragmaKey)
if err := exec(query); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// _pragma_cipher_page_size
if pragmaCipherPageSize != -1 {
query := fmt.Sprintf("PRAGMA cipher_page_size = %d;",
pragmaCipherPageSize)
if err := exec(query); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// support multi pragma
for key, val := range pragmaMap {
if val != "" && key != "key" && key != "cipher_page_size" {
query := fmt.Sprintf("PRAGMA %s = %s;", key, val)
if err := exec(query); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
}
Hi, thanks for the great library!
I noticed in the LICENSE that the license for all the dependencies are added, but the license doesn't mention the code in this repository.
Is there an official license for the code directly contributed to this repo?
Can you please let me the value of KDF itereations , HMAC algo used and KDF algo used. If page size is 4096
go get github.com/mutecomm/go-sqlcipher
report many errors about pthread, you can just modify sqlite3_windows.go
such as:
crypt_cipher_is_valid.c:25: undefined reference to _imp__pthread_mutex_lock' crypt_cipher_is_valid.c:30: undefined reference to
_imp__pthread_mutex_unlock'
crypt_cipher_is_valid.c:27: undefined reference to _imp__pthread_mutex_unlock' crypt_find_cipher.o: In function
find_cipher':
crypt_find_cipher.c:27: undefined reference to _imp__pthread_mutex_lock' crypt_find_cipher.c:30: undefined reference to
_imp__pthread_mutex_unlock'
crypt_find_cipher.c:34: undefined reference to _imp__pthread_mutex_unlock' crypt_find_hash.o: In function
find_hash':
crypt_find_hash.c:27: undefined reference to _imp__pthread_mutex_lock' crypt_find_hash.c:30: undefined reference to
_imp__pthread_mutex_unlock'
crypt_find_hash.c:34: undefined reference to _imp__pthread_mutex_unlock' crypt_hash_is_valid.o: In function
hash_is_valid':
crypt_hash_is_valid.c:25: undefined reference to _imp__pthread_mutex_lock' crypt_hash_is_valid.c:30: undefined reference to
_imp__pthread_mutex_unlock'
crypt_hash_is_valid.c:27: undefined reference to _imp__pthread_mutex_unlock' crypt_register_cipher.o: In function
register_cipher':
crypt_register_cipher.c:30: undefined reference to _imp__pthread_mutex_lock' crypt_register_cipher.c:42: undefined reference to
_imp__pthread_mutex_unlock'
crypt_register_cipher.c:48: undefined reference to _imp__pthread_mutex_unlock' crypt_register_hash.o: In function
register_hash':
crypt_register_hash.c:30: undefined reference to _imp__pthread_mutex_lock' crypt_register_hash.c:42: undefined reference to
_imp__pthread_mutex_unlock'
crypt_register_hash.c:48: undefined reference to _imp__pthread_mutex_unlock' crypt_register_prng.o: In function
register_prng':
crypt_register_prng.c:30: undefined reference to `_imp__pthread_mutex_lock'
Hi @frankbraun @klingtnet @nkbai @JonathanLogan
go-sqlite3 affected by vulnerability CVE-2022-35737. Can we please update sqlite3 code to latest 3.39.2?
Go sqlite3 driver: https://github.com/mattn/go-sqlite3
Seems above package code is we are using here. They updated the sqlite3 code to latest to fix the vulnerability CVE-2022-35737.
Below is the commit details they did:
mattn/go-sqlite3@d8e192b
Please update our sqlite source code also to latest.
Thanks,
Durgababu
Hi,
I am trying to write a commandline client for Enpass 6.x password vaults.
These are stored on regular sqlite databases as attached. enpassvault.zip
However, every query will return file is not a database
while the Python version seems to work fine.
Any idea?
https://github.com/hazcod/enpass-cli-test
% go run main.go
2020/12/07 09:55:14 printing tables
2020/12/07 09:55:15 could not retrieve crypto parameters: could not query crypto parameters: file is not a database
exit status 1
I compile sqlcipher in Windows and generated an encrypted db file like this:
#include <iostream>
#include <string.h>
#include "sqlite3.h"
using namespace std;
static int callback(void* notUsed, int argc, char** argv, char** azColName)
{
for (int i = 0; i < argc; i++)
cout << azColName[i] << ":" << (argv[i] ? argv[i] : "NULL") << "\t";
cout << endl;
return 0;
}
void dbTest()
{
#pragma region 打开或创建数据库
/*打开或创建的数据库实例句柄*/
sqlite3* db = NULL;
/*数据库文件的路径及文件名*/
const char* path = "./sqlcipher.db";
/*根据文件路径打开数据库连接。如果数据库不存在,则创建。数据库文件的路径必须以C字符串传入*/
int result = sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_SHAREDCACHE, NULL);
if (result == SQLITE_OK)
cout << "打开或创建数据库成功" << endl;
else
cout << "打开或创建数据库失败" << endl;
sqlite3_close(db);
#pragma endregion
#pragma region 指定数据库密码
const char* pwd = "abcdefg";
result = sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_CREATE, NULL);
if (result == SQLITE_OK)
cout << "打开数据库成功" << endl;
else
cout << "打开数据库失败" << endl;
result = sqlite3_key(db, pwd, strnlen(pwd, 1000));
cout << "指定数据库密码是否成功:" << result << endl;
char* errmsg;
//sqlite3_exec(db, "PRAGMA key = \"'abcdefg'\";", NULL, NULL, &errmsg);
//if (result == SQLITE_OK)
//{
// cout << "SQL 语句执行成功" << endl;
//}
//else
//{
// cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
//}
#pragma endregion
#pragma region 执行SQL语句
result = sqlite3_exec(db, "CREATE TABLE [t1](id integer PRIMARY KEY AUTOINCREMENT UNIQUE, name varchar);", NULL, NULL, &errmsg);
if (result == SQLITE_OK)
{
cout << "SQL 语句执行成功" << endl;
}
else
{
cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
}
result = sqlite3_exec(db, "INSERT INTO t1(name) VALUES('张三');", NULL, NULL, &errmsg);
if (result == SQLITE_OK)
{
cout << "SQL 语句执行成功" << endl;
}
else
{
cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
}
result = sqlite3_exec(db, "SELECT * FROM t1;", callback, NULL, &errmsg);
if (result == SQLITE_OK)
{
cout << "SQL 语句执行成功" << endl;
}
else
{
cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
}
#pragma endregion
sqlite3_close(db);
}
int main()
{
std::cout << "Hello World!\n";
dbTest();
char sz[] = "End !";
cout << sz << endl;
return 0;
}
then I want to use it in Go project, code like this:
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/mutecomm/go-sqlcipher/v4"
)
func main() {
key := "abcdefg"
dbname := fmt.Sprintf("sqlcipher.db?_pragma_key=x'%s'", key)
db, err := sql.Open("sqlite3", dbname)
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Exec("SELECT * FROM t1;")
if err != nil {
return
}
fmt.Println(rows)
}
when execute:
rows, err := db.Exec("SELECT * FROM t1;")
throw an error: file is not a database.
Any hints?
Upgrading the version by cloning the code and running the script make the database not encrypted.
The tag is v3.4.2, but the go module name is github.com/mutecomm/go-sqlcipher, which is not right. Should be changed to github.com/mutecomm/go-sqlcipher/v3
I have a password (hex, 64 len). And I have some other options. For now, I don't know how to specify those option. I have tried three ways. But none of those works, the error is file is not a database
.
Tried 1:
param_str := "_pragma_cipher_page_size=4096&_cipher_compatibility=3&_cipher_page_size=4096&_synchronous=NORMAL&_count_changes=OFF&_auto_vacuum=0&_journal_mode=WAL"
dbname := fmt.Sprintf("%s?_pragma_key=x'%s'&%s", dbPath, dbPwd, param_str)
db, err := sql.Open("sqlcipher", dbname)
Tried 2:
sql.Register("sqlcipher", &sqlcipher.SQLiteDriver{
ConnectHook: func(conn *sqlcipher.SQLiteConn) error {
// fmt.Println("sqlcipher PRAGMA called")
conn.Exec("PRAGMA cipher_compatibility = 3", nil)
conn.Exec("PRAGMA cipher_page_size = 4096", nil)
conn.Exec("PRAGMA synchronous=NORMAL", nil)
conn.Exec("PRAGMA count_changes=OFF", nil)
conn.Exec("PRAGMA auto_vacuum=0", nil)
conn.Exec("PRAGMA journal_mode = WAL", nil)
return nil
},
})
db, err := sql.Open("sqlcipher", dbname)
Tried 3:
db, err := sql.Open("sqlcipher", dbname)
if err != nil {
log.Panic(err.Error())
}
db.Exec("PRAGMA cipher_compatibility=3")
db.Exec("PRAGMA cipher_page_size=4096")
db.Exec("PRAGMA synchronous=NORMAL")
db.Exec("PRAGMA count_changes=OFF")
db.Exec("PRAGMA auto_vacuum=0")
db.Exec("PRAGMA journal_mode=WAL")
What I want is specify the key and those pragma. What is the right way. Thank you!
Question.
I'm currently doing something like this:
conn, err := sql.Open("sqlite3", dbPath)
if err != nil {
return nil, err
}
if password != "" {
p := "pragma key='" + password + "';"
conn.Exec(p)
}
Immediately following this code I query to check to see if the db decrypted properly and it does. But then a minute or so later I start getting a file is encrypted or is not a database
error. I'm not closing the connection. Just making queries on the existing instance.
Am I using this wrong? Is there some kind of timeout that re-encrypts it shortly after decryption? Do I need to re-call pragma key=
before each db query?
I would like to confirm this kind of information, is there any method?
Before using go-sqlcipher
, I was using gorm
+ sqilte3 and everything was working fine.
After I switched from sqlite3
to go-sqlcipher
, I get an error at runtime like this:
file is not a database
When do some query like:
db.Where().Find()
Where did this go wrong? any clue to resolve this probelem?
hi, i need to use this package and enable json_extract features, i tried to modify sqlite3.c and try to enable json_extract but it does not work, is there anyway to activate it? since the code is already there. thank you
Using 4.4.2 can successfully add table column, but cannot drop table column.
I checked sqlite version-3.38.0 to support drop column.
Could you update the sqlite that go-sqlcipher depends on to support drop column?
Do you have a plan to update codes from mattn/go-sqlite3?
I wanna use this method.
// from mattn/go-sqlite3
func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error
https://github.com/mattn/go-sqlite3/blob/2a192bf7823799e082cfa3380aab9f02e4d312c0/sqlite3.go#L551
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.