When using os.urandom(64) it generates a string with 64 random characters, this works as intended but oddly when turning it, alongside other data into a list (I need to do this to writerow into a csv file) it turns the slashes into double slashes.
Normal Salt: b'\xfe\x82;o\xa6\x8e\xfeF]\x140\x02+\xe9\x82\xa0j\x0e\xe19n\x02\xa0_t\xb6\xa8\xe1u\xc6\x94\x9a\xb94P\t\x83\xe0\x0e&B\xda\xe5)62\xa3l\x807\xb6\xd8\x0bU\xd0\xf1\xe0\xf7R:\xbc\xfe\x86\x96'
Salt within the list: "b'\xfe\x82;o\xa6\x8e\xfeF]\x140\x02+\xe9\x82\xa0j\x0e\xe19n\x02\xa0_t\xb6\xa8\xe1u\xc6\x94\x9a\xb94P\t\x83\xe0\x0e&B\xda\xe5)62\xa3l\x807\xb6\xd8\x0bU\xd0\xf1\xe0\xf7R:\xbc\xfe\x86\x96'"
Code:
def SaltGenerator(): # Used to generate Salts to be stored, will not be run in final code as salts will be stored
salt = os.urandom(64) # Generates a cryptographically secure random string
return salt
def CSVAppend(Directory,Value):
with open (os.path.join(sys.path[0],Directory),"a", newline = "") as Write:
writer = csv.writer(Write)
writer.writerow(Value)
import os
import csv
import sys
Salt = str(SaltGenerator())
print(Salt)
UsernameSaltHashedPasswordAppend=[Salt]
print(UsernameSaltHashedPasswordAppend)
CSVAppend("UsernameSaltHashedPassword",UsernameSaltHashedPasswordAppend)
csv.writer
takes Unicode strings. os.urandom()
returns a byte string. You've converted it to a Unicode string by calling str()
, but you get a byte string representation (b"..."
) which has escape codes for unprintable bytes and double backslash escapes for backslashes. Instead, use .hex()
to convert to a readable hexadecimal Unicode string.
You can use bytes.fromhex()
to convert back once you read the string from the CSV:
import csv
import os
salt = os.urandom(64)
with open('test.csv', 'w', newline='') as f:
w = csv.writer(f)
w.writerow([salt.hex()])
with open('test.csv', 'r', newline='') as f:
r = csv.reader(f)
for line in r:
salt2 = bytes.fromhex(line[0])
print(salt == salt2) # True
test.csv (example):
151c5611a5107654c9326ef7a99f5fb6aebabc579bb8f1785aa59f485008987e370eb4c8b4d856995164974539147a24e989711634865b8fc8d39bc238adfc8e