SQLite中的SHA1哈希:如何?

时间:2010-07-05 11:15:47

标签: c# sqlite cryptography hash sha1

并行处理多个DB,需要使用散列密码初始化一些记录。在MS SQL server中,有一些方便的函数允许动态散列:


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

SQLite是否有类似的功能?

如果没有,这是最简单的解决方法(例如从SQL server中选择并以某种方式将其插入SQLite表)?

首选哈希算法为SHA1,密码存储在BLOB列中。

更新:我在当前项目中使用C#语言。

6 个答案:

答案 0 :(得分:10)

SQLite3中没有内置这样的功能。

但你可以定义一个用户功能,例如如果您正在使用C接口,则使用sqlite3_create_function,并使用它实现SHA-1。 (但是如果你有一个可编程接口,也许你可以在SQL引擎之外使用SHA-1密码。)

您还可以尝试查找/创建扩展程序并使用the load_extension function加载,但我没有相关经验。

编辑:

答案 1 :(得分:4)

SQLite不附带SHA1,但添加相对容易。您没有说出您正在使用的语言,但您可以查看create_functionsqlite3_result的C文档。您还可以查看this example如何使用Ruby将SHA1添加到SQLite。

使用System.Data.SQLite,它们被称为用户定义的函数。您可以在主站点上查看this example

答案 2 :(得分:3)

您可以在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')

答案 3 :(得分:2)

注意到sqlite在2017年确实添加了FirstComponent扩展名

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

尽管默认情况下可能未启用。

答案 4 :(得分:1)

据我所知,SQLite没有内置任何散列函数。

a way向SQLite添加自定义函数,但如果只计算程序中的SHA1哈希并将其存储在SQlite中,则可能更容易。

为SQLite创建自定义函数在某种程度上取决于API和您正在使用的语言。我只有从Python创建SQLite函数的经验。

答案 5 :(得分:0)

以下内容构建了具有动态库支持的最新sqlite,并编译了sha1 extension。它还假定基于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 -
相关问题