我想10个字符(字母数字仅)串加密成一个16或32个字符的字母数字串。
我加密字符串是一个资产标签。所以,它本身不携带信息,但我想隐藏一个更大的小组可能的字符串内的所有有效的可能的字符串。我希望加密的字符串将是做到这一点的好办法。
是否有可能使用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')
还有一个功能 - 这个时候产生约96位*消化使用SHA-2和截断输出,使我们可以把它限制在16个alphanum字符。这给稍微碰撞的机会,但应该是最实用的目的不够好。
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
为了使串越长,你可以尝试以下;
像这样:
import bz2
import base64
base64.b64encode(bz2.compress('012345'))
这将产生:
'QlpoOTFBWSZTWeEMDLgAAAAIAH4AIAAhgAwDJy7i7kinChIcIYGXAA=='
由于bzip2的头,前13个字符将始终是相同的,所以你应该抛弃他们。
base64.b64encode(bz2.compress('012345'))[14:]
这给:
'EMDLgAAAAIAH4AIAAhgAwDJy7i7kinChIcIYGXAA=='
请注意,这是不加密的安全;这是微不足道的反转,如果你知道所使用的食谱:
foo = base64.b64encode(bz2.compress('012345'))
bz2.decompress(base64.b64decode(foo))
得到:
'012345'
是的,你也可以使用PyCrypto:
from Crypto.Hash import SHA256
aHash = SHA256.new("somethingToHash")
print(aHash.hexdigest()) #will print out the hashed password
该Crypto.Hash模块是由安装pycrypto模块(sudo pip install pycrypto
)会发生什么。
这基本上是同样的事情hashlib,但是PyCrypto库自带的加密模块。
我认为shake256满足您的需求:
您需要安装pycryptodome。
https://pycryptodome.readthedocs.io/en/latest/src/hash/shake256.html
#!/usr/bin/env python
from Crypto.Hash import SHAKE256
from binascii import hexlify
def encrypt_shake256(s, hash_size):
shake = SHAKE256.new()
shake.update(s.encode())
return hexlify(shake.read(hash_size//2))
def main():
hash = encrypt_shake256("holahola", 16)
print(hash)
print(len(hash))
if __name__ == '__main__':
main()
输出:
b'c126f8fb14fb21d8'
16