Concatenating a Hash to a String

Ivan "Rambius" Ivanov rambiusparkisanius at gmail.com
Tue Dec 1 00:32:23 EST 2020


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?

Regards
rambius

-- 
Tangra Mega Rock: http://www.radiotangra.com


More information about the Python-list mailing list