DEV Community

Mark Marus
Mark Marus

Posted on

creating a self signed ssl certificate and making your browser trust it

So i needed to make localhost with ssl certificate but couldn't find a way to create a certificate. After a few hours i found the solution. So first of all:
1) openssl genrsa -out rootCA.key 2048
2) openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
After those 2 commands you should get 2 files (rootCA.key & rootCA.pem
3) Now let's create a bash script. I'll name it create_certificate_for_domain.sh
to begin type this lines:

if [ -z "$1" ]
then
  echo "Please supply a subdomain to create a certificate for";
  echo "e.g. mysite.localhost"
  exit;
fi
if [ -f device.key ]; then
  KEY_OPT="-key"
else
  KEY_OPT="-keyout"
fi
DOMAIN=$1
COMMON_NAME=${2:-$1}
SUBJECT="/C=CA/ST=None/L=NB/O=None/CN=$COMMON_NAME"
NUM_OF_DAYS=999


cat v3.ext | sed s/%%DOMAIN%%/$COMMON_NAME/g > /tmp/__v3.ext
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days $NUM_OF_DAYS -sha256 -extfile /tmp/__v3.ext

mv device.csr $DOMAIN.csr
cp device.crt $DOMAIN.crt

rm -f device.crt;

Enter fullscreen mode Exit fullscreen mode

4) create csr file
openssl req -new -newkey rsa:2048 -sha256 -nodes $KEY_OPT device.key -subj "$SUBJECT" -out device.csr
5) now we have to create a support file with settings. I'll call it v3.ext

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = %%DOMAIN%%
DNS.2 = *.%%DOMAIN%%
Enter fullscreen mode Exit fullscreen mode

5) Now run the script
./create_certificate_for_domain.sh mysite.localhost
6) We get 2 files: mysite.localhost.crt && device.key
7) We have to link them to our localhost (nginx example)

Image description
8)open our link in browser. you should get security error
9) go into keychain and trust our mysite.localhost.crt

Image description

10) open the browser again and open localhost. That's it, you should be good to go!

Top comments (0)