Search code examples
batch-filecmdbase64newlinetrim

CMD batch - encode file to base 64 and trim characters and new line


I'm trying to make a batch file from CMD with the following commands:

  1. Convert file to base 64 - using certutil command this is how the contents of the base 64 looks like (B64.txt):

converted B64.txt

  1. Trim the base 64 - basically, I want to remove -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- this part is done, the only thing left is trim the newline characters to make a one liner of base64, because I will be passing this to a request payload.

This is what I did so far:

@ECHO OFF 
cd /filePath
certutil -encode sample.pdf B64.txt
type B64.txt | find /V "-----BEGIN CERTIFICATE-----" | find /V "-----END CERTIFICATE-----" > B64.txt

My question is:

  1. Using the command find /V* how can I define the new line characters and remove them?

  2. Is there a more efficient way to do this?

Can this also be done without assigning the base 64 as a variable? It turns out that the limit for variables is only around 9000 characters, and the base 64 I convert normally has 70,000 characters.


Solution

  • There is a really simple solution using undocumented features of CERTUTIL. You can use the
    -ENCODEHEX verb with an undocumented format at the end to directly get your desired output of base 64 all on one line without any headers.

    certutil -encodehex -f sample.pdf B64.txt 0x40000001
    

    See the DosTips More Tricks with certutil thread for more information. Especially look at this 4th post for a detailed explanation of all the format options.