TL;DR: How much can a function (such as the one below) modify an initially random string before that string becomes useless as a salt for password hashing? Is there a general rule?

# Function generates a random string of characters using urandom(), then converts each
# character to its hexadecimal equivalent, and then converts *those* digits back to characters.
# Each hexadecimal character-string is then concatenated into a super-string, excluding the '0x' 
# prefixes. The function returns the first 64 characters of the super-string.

def hex_salt():
    raw_salt = os.urandom(500)
    hex_salt = ""
    trimmed_salt = ""

    for i in range(len(raw_salt)):
        dec_num = ord(raw_salt[i])
        hex_substring = str(hex(dec_num))
        hex_salt += hex_substring

    while(len(trimmed_salt) < 64):
        if (hex_salt[j]=='0' and hex_salt[j+1]=='x') or (hex_salt[j]=='x'):


    return trimmed_salt

The reason I ask is that I'm using python's built in hashlib module to set up a login service for my website. Because hexadecimal characters are easier to deal with, I want to create a random salt (using os.urandom) and derive an equally random salt from it containing only hexadecimal characters. This is my first post on here, so I apologize for whatever sins I've no doubt committed.

  • 1
    There's no need to "derive" a random salt from your already-random salt. Just encode it directly as hex. That said, cryptographic hashes such as the ones offered by hashlib are unsuitable to use for passwords. Just use bcrypt. Jul 1 '15 at 22:32
  • Thanks, that's really good to know! I'm basically teaching myself web development via internet resources, so a clear concise answer is a godsend.
    – AG Boling
    Jul 2 '15 at 0:35

Simply changing the representation of the message shouldn't reduce the entropy given the underlying meaning of the data shouldn't be altered. So for example, you could encode it into Base64 or ASCII without issue.

However, to answer this question generally:

How much can a function (such as the one below) modify an initially random string before that string

It's more of a concern how you modify the data rather than how much the data has changed. If you do anything which makes the data more predictable then you'll compromise the security of the random value. For example, you could safely invert the bits of the string, but if you went through any removed any bit sequences that didn't correspond to an ASCII A-Z character then you'd be making it less secure.

In your case, I wouldn't implement my own encoding scheme - I'd just use Base64.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.