Skip to content

Instantly share code, notes, and snippets.

@sgpopov
Last active February 22, 2016 15:16
Show Gist options
  • Save sgpopov/ece6eda3b01b9331bb03 to your computer and use it in GitHub Desktop.
Save sgpopov/ece6eda3b01b9331bb03 to your computer and use it in GitHub Desktop.
Windows: Creating a code-signing certificate
#!/bin/bash
printf "\n"
commands=(makecert certutil pvk2pfx)
for i in "${commands[@]}"
do
command -v $i >/dev/null && continue || {
echo "ERROR: $i command not found.";
exit 1;
}
done
while [[ -z "$COMPANY_NAME" ]]
do
read -p "Company name: " COMPANY_NAME
done
while [[ -z "$OUTPUT_FILE" ]]
do
read -p "Output filename (without an extension): " OUTPUT_FILE
done
printf "\n"
makecert -r -pe -n "CN=$COMPANY_NAME" -ss CA -sr CurrentUser -a sha256 -cy authority -sky signature -sv $OUTPUT_FILE.pvk $OUTPUT_FILE.cer
if ! [ $? -eq 0 ]; then
exit 1;
fi
certutil -user -addstore Root $OUTPUT_FILE.cer
if ! [ $? -eq 0 ]; then
exit 1;
fi
makecert -pe -n "CN=$COMPANY_NAME" -a sha256 -cy end -sky signature -ic $OUTPUT_FILE.cer -iv $OUTPUT_FILE.pvk -sv $OUTPUT_FILE.pvk $OUTPUT_FILE.cer
if ! [ $? -eq 0 ]; then
exit 1;
fi
pvk2pfx -pvk $OUTPUT_FILE.pvk -spc $OUTPUT_FILE.cer -pfx $OUTPUT_FILE.pfx
@sgpopov
Copy link
Author

sgpopov commented Feb 22, 2016

Creating a self-signed Certificate Authority (CA)

makecert -r -pe -n "CN=COMPANY NAME" -ss CA -sr CurrentUser ^
             -a sha256 -cy authority -sky signature -sv OUTFILE.pvk OUTFILE.cer

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "COMPANY NAME", and should be put in the CA store for the current user. We're using the sha256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the OUTFILE.pvk file, and the certificate in the OUTFILE.cer file.

Importing the CA Certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root OUTFILE.cer

Creating a code-signing (SPC) Certificate

Pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

makecert -pe -n "CN=COMPANY NAME" -a sha256 -cy end ^
         -sky signature -ic OUTFILE.cer -iv OUTFILE.pvk ^
         -sv OUTFILE.pvk OUTFILE.cer

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk OUTFILE.pvk -spc OUTFILE.cer -pfx OUTFILE.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v ^
         /f OUTFILE.pfx ^
         /t http://timestamp.verisign.com/scripts/timstamp.dll ^
         <PATH TO EXE>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment