标签:pycrypto python encryption hash
我想将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')
还有一个功能 – 这次使用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
标签:pycrypto,python,encryption,hash 来源: https://codeday.me/bug/20190723/1512489.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。