我对加密很陌生,我需要将一个简单的字符串编码'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