简体   繁体   中英

Hex string to ASCII conversion with errors?

I am trying to write a python script to convert a hex string into ASCII and save the result into a file in .der cert format. I can do this in Notepad++ using the conversion plugin, but I would like to find a way to do this conversion in a python script from command line, either by invoking the notepad++ NppConverter plugin or using python modules.

I am part way there, but my conversion is not identical to the ASCII ouptut seen in notepad++, below is a snippet of the output in Notepad++

在此处输入图片说明

But my python conversion is displaying a slightly different output below

在此处输入图片说明

As you can see my script causes missing characters in the output, and if i'm honest I don't know why certain blocks are outlined in black. But these missing blocks are needed in the same format to the first picture.

Here's my basic code, I am working in Python 3, I am using the backslashreplace error control as this is the only way I can get the problematic hex to appear in the output file

result = bytearray.fromhex('380c2fd6172cd06d1f30').decode('ascii', 'backslashreplace')

text_file = open("C:\Output.der", "w")
text_file.write(result)
text_file.close()

Any guidance would be greatly appreciated.

MikG, I would say that python did exactly what you requested.

You told to convert the bytes to string, and replace bytes with most significant bit set with escape sequence (except for \\xFF char).

Characters \\x04 (ETB) and \\x1F (US) are perfectly legal ASCII chars (though non-printable), and they are encoded using their literal value.

Characters \\xd6 and \\xd0 are illegal in ASCII - they are 8-bit long. They are encoded using 4-letter long escape sequence, as you asked: "\\" (backslash char) and "xd6" / "xd0" strings

I'm not good with DER, but suppose that you expect to have raw 8-bit sequences. Here is how this could be accomplished:

result = bytearray.fromhex('380c2fd6172cd06d1f30')

with open("Output.der", "wb") as text_file:
    text_file.write(result)

Please note "wb" specifier to open -- it tells python to do binary IO.

I also used with statement to ensure that text_file is closed whatever happens with write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM