簡體   English   中英

SQLite 中的 SHA1 哈希:如何?

[英]SHA1 hashing in SQLite: how?

並行處理多個數據庫,需要使用散列密碼初始化一些記錄。 MS SQL server有一些方便的函數允許動態散列:


HashBytes('SHA1', CONVERT(nvarchar(32), N'admin'))

SQLite是否有類似的功能?

如果不是,這是最簡單的解決方法(例如從SQL server選擇並以某種方式將其插入到SQLite表中)?

首選散列算法是SHA1 ,密碼存儲在BLOB列中。

更新:我在當前項目中使用 C# 語言。

SQLite3 中沒有內置這樣的函數。

但是,如果您使用 C 接口,您可以定義一個用戶函數,例如使用sqlite3_create_function ,並用它實現 SHA-1。 (但如果您有一個可編程接口,也許您可​​以在 SQL 引擎之外對密碼進行 SHA-1 處理。)

您也可以嘗試查找/創建擴展並使用load_extension函數加載,但我沒有這方面的經驗。

編輯:

SQLite 沒有附帶 SHA1,但添加起來相對容易。 您沒有說明您使用的是什么語言,但您可以查看create_functionsqlite3_result的 C 文檔。 您還可以查看此示例,了解如何使用 Ruby 將 SHA1 添加到 SQLite。

使用System.Data.SQLite ,它們被稱為用戶定義函數。 您可以在主站點上查看此示例

您可以在 C# 中為 SHA1 創建自定義函數,如下所示:

[SQLiteFunction(Name = "Sha1", Arguments = 1, FuncType = FunctionType.Scalar)]
public class Sha1 : SQLiteFunction
{
    public override object Invoke(object[] args)
    {
        var buffer = args[0] as byte[];

        if ( buffer == null )
        {
            var s = args[0] as string;

            if ( s != null )
                buffer = Encoding.Unicode.GetBytes(s);
        }

        if ( buffer == null )
            return null;

        using ( var sha1 = SHA1.Create() )
        {
            return sha1.ComputeHash(buffer);
        }
    }
}

可以為二進制數據或字符串調用此函數。 字符串在它們的 Unicode 表示中被散列。 這應該與 SQL Server 匹配。

該函數可以這樣調用:

select sha1('abc')
select sha1(x'010203')

注意到 sqlite 確實在 2017 年添加了sha1()擴展

https://www.sqlite.org/src/file/ext/misc/sha1.c

盡管默認情況下它可能未啟用。

據我所知,SQLite 沒有內置任何散列函數。

一種方法可以將自定義函數添加到 SQLite,但如果您只是在程序中計算 SHA1 哈希並將其存儲在 SQlite 中,則可能會更容易。

為 SQLite 創建自定義函數在某種程度上取決於 API 和您使用的語言。 我只有從 Python 創建 SQLite 函數的經驗。

以下構建具有動態庫支持的最新 sqlite,並編譯sha1 擴展 它還假設基於 debian 的 linux 發行版:

sudo apt build-dep sqlite3 # fetches dependencies to compile sqlite3

mkdir sqlite-compilation
cd    sqlite-compilation

wget -O sqlite.tar.gz https://www.sqlite.org/src/tarball/sqlite.tar.gz?r=release

tar xzf sqlite.tar.gz

mkdir build
cd    build
  ../sqlite/configure
  make OPTS='-DSQLITE_ENABLE_LOAD_EXTENSION'
  ./sqlite3 -cmd 'pragma compile_options;' <<< .exit
cd -

cd sqlite/ext/misc
  # https://sqlite.org/src/file?name=ext/misc/sha1.c
  sed -i 's/int sqlite3_sha_init(/int sqlite3_extension_init(/' sha1.c # this is needed to give object file custom name, for example libSqlite3Sha1.so:
  gcc -g -O2 -shared -fPIC -I ../../../build -o libSqlite3Sha1.so ./sha1.c
  cp libSqlite3Sha1.so ../../../build/
cd -

結果,您將擁有:

build/sqlite3           # sqlite3 binary
build/libSqlite3Sha1.so # sha1 extension

測試:

cd build
  sqlite3 <<< '
.load ./libSqlite3Sha1
select sha1(1);
.exit
  '
  # compare output with:
  echo -n 1 | sha1sum
cd -

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM