Reputation: 1129
I am using a AES program and the output in encrypted format is a bytearray. From one string I am given
e37c1a5132a9a121d4fbb98ba42a684
however the hex array is supposed to be
e3 7c 1a 51 32 a9 a1 21 d4 fb b9 8b 0a 42 a6 84
The 4th to last term is 0a but in the concatenated string is showing up as just a plain a. How can I detect this?
In the attached link below I am trying to go from the first generated link to a byte array however when i am missing the 0 in the 0a, the string crashes.
http://laurentcharignon.com/blog/?p=37
Upvotes: 0
Views: 228
Reputation: 123521
The problem is that in the loop, thehex()
function result doesn't include leading zeros after the'0x'
prefix for values less that 16, sohex(10)
is'0xa'
andhex(10)[2:]
is'a'
(the call tostr()
is unnecessary). So instead of:
result = ""
for char in ciph:
result += str((hex(ord(char))))[2:]
You could avoid usinghex()
with something like this:
result = ""
for char in ciph:
result += '%02x' % ord(char)
A slightly more concise way to do the same thing would be with a generator expression:
result = ''.join('%02x' % ord(char) for char in ciph)
Spaces could be added between each 2-byte hex value with the following slightly different expression to make the result more readable:
' '.join('%02x' % ord(char) for char in ciph)
Upvotes: 2
Reputation: 6788
This kind of missing information is not recoverable. You have to fix the place that generates this broken string. Another valid source string for producing your string above would be:
e3 7c 1a 51 32 a9 a1 21 d4 fb b9 8b a4 02 a6 84
Here the 0 is inserted one place later. On a technical level it is not possible to infer which of these source strings was used to produce the above hex representation with zeros dropped.
Upvotes: 2