6

I need to convert a DLL file to HEX representation to use it as a part of string to create a sql server assembly like this

CREATE ASSEMBLY [AssemblyNameHere]
FROM 0x4D5A90000300000004000000FFFF000......continue binary data
WITH PERMISSION_SET = EXTERNAL_ACCESS

I need this to be in a batch file for many reasons, but it seems that FOR statement only suitable for text files.

Esam Bustaty
  • 346
  • 1
  • 4
  • 13

2 Answers2

14

the easiest way is with CERTUTIL command:

certutil -encodehex c:\myfile.dll myfile.hex
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 1
    great tool, but it seems that it was a Windows-Server tool that got introduced to windows 8, so maybe not applicable back when the question was asked, was it? – Esam Bustaty Mar 09 '15 at 14:15
  • 5
    If you want to have raw hexadecimal contents without address column, ASCII representation and spaces between byte values, add "12" to the end of the command line, like this: certutil -encodehex c:\myfile.dll myfile.hex 12 – astraujums Apr 26 '18 at 11:35
  • 1
    Here is the description of various format types that can be used: https://msdn.microsoft.com/en-us/library/windows/desktop/aa379887(v=vs.85).aspx – astraujums Apr 26 '18 at 11:38
4

It is not a very good idea to create a hex output with pure batch.

But you could use vbscript or for simple tasks FC.exe could work.

@echo off
SETLOCAL EnableDelayedExpansion
set filesize=%~z1
set "hexVal=41"
set "x10=AAAAAAAAAA"

set /a chunks=1+filesize / 10

del dummy.txt 2>nul > nul
for /L %%n in (0,1,%chunks%) DO (
  <nul >> dummy.txt set /p ".=%x10%"
)

set /a expectedNum=0
for /F "eol=F usebackq tokens=1,2 skip=1 delims=:[] " %%A in (`fc /b "%~dpf1" dummy.txt`) DO (
    set /a num=0x%%A && (
            set /a numDec=num-1
        set "hex=%%B"

        for /L %%n in (!expectedNum!=,=1 !numDec!) DO (
            echo %hexVal%
        )
        set /a expectedNum=num+1
        echo !hex!
    )
)

First I create a file with (nearly) the same length, and then I compare them with FC in binary mode (/B), the output is scanned and if a line missings are detected, they are filled with the hexVal of the x10 string (in this case 0x41='A').

jeb
  • 78,592
  • 17
  • 171
  • 225
  • Thanks, this works perfectly but it's too slow on relatively large files (36KB), btw when you mentioned vbscript did you mean that there is a command line way to call a script? – Esam Bustaty Jan 10 '11 at 17:07
  • You can call a VBScript from a batch file like this `CSCRIPT MyScript.vbs`. – aphoria Jan 10 '11 at 18:10