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

时间:2014-03-25 20:12:04

标签: python sql

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

>>> 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'

谢谢!

1 个答案:

答案 0 :(得分:1)

您有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是你的选择,真的。