Hashing (hiding) strings in Python

前端 未结 4 1735
南方客
南方客 2020-12-15 08:14

What I need is to hash a string. It doesn\'t have to be secure because it\'s just going to be a hidden phrase in the text file (it just doesn\'t have to be recognizable for

4条回答
  •  没有蜡笔的小新
    2020-12-15 08:34

    Note that Python's string hash is not "defined" - it can, and does, vary across releases and implementations. So storing a Python string hash will create difficulties. CPython's string hash makes no attempt to be "obscure", either.

    A standard approach is to use a hash function designed for this kind of thing. Like this:

    >>> import hashlib
    >>> encoded = hashlib.sha1("abcdef") # "abcdef" is the password
    >>> encoded.hexdigest()
    '1f8ac10f23c5b5bc1167bda84b833e5c057a77d2'
    

    That long string of hexadecimal digits is "the hash". SHA-1 is a "strong" hash function. You can get famous if you find two strings that hash to the same value ;-) And given the same input, it will return the same "hexdigest" on all platforms across all releases and implementations of Python.

提交回复
热议问题