How to create a JKS or P12 keystore with Python

2.7k Views Asked by At

I'm working on a Python 3 script that among other things, at some point it needs to create a .JKS or .P12 keystore. I use to have a bash script that used keytool for this:

keytool -genkey -keyalg RSA -alias certAlias \
        -keystore keystore.jks -storepass $keyPass \
        -validity 360 -keysize 2048 \
        -noprompt -dname "CN=com.myCompany, OU=ID, O=AwesomeSoft, L=SF, S=CA, C=US" \
        -keypass $keyPass

mv ./keystore.jks src/main/resources/

Now i'm moving the same functionality from that bash script to python and I having some issues to figure it out and any pointer will ne more than welcome.. you may noticed that the example above is for jks, not p12... the newer version have to be able to, depending on a variable before called certType with create one or the other... or create a jks and later convert it to p12... i'm open to options..

Thanks in advance!!

1

There are 1 best solutions below

1
On

Found my answer:

import os

certAlias = 'cert'
certAlg = 'RSA'
certSigAlg = 'SHA1withRSA'
certExp = '365'
certKeySize = '2048'
certKeyType = 'PKCS12' # Select PKCS12 or JKS 
certKeyPass = 'password123'
fileName = 'keystore'
dname = 'CN=mySite.com'

#

if certKeyType == "PKCS12":
    fileExt = 'p12' 
elif certKeyType == "JKS":
    fileExt = 'jks' 
certFile = fileName + '.' + fileExt

keytool = 'keytool -genkey -noprompt \
            -alias ' + certAlias + ' \
            -keypass ' + certKeyPass + ' \
            -keyalg ' + certAlg + ' \
            -sigalg ' + certSigAlg + '\
            -validity ' + certExp + ' \
            -dname ' + dname + ' \
            -keysize ' + certKeySize + ' \
            -keystore ' + certFile + ' \
            -storepass '+ certKeyPass +' \
            -storetype  ' + certKeyType 

os.system(keytool)

I did this and works but I will be playing to add more logic... hope it helps anyone.