【发布时间】:2013-07-06 06:34:55
【问题描述】:
我对加密非常陌生,我需要将像 'ABC123' 这样的简单字符串编码成类似于 '3d3cf25845f3aae505bafbc1c8f16d0bfdea7d70f6b141c21726da8d' 的字符串。
我第一次尝试这个:
>>> import base64
>>> q = 'ABC123'
>>> w = base64.encodestring(q)
>>> w
'QUJDMTIz\n'
但这太短了,我需要更长的时间,而不是我尝试过的:
>>> import hashlib
>>> a = hashlib.sha224(q)
>>> a.hexdigest()
'3d3cf25845f3aae505bafbc1c8f16d0bfdea7d70f6b141c21726da8d'
这很好,但现在我不知道如何将其转换回来。如果有人可以帮助我了解这个示例或提出其他建议,那么我如何将一个小字符串编码/解码为更长的字符串,那就太好了。
更新
基于plockc 的回答我这样做了,它似乎工作:
from Crypto.Cipher import AES # encryption library
BLOCK_SIZE = 32
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'
# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
# create a cipher object using the random secret
cipher = AES.new('aaaaaaaaaa123456')
# encode a string
encoded = EncodeAES(cipher, 'ABC123')
print 'Encrypted string: %s' % encoded
# decode the encoded string
decoded = DecodeAES(cipher, encoded)
print 'Decrypted string: %s' % decoded
【问题讨论】:
-
哈希不是这个意思。
-
安全性是hard。你想保护什么场景?
-
我需要将帐户 ID 编码为更长的内容,而不是在需要时将其解码。
-
您要防御哪些攻击者?你想拥有一个秘密密钥吗?你想防止突变吗?
-
是的,我想我需要一个密钥……可以让我对其进行编码和解码的东西
标签: python encryption hash sha