您最好使用简单的散列(类似于单向加密)。为此,只需使用 md5 函数生成摘要,然后对其进行 base64 或 base16 编码。请注意,base64 字符串可以包含 +、= 或 /。
import md5
import base64
def obfuscate(s):
return base64.b64encode( md5.new(s).digest())
def obfuscate2(s):
return base64.b16encode( md5.new(s).digest())
# returns alphanumeric string but strings can also include slash, plus or equal i.e. /+=
print obfuscate('Tag 1')
print obfuscate('Tag 2')
print obfuscate('Tag 3')
# return hex string
print obfuscate2('Tag 1')
正如已经评论的那样,md5 正在迅速失去其安全性,因此如果您希望将来拥有更可靠的东西,请使用下面的 SHA-2 示例。
import hashlib
def obfuscate(s):
m = hashlib.sha256()
m.update(s)
return m.hexdigest()
print obfuscate('Tag 1')
print obfuscate('Tag 2')
print obfuscate('Tag 3')
还有一个功能 - 这次使用 SHA-2 生成大约 96 位* 摘要并截断输出,以便我们可以将其限制为 16 个字母数字字符。这会稍微增加碰撞的可能性,但对于大多数实际用途来说应该足够了。
import hashlib
import base64
def obfuscate(s):
m = hashlib.sha256()
m.update(s)
hash = base64.b64encode(m.digest(), altchars="ZZ") # make one way base64 encode, to fit characters into alphanum space only
return hash[:16] # cut of hash at 16 chars - gives about 96 bits which should
# 96 bits means 1 in billion chance of collision if you have 1 billion tags (or much lower chance with fewer tags)
# http://en.wikipedia.org/wiki/Birthday_attack
print obfuscate('Tag 1')
print obfuscate('Tag 2')
print obfuscate('Tag 3')
*实际的摘要只有 95.2 位,因为我们使用 62 个字符的字母进行编码。
>>> math.log(62**16,2)
95.26714096618998