我想将10个字符(仅限字母数字)字符串加密为16或32个字符的字母数字字符串。
我正在加密的字符串是一个资产标签。因此,它本身并不包含任何信息,但我希望将所有有效的可能字符串隐藏在一个更大的可能字符串组中。我希望对字符串进行加密是一种很好的方法。
使用Python PyCrypto库可以做到这一点吗?
关于使用PyCrypto,我找到了Here is an example。
发布于 2012-07-03 03:47:51
您最好使用简单的散列(类似于单向加密)。为此,只需使用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发布于 2012-07-03 04:55:11
要使字符串更长,您可以尝试执行以下操作;
使其再次可读
如下所示:
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'发布于 2015-09-03 08:15:10
可以,您也可以使用PyCrypto:
from Crypto.Hash import SHA256
aHash = SHA256.new("somethingToHash")
print(aHash.hexdigest()) #will print out the hashed passwordCrypto.Hash模块是通过安装pycrypto模块(sudo pip install pycrypto)得到的。
这基本上与hashlib是一样的,但是PyCrypto库附带了加密模块。
https://stackoverflow.com/questions/11299688
复制相似问题