Rob van der Woude's Scripting Pages

Batch How To ...

Hexadecimal Encode and Decode Files

 

Using native CERTUTIL

CERTUTIL is native in Windows 8 .. 11 (not sure about Vista and 7).

Encode:

CERTUTIL.EXE -encodehex myfile.org myfile.hex format

The format argument is optional.
The accepted values are discussed here.
Without a format specified, the output will look like any hexadecimal's editor screen:

0000	54 68 69 73 20 69 73 20  74 68 65 20 66 69 72 73   This is the firs
0010	74 20 6c 69 6e 65 2e 0d  0a 41 6e 64 20 74 68 69   t line...And thi
0020	73 20 69 73 20 74 68 65  20 73 65 63 6f 6e 64 20   s is the second 
0030	6f 6e 65 2e 0d 0a                                  one...

To remove the addresses and text, use:

CERTUTIL.EXE -encodehex myfile.org myfile.hex 4
54 68 69 73 20 69 73 20  74 68 65 20 66 69 72 73
74 20 6c 69 6e 65 2e 0d  0a 41 6e 64 20 74 68 69
73 20 69 73 20 74 68 65  20 73 65 63 6f 6e 64 20
6f 6e 65 2e 0d 0a

For a single-line hexadecimal string without spaces, use:

CERTUTIL.EXE -encodehex myfile.org myfile.hex 12
5468697320697320746865206669727374206c696e652e0d0a416e64207468697320697320746865207365636f6e64206f6e652e0d0a

 

Decode:

CERTUTIL.EXE -decodehex myfile.hex myfile.org

Addresses and text in the hexadecimal encoded file will be ignored.

 

Using native PowerShell

You can use the following PowerShell code to encode to and decode from hexadecimal.
The encoding script code inserts spaces that are required by the decoding script's Split( ) function.

Encode:

$( Get-Content 'myfile.org' -Raw ).ToCharArray( ) | ForEach-Object { ( "{0:X2} " -f [int]$_ ) } | Out-File -FilePath 'myfile.hex' -NoNewline

The decoded output will be a single line with whitespace:

54 68 69 73 20 69 73 20 74 68 65 20 66 69 72 73 74 20 6C 69 6E 65 2E 0D 0A 41 6E 64 20 74 68 69 73 20 69 73 20 74 68 65 20 73 65 63 6F 6E 64 20 6F 6E 65 2E 0D 0A 

 

Decode:

$( Get-Content 'myfile.hex' ).Trim( ).Split( ) | ForEach-Object { ( "{0}" -f [char][int]"0x$_" ) } | Out-File -FilePath 'myfile.org' -NoNewline

page last modified: 2023-07-01; loaded in 0.0016 seconds