我對加密非常陌生,我需要將一個簡單的字符串(如'ABC123'
)編碼爲與'3d3cf25845f3aae505bafbc1c8f16d0bfdea7d70f6b141c21726da8d'
類似的東西。如何對簡單字符串進行編碼/解碼
我第一次嘗試這樣的:
>>> import base64
>>> q = 'ABC123'
>>> w = base64.encodestring(q)
>>> w
'QUJDMTIz\n'
但它是短暫的,我需要的東西更長的時間,比我想這:
>>> import hashlib
>>> a = hashlib.sha224(q)
>>> a.hexdigest()
'3d3cf25845f3aae505bafbc1c8f16d0bfdea7d70f6b141c21726da8d'
這是好事,但現在我不知道該怎麼將其轉換回來。如果有人能夠幫助我學習這個例子或者提出其他的建議,那麼我怎樣才能將一個小字符串編碼/解碼爲更長的東西,這將會很棒。
UPDATE
基於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
這不是一個散列意味着什麼。 – SLaks
安全性是_hard_。你想要捍衛什麼場景? – SLaks
我需要將帳戶ID編碼爲更長的內容,並在需要時將其解碼回來。 – Vor