+3 votes
in Programming Languages by (73.8k points)
I am working on 1024-bits RSA encryption/decryption algorithm where I need to convert hex to integer, integer to hex, hex to bytes, bytes to hex etc. Can someone give me the functions to do all these conversions?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use Crypto.Util.number and binascii packages . See the following examples. Hope it helps.

>>> bb='11011100001000011100000110110000111101010101000100010000011000101111000100001001110111101100001100010010011110011011011111001010'
>>> from Crypto.Util.number import *
>>> import binascii

Binary to Int
>>> cc=int(bb,2)
>>> cc
292605433394145076414125928229696550858L

Binary to hex
>>> dd=hex(int(bb,2))
>>> dd
'0xdc21c1b0f5511062f109dec31279b7caL'

Int to bytes
>>> long_to_bytes(cc)
'\xdc!\xc1\xb0\xf5Q\x10b\xf1\t\xde\xc3\x12y\xb7\xca'

Hex to bytes
>>> ee=binascii.unhexlify(dd[2:len(dd)-1])
>>> ee
'\xdc!\xc1\xb0\xf5Q\x10b\xf1\t\xde\xc3\x12y\xb7\xca'

Bytes to hex
>>> ff=binascii.hexlify(ee)
>>> ff
'dc21c1b0f5511062f109dec31279b7ca'

Hex to Int
>>> gg=int(ff,16)
>>> gg
292605433394145076414125928229696550858L

Int to Hex
>>> hex(gg)
'0xdc21c1b0f5511062f109dec31279b7caL'


...