Programing

암호화 / 암호 보호 기능이있는 SQLite

crosscheck 2020. 7. 13. 20:33
반응형

암호화 / 암호 보호 기능이있는 SQLite


나는 단지 SQLite를 사용하는 법을 배우고 있는데 가능하다면 궁금합니다.

  1. 데이터베이스 파일의 암호화?

  2. 데이터베이스 열기를 비밀번호로 보호 하시겠습니까?

추신. 이 "SEE (SQLite Encryption Extension)"가 있다는 것을 알고 있지만 설명서에 따르면 "SEE는 라이센스가있는 소프트웨어입니다 ..."및 "SEE의 영구적 인 소스 코드 라이센스 비용은 US $ 2000입니다."


SQLite에는 정규 배포에 사용되지 않는 암호화 용 후크가 내장되어 있지만 다음과 같은 몇 가지 구현이 있습니다.

  • 참조 -공식 구현.
  • wxSQLite -SQLite의 암호화도 구현하는 wxWidgets 스타일 C ++ 래퍼입니다.
  • SQLCipher -openSSL의 libcrypto를 사용하여 구현합니다.
  • SQLiteCrypt- 사용자 정의 구현, 수정 된 API.
  • botansqlite3 -botansqlite3은 암호화를 위해 Botan의 모든 알고리즘을 사용할 수있는 SQLite3 용 암호화 코덱입니다.

SEE 및 SQLiteCrypt는 라이센스 구매가 필요합니다.

공개 : 나는 botansqlite3을 만들었습니다.


SQLite3 DB를 비밀번호로 보호 할 수 있습니다. 작업을 수행하기 전에 처음으로 다음과 같이 비밀번호를 설정하십시오.

SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.open();

다음에 다음과 같이 액세스 할 수 있습니다.

conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();

이렇게하면 GUI 편집기에서 데이터를 볼 수 없습니다. 나중에 비밀번호를 변경 conn.ChangePassword("new_password");하려면 다음을 사용 하십시오. 비밀번호를 재설정하거나 제거하려면conn.ChangePassword(String.Empty);


.net 라이브러리 System.Data.SQLite 도 암호화를 제공합니다.


http://system.data.sqlite.org/sqlite3.dll 에서 암호화 지원 파일을 얻을 수 있습니다 .

1- http ://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki로 이동 하여 패키지 중 하나를 다운로드하십시오. .NET 버전은 여기와 관련이 없습니다.

2- SQLite.Interop.dll패키지에서 추출 하여 이름을 바꿉니다 sqlite3.dll. 이 DLL은 일반 텍스트 비밀번호 또는 암호화 키를 통한 암호화를 지원합니다.

언급 된 파일은 기본 파일이며 .NET 프레임 워크가 필요 하지 않습니다 . 다운로드 한 패키지에 따라 Visual C ++ 런타임이 필요할 수 있습니다.

최신 정보

이것은 32 비트 개발을 위해 다운로드 한 패키지입니다 : http://system.data.sqlite.org/blobs/1.0.94.0/sqlite-netFx40-static-binary-Win32-2010-1.0.94.0.zip


확실히 가능하며 SEE 외에 몇 가지 오픈 소스 솔루션이 있습니다. 그중에는 wxSQLite3와 함께 제공되는 암호화 확장 기능이 있습니다. 자세한 내용은 비슷한 질문에 대한 답변을 참조하십시오.


다음은 적절한 보안 솔루션을 대체하기위한 것이 아닙니다.

4 일 동안이 문제를 해결 한 후에 NuGet의 오픈 소스 System.Data.SQLite 패키지 만 사용하여 솔루션을 구성했습니다. 이것이 얼마나 많은 보호를 제공하는지 모르겠습니다. 나는 내 자신의 학습 과정에만 사용하고 있습니다. 그러면 DB가 생성되고 암호화되어 테이블이 생성되며 데이터가 추가됩니다.

using System.Data.SQLite;

namespace EncryptDB
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = @"C:\Programming\sqlite3\db.db";
            string passwordString = "password";
            byte[] passwordBytes = GetBytes(passwordString);
            SQLiteConnection.CreateFile(connectionString);
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
            conn.SetPassword(passwordBytes);
            conn.Open();
            SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
            sqlCmd.ExecuteNonQuery();
            sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
            sqlCmd.ExecuteNonQuery();
            conn.Close();
        }
        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            bytes = System.Text.Encoding.Default.GetBytes(str);
            return bytes;
        }
    }
}

선택적으로을 제거 conn.SetPassword(passwordBytes);하고 이전 대신에 conn.ChangePassword("password");배치해야하는로 교체 할 수 있습니다 conn.Open();. 그러면 GetBytes 메서드가 필요하지 않습니다.

To decrypt, it's just a matter of putting the password in your connection string before the call to open.

        string filename = @"C:\Programming\sqlite3\db.db";
        string passwordString = "password";
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
        conn.Open();

You can always encrypt data on the client side. Please note that not all of the data have to be encrypted because it has a performance issue.


Well, SEE is expensive. However SQLite has interface built-in for encryption (Pager). This means, that on top of existing code one can easily develop some encryption mechanism, does not have to be AES. Anything really. Please see my post here: https://stackoverflow.com/a/49161716/9418360

You need to define SQLITE_HAS_CODEC=1 to enable Pager encryption. Sample code below (original SQLite source):

#ifdef SQLITE_HAS_CODEC
/*
** This function is called by the wal module when writing page content
** into the log file.
**
** This function returns a pointer to a buffer containing the encrypted
** page content. If a malloc fails, this function may return NULL.
*/
SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  void *aData = 0;
  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  return aData;
}
#endif

There is a commercial version in C language for SQLite encryption using AES256 - it can also work with PHP, but it needs to be compiled with PHP and SQLite extension. It de/encrypts SQLite database file on the fly, file contents are always encrypted. Very useful.

http://www.iqx7.com/products/sqlite-encryption


You can use SQLite's function creation routines (PHP manual):

$db_obj->sqliteCreateFunction('Encrypt', 'MyEncryptFunction', 2);
$db_obj->sqliteCreateFunction('Decrypt', 'MyDecryptFunction', 2);

When inserting data, you can use the encryption function directly and INSERT the encrypted data or you can use the custom function and pass unencrypted data:

$insert_obj = $db_obj->prepare('INSERT INTO table (Clear, Encrypted) ' .
 'VALUES (:clear, Encrypt(:data, "' . $passwordhash_str . '"))');

When retrieving data, you can also use SQL search functionality:

$select_obj = $db_obj->prepare('SELECT Clear, ' .
 'Decrypt(Encrypted, "' . $passwordhash_str . '") AS PlainText FROM table ' .
 'WHERE PlainText LIKE :searchterm');

Yes, it's possible. If targeting .Net Standard 4.6.1+ or Core, I think a fairly straightforward to get Sqlite encryption is to use Microsoft.Data.Sqlite per my answer here.


For projects using Javascript, the package written by journeyapps works seamlessly.

https://github.com/journeyapps/node-sqlcipher

It worked on Mac/Windows/Linux for me. It compiles SQLCipher on your platform. There is no need to pay for the licenses from Zetetic.


It includes everything you're looking for.

db browser for sqlite:

https://sqlitebrowser.org/

Easy table creation, easy data modification, easy deletion, and easy-to-view components.

document :

https://github.com/sqlitebrowser/sqlitebrowser/wiki

참고URL : https://stackoverflow.com/questions/5669905/sqlite-with-encryption-password-protection

반응형