Search code examples
securitycertificatessl-certificatex509certificatekeytool

generate key and certificate using keytool


I want to generate a self signed trusted certificate and a csr and sign the csr with trusted certificate created. I am trying it with keytool. In the first step of creating a trusted certificate using the below command:

keytool -genkey -alias mytrustCA -keyalg RSA -keystore keystore.jks -keysize 1024

where it puts the certificate into keystore. How can I store it to a file ? and when I list the contents using:

keytool -list -v -keystore cert/test.keystore

Certificate resulted from above genkey command is created with entry type as PrivateKeyEntry, how can I create a trusted Cert Entry?


Solution

  • In your first command, you have used the -genkey option to generate the keystore named keystore.jks.

    To export the certificate in .CER format file, you will need to use the -export option of the keytool.

    An example is:

    keytool -v -export -file mytrustCA.cer -keystore keystore.jks -alias mytrustCA
    

    This will generate a file named mytrustCA.cer

    To generate a certificate request to send to a CA for obtaining a signed certificate, you will need to use the -certreq option of keytool.

    An example is:

    keytool -v -certreq -keystore keystore.jks -alias mytrustCA
    

    This will ask for the keystore password and on successful authentication, it will show the certificate request as given below (a sample).

    -----BEGIN NEW CERTIFICATE REQUEST-----
    MIIBtDCCAR0CAQAwdDELMAkGA1UEBhMCSU4xFDASBgNVBAgTC01haGFyYXNodHJhMQ8wDQYDVQQH
    EwZNdW1iYWkxEjAQBgNVBAoTCU1pbmRzdG9ybTEUMBIGA1UECxMLRW5naW5lZXJpbmcxFDASBgNV
    BAMTC1JvbWluIElyYW5pMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqOLEumwLHlzIUAPD6
    Ab1pVp84mhSNCCcUKInZbSdiDYnKSr46EjEw0PtZOVPJbM4ZG3bZsOboYr0YfViJi41o4yJICFAZ
    8wCQQxPK/4N8MPV7C5WDH28kRKGH/Pc2e7CxV+as573I34QmkINk7fEyERMDwP/WgmrcKZgL0sfy
    ewIDAQABoAAwDQYJKoZIhvcNAQEFBQADgYEAlcpjOUZFP9ixskXSA7HNlioWwjbL9f9rQskJ9rK8
    kGLJ1td+mqqm20yo/JrKCzZjOMqr/aL6Zw2dkoyU34T9HnR2Bs3SgKn6wlYsYEVvVBk71Ec6PeTi
    e+fhfNQEHsj4wuB4qixO3s1jtsLDy+DpTzYguszczwxXGFVNuk+y2VY=
    -----END NEW CERTIFICATE REQUEST-----
    

    You will need to send this Certificate REquest or paste it into the Digital Certificate signer webpage. Alternately, you can even redirect this output to a file instead of the console as follows:

    keytool -v -certreq -keystore keystore.jks -alias mytrustCA > mycertreq.txt