Concatenating a Hash to a String
MRAB
python at mrabarnett.plus.com
Tue Dec 1 13:30:21 EST 2020
On 2020-12-01 05:32, Ivan "Rambius" Ivanov wrote:
> Hello,
>
> I want to store the hashes of strings in a database and I have
> problems generating the sql statements. I generate the hashes using
> hashlib and then convert it to base64 and I put the base64
> representation in the sql. Here is the code:
>
> #!/usr/bin/env python3.8
>
> import base64
> import hashlib
>
> def gen_sql(s):
> sha = hashlib.sha256()
> # need to encode s as binary, otherwise the next line throws
> # TypeError: Unicode-objects must be encoded before hashing
> sha.update(b"{s}")
> ehash = base64.b64encode(sha.digest())
> sql = "insert into HASHES value ('" + ehash + "')"
>
> s = "test"
> gen_sql(s)
>
> This code throws
>
> $ ./hashinstr.py
> Traceback (most recent call last):
> File "./hashinstr.py", line 16, in <module>
> gen_sql(s)
> File "./hashinstr.py", line 13, in gen_sql
> sql = "insert into HASHES value ('" + ehash + "')"
> TypeError: can only concatenate str (not "bytes") to str
>
> Any help on how to concatenate ehash to the sql?
>
The bytes are all in the ASCII range, so you can convert it into a
string using .decode('ascii').
And, of course, use parametrised queries, as ChrisA said.
More information about the Python-list
mailing list