echo off
echo Usage create_certificate.bat 'location_root' 'unique_name' 'subj'
echo where subj has the form: "/C=%COUNTRY%/DC=%DomainComponent%/ST=%STATE%/O=%ORGANIZATION%/OU=%ORGANIZATION_UNIT%/CN=%TO%"

SET BATCH_DIR=%~dp0
SET OPENSSL_EXE_DIR="%BATCH_DIR%..\..\Tools\OpenSSL_3.0\Bin\"

if %1.==. GOTO NO_PATH_CERTIFICATE_REQUEST
if %2.==. GOTO NO_NAME_CERTIFICATE_REQUEST
if %3.==. GOTO NO_SUBJ_CERTIFICATE_REQUEST

set LOCATION=%~1
set NAME=%2
set SUBJ=%3
echo Subject: %3

set PRIVATE_KEY_LOCATION=%LOCATION%\private\private_key_%NAME%.pem
set CERTIFICATE_LOCATION=%LOCATION%\certs\cert_%NAME%.der
set TEMP_CERTIFICATE_LOCATION=%LOCATION%\certs\cert_%NAME%.pem
set REQUEST_LOCATION=%LOCATION%\request\req_%NAME%.csr

REM 	Generate private key
"%OPENSSL_EXE_DIR%openssl" genrsa -des3 -out "%PRIVATE_KEY_LOCATION%"  -passout pass:pass 1024 
REM 	Generate request key
"%OPENSSL_EXE_DIR%openssl" req -config "%BATCH_DIR%openssl.cnf" -new -days 365 -key "%PRIVATE_KEY_LOCATION%" -outform PEM -out "%REQUEST_LOCATION%" -passin pass:pass
REM 	Sign request, certificate in PEM format will be generated
"%OPENSSL_EXE_DIR%openssl" ca -config "%BATCH_DIR%openssl.cnf" -batch -in "%REQUEST_LOCATION%" -out "%TEMP_CERTIFICATE_LOCATION%"  -subj %SUBJ% -passin pass:pass
REM 	Convert PEM certificate to DER format
"%OPENSSL_EXE_DIR%openssl" x509 -inform PEM -in "%TEMP_CERTIFICATE_LOCATION%" -outform DER -out "%CERTIFICATE_LOCATION%"

GOTO END_CERTIFICATE_REQUEST

:NO_PATH_CERTIFICATE_REQUEST
echo No path has been specified
GOTO END_CERTIFICATE_REQUEST

:NO_NAME_CERTIFICATE_REQUEST
echo No name has been specified
GOTO END_CERTIFICATE_REQUEST

:NO_SUBJ_CERTIFICATE_REQUEST
echo No subject has been specified
GOTO END_CERTIFICATE_REQUEST

:END_CERTIFICATE_REQUEST


