python - 在 Python 中加密字符串。限制字符只能使用字母数字

标签 python encryption hash pycrypto

我想将 10 个字符(仅限字母数字)的字符串加密为 16 或 32 个字符的字母数字字符串。

我正在加密的字符串是一个 Assets 标签。所以它本身不携带任何信息,但我想在更大的一组可能的字符串中隐藏所有有效的可能字符串。我希望加密字符串是实现此目的的好方法。

是否可以使用 Python PyCrypto 库来做到这一点?

Here is an example我发现了有关使用 PyCrypto 的信息。

最佳答案

您最好使用简单的散列(就像单向加密)。为此,只需使用 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

关于python - 在 Python 中加密字符串。限制字符只能使用字母数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11299688/

相关文章:

python - Nosetests 缺少命令行选项

iOS加密使用DER格式的RSA公钥文件

apache - 在 Apache 上设置 ECDSA 并获取 SSL_ERROR_NO_CYPHER_OVERLAP

ruby - 使用 Ruby 将哈希数组转换为 CSV

python - 在 IPython 启动时自动加载模块

python - _csv.错误: field larger than field limit (131072)

python - 让python写入文件中的新行

linux - 完整性检查 SSH 公钥?

javascript - 如何将 $.extend() 与变量一起使用

c - 散列函数的问题 - C