Formatting code for JavaKeystore
{{parent page="CoreJava"}}
===Java keystore===
==To list all keys and certificates==
%%
keytool -keystore xxx.jks -list
%%
Tomcat's keystore has a default password of "changeit"
==Extracting private key==
There is no way to do that with keytool. use the following hava program:
%%(java;DumpPrivateKey.java)
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.Key;
public class DumpPrivateKey {
static public void main(String[] args) {
try {
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream(args[0]),
args[2].toCharArray());
Key key = ks.getKey(args[1],
args[2].toCharArray());
System.out.write(key.getEncoded());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Usage: java DumpPrivateKey file alias password");
}
}
}
%%
Then use it in combination with openssl:
%%
echo "-----BEGIN PRIVATE KEY-----" > tomcat.key
java DumpPrivateKey tomcat.keystore tomcat changeit | openssl enc -a >> tomcat.key
echo "-----END PRIVATE KEY-----" >> tomcat.key
%%
There you go, you just exported the jks private key to a PEM file.
===Java keystore===
==To list all keys and certificates==
%%
keytool -keystore xxx.jks -list
%%
Tomcat's keystore has a default password of "changeit"
==Extracting private key==
There is no way to do that with keytool. use the following hava program:
%%(java;DumpPrivateKey.java)
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.Key;
public class DumpPrivateKey {
static public void main(String[] args) {
try {
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream(args[0]),
args[2].toCharArray());
Key key = ks.getKey(args[1],
args[2].toCharArray());
System.out.write(key.getEncoded());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Usage: java DumpPrivateKey file alias password");
}
}
}
%%
Then use it in combination with openssl:
%%
echo "-----BEGIN PRIVATE KEY-----" > tomcat.key
java DumpPrivateKey tomcat.keystore tomcat changeit | openssl enc -a >> tomcat.key
echo "-----END PRIVATE KEY-----" >> tomcat.key
%%
There you go, you just exported the jks private key to a PEM file.