是否可以将SHA 256位哈希作为整数存储在BIGINT列中?



给定一个非常大的整数,例如:

>>> import hashlib
>>> h = hashlib.sha256("foo").hexdigest()
>>> h
'2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
>>> i = int(h, 16)
>>> i
19970150736239713706088444570146546354146685096673408908105596072151101138862L

我尝试在SQLite版本3.7.13中创建一个表,如:

sqlite> .schema sha_table
CREATE TABLE "sha_table" (
        "id" integer NOT NULL PRIMARY KEY,
        "sha_hash" UNSIGNED BIG INT NOT NULL
    );
sqlite> INSERT INTO `sha_table` (`sha_hash`) VALUES (19970150736239713706088444570146546354146685096673408908105596072151101138862);
sqlite> SELECT * FROM `sha_table`;
1|1.99701507362397e+76

尝试将该数字转换回预期的整数/十六进制不工作:

>>> i = int(1.99701507362397e+76)
>>> i
19970150736239699946838208148745496378851447158029907897771645036831291998208L
>>> "{:0>64x}".format(i)
'2c26b46b68ffbe00000000000000000000000000000000000000000000000000'

编辑:从Python sqlite3客户端尝试似乎也不起作用:

>>> cursor.execute("SELECT sha_hash FROM sha_table")
>>> i = int(cursor.fetchone()[0])
>>> i
19970150736239716016218650738648251798472370569655933119801582864759645011968L
>>>> "{:0>64x}".format(i)
'2c26b46b68ffbe00000000000000000000000000000000000000000000000000'

谢谢!

你有256位的数字。这远远大于BIGINT的存储容量。

sqlite> CREATE TABLE "sha_table" (
   ...>         "id" integer NOT NULL PRIMARY KEY,
   ...>         "sha_hash" UNSIGNED BIG INT NOT NULL
   ...>     );
sqlite> INSERT INTO sha_table (sha_hash) VALUES (9223372036854775807);
sqlite> INSERT INTO sha_table (sha_hash) VALUES (9223372036854775808);
sqlite> SELECT typeof(sha_hash) from sha_table;
integer
real

当溢出时,sqlite将其存储为REAL(即float)。

所以回答你的问题,不,在64位数据类型中无损存储256位哈希是不可能的。您需要选择一种不同的数据类型来存储它——实际上,文本或BLOB是您的选择。

最新更新