Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you print cipher text as a hex string?

I use the PyCrypto module to generate a cipher text for a message.

>>> a=AES.new("1234567890123456")
>>> m='aaaabbbbccccdddd'
>>> a.encrypt(m)
'H\xe7\n@\xe0\x13\xe0M\xc32\xce\x16@\xb2B\xd0'

I would like to have this output like the one by hashlib

>>> from hashlib import sha1
>>> sha1(m).hexdigest()
'68b69b51da162fcf8eee65641ee867f02cfc9c59'

That is, I would need a clean string instead of the string with the hex markers like \x and stuff.

Is there any way in PyCrypto to achieve this?

If yes,How can encryption and decryption be performed?

If no, how can I convert the string to the string I need?

like image 264
rjv Avatar asked Feb 14 '23 16:02

rjv


2 Answers

Use binascii.hexlify (or binascii.b2a_hex):

>>> from Crypto.Cipher import AES
>>> a = AES.new("1234567890123456")
>>> m = 'aaaabbbbccccdddd'
>>> a.encrypt(m)
'H\xe7\n@\xe0\x13\xe0M\xc32\xce\x16@\xb2B\xd0'

>>> import binascii
>>> binascii.hexlify(a.encrypt(m))
'48e70a40e013e04dc332ce1640b242d0'
like image 114
falsetru Avatar answered Feb 17 '23 07:02

falsetru


If the encrypt function returns a Python string, then you can do:

a.encrypt(m).encode('hex')
like image 21
dmchk Avatar answered Feb 17 '23 08:02

dmchk