How to create an empty java trust store? - java

I want to make a https client in java which initially does not have any CA certs to trust. Since I don't want the JVM to use the default cacerts file I should make an empty trust store and point it to the JVM.
How can I make an empty trust store?

Using keytool, create a random key pair:
keytool -genkeypair -alias boguscert -storepass storePassword -keypass secretPassword -keystore emptyStore.keystore -dname "CN=Developer, OU=Department, O=Company, L=City, ST=State, C=CA"
then delete it
keytool -delete -alias boguscert -storepass storePassword -keystore emptyStore.keystore
review its contents:
$ keytool -list -keystore emptyStore.keystore -storepass storePassword
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 0 entries

if someone eventually reaches here again:
public static void main (String[] args) {
String storePassword = "storePassword";
String storeName = "emptyStore.jks";
String storeType = "jks";
try (FileOutputStream fileOutputStream = new FileOutputStream(storeName)) {
KeyStore keystore = KeyStore.getInstance(storeType);
keystore.load(null, storePassword.toCharArray());
keystore.store(fileOutputStream, storePassword.toCharArray());
} catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) {
e.printStackTrace();
}
then check the content with keytool:
$ keytool -list -keystore emptyStore.jks -storepass storePassword
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 0 entries

One possible solution I found is to import some random certificate into a newly created trust store with keytool import and then delete the imported certificate from it. This leaves you with an empty key/trust store.
Unfortunately the JVM is not happy with an empty trust store and throws an exception upon that. So at least one certificate should be present there which could be any invalid or expired one in order to achieve the goal.

You may pass a null argument to KeyStore::load to create an empty keystore. See
https://docs.oracle.com/javase/8/docs/api/java/security/KeyStore.html#load-java.io.InputStream-char:A-

Related

Import Certificate to Keystore

I have generated the keystore using this command :
keytool -genkeypair -alias test -keyalg RSA -keystore keystore.jks
Under this section i have provided the following response:
What is your first and last name?
[Unknown]: myservice.example.com
Now i have generated the certificate with Common Name:myservice.example.com,
How should i import this certificate to my keystore so my client can connect to my service to a specific port and browser shouldn't display the invalid certificate error ?

Failed to read key my-key-alias from store "myproject/android/keystores/debug.keystore.properties": Invalid keystore format

I already create a keystore file using this script
keytool -genkey -v -keystore my-upload-key.keystore -alias
my-key-alias -keyalg RSA -keysize 2048 -validity 10000
I try to generate on myproject/android
in my android/gradle.properties
android.useDeprecatedNdk=true
android.enableJetifier=true
android.useAndroidX=true
MYAPP_UPLOAD_STORE_FILE=my-upload-key.keystore
MYAPP_UPLOAD_KEY_ALIAS=my-key-alias
MYAPP_UPLOAD_STORE_PASSWORD=****** (my password)
MYAPP_UPLOAD_KEY_PASSWORD=****** (my password)
I have a folder named keystores store all the key
my BUCK file
keystore(
name = "debug",
properties = "debug.keystore.properties",
store = "debug.keystore",
visibility = [
"PUBLIC",
],
)
my debug.keystore.properties file
could anyone help me with this.

How do I use client certificates in a client java application?

This is a topic that has taken me quite some time to figure out. There are bits and pieces of information scattered and one has to put everything together. I was hoping that with this post I could help others quickly assemble a working solution.
I have a client-cert.pem, client-key.pem and a root.pem files and I need to used them in my Java client to access a remote REST API.
How do I package them into a truststore and use them to make API calls?
In order to load your certificates into your application your will need to package them into a truststore.
Creating a truststore
given the 3 files:
client-cert.pem
client-key.pem
root.pem
Run the following commands in your terminal. Replace PASSWORD with your desired password.
Package your client key and certificate into a keystore. This will create a PKCS12 keystore file.
openssl pkcs12 -export \
-inkey client-key.pem -in client-cert.pem \
-out client.pfx -passout pass:PASSWORD \
-name qlikClient
Add the keystore to your truststore. It will create a truststore if the destination doesn't exit. This will create a PKCS12 truststore file. By default it creates a JKS file which is a proprietary format. By specifying -deststoretype PKCS12 you will create a file which is in an industry standard format.
keytool -importkeystore \
-destkeystore truststore.pfx -deststoretype PKCS12 -deststorepass PASSWORD \
-srckeystore client.pfx -srcstorepass PASSWORD -srcstoretype PKCS12 \
-alias qlikClient
Add your root CA to the truststore
keytool -importcert \
-keystore truststore.pfx -storepass PASSWORD \
-file root.pem -noprompt \
-alias qlikServerCACert
Note that in the above commands we use the same PASSWORD for both the keystore and the truststore. You could alternatively use different passwords. Also note that you have to specify an alias for each item you add to the truststore.
If you want your truststore to trust all cacerts available in your system add -trustcacerts option to step 2 or 3.
You can use the following command to list the contents of your truststore
keytool -list -keystore truststore.pfx -storepass PASSWORD
Using the truststore in you application
Once you have your truststore you need to load it into your application. Assuming you have a constant KEYSTORE_PATH holding the path to your truststore and keyStorePass holding the password, read the truststore file into a KeyStore
private KeyStore readStore() {
try (InputStream keyStoreStream = new FileInputStream(KEYSTORE_PATH)) {
KeyStore keyStore = KeyStore.getInstance("PKCS12"); // or "JKS"
keyStore.load(keyStoreStream, keyStorePass.toCharArray());
return keyStore;
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
Create a custom SSLContext and a custom HttpClient,
final KeyStore truststore = readStore();
final SSLContext sslContext;
try {
sslContext = SSLContexts.custom()
.loadTrustMaterial(truststore, new TrustAllStrategy())
.loadKeyMaterial(truststore, keyStorePass.toCharArray(), (aliases, socket) -> "qlikClient")
.build();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | UnrecoverableKeyException e) {
throw new RuntimeException("Failed to read keystore", e);
}
final CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
You can now use this HttpClient to make requests to your API.
HttpResponse response = httpClient.execute(new HttpGet("https://sense-gcp-central1eu.net:4242/qrs/app/full"));
Or, if you are using the OpenUnirest/unirest-java library, you can configure Unirest to use your custom HttpClient
Unirest.config().httpClient(httpClient);
HttpResponse<JsonNode> response = Unirest.get("https://sense-gcp-central1eu.net:4242/qrs/app/full").asJson();
References
https://alvinalexander.com/java/java-keytool-keystore-certificate-tutorials
How do I use an SSL client certificate with Apache HttpClient?
I know it is an old question, but I figured out something wrong in your question.
The truststore is used by your client to list the remote server to which it can trust.
If the certificate/key you have and would like to use, is for your own java client, you should include them in your keystore, not truststore.
This is the store your client will use in case the remote server asks your client to authenticate itself.
On top of the already given answers, if you are using spring boot and resttemplate as http client implementation, you can use the keystore you created by doing so in your application properties:
server:
ssl:
enabled: true
key-alias: <<app-client-alias>>
key-store: <<path_to_your_keystore>>
key-store-password: <<PASSWORD>>

sun.security.validator.ValidatorException: PKIX path building failed

I have Created CSR request using this command :
openssl req -out certificatecsr.csr -new -newkey rsa:2048 -keyout certificatekey.key
After that CA has shared certificate(.cer) file with me.
Now after that i have converted .cer file to .p12 using key.
Creating a .p12 certificate using cer sent by CA and private key
C:\Java\jdk1.6.0_38\jre\bin>openssl pkcs12 -export -in C:\Users\asharma1\cert.cer -inkey certificatekey.key -out
certi.p12
Creating JKS keystore :
keytool -genkey -alias quid -keystore quid.jks
importing .p12 certificate into jks keystore
C:\Java\jdk1.6.0_38\jre\bin>keytool -v -importkeystore -srckeystore C:\OpenSSL-Win64\bin\certi.p12 -srcstoretype PKCS12
-destkeystore quid.jks -deststoretype JKS
but when i am referring this JKS from my java code i am getting this error :
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I have also added cer file to cacerts.but still getting the same error.
As far as JAVA code is concerned i am refering this link to refer my own created keystore :
http://jcalcote.wordpress.com/2010/06/22/managing-a-dynamic-java-trust-store/
public SSLContext getSSLContext(String tspath)
throws Exception {
TrustManager[] trustManagers = new TrustManager[] {
new ReloadableX509TrustManager(tspath)
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, null);
return sslContext;
}
SSLContext sslContext=getSSLContext("C:\\Java\\jdk1.6.0_38\\jre\\bin\\quid.jks");
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
URL pickUrl = new URL(pickupLocation);
URLConnection urlConn = pickUrl.openConnection();
HttpsURLConnection httpsURLConn = (HttpsURLConnection)urlConn;
httpsURLConn.setSSLSocketFactory(socketFactory);
String encoding = urlConn.getContentEncoding();
InputStream is = urlConn.getInputStream();
InputStreamReader streamReader = new InputStreamReader(is, encoding != null
? encoding : "UTF-8");
Please note i am not using any server. I am trying ti run above written code thorugh main method only.
Please let me know what need to be done.
Why do i need to convert my .cer file to .p12 file ?
I would suggest you import CA certificate (or whole chain of CA and intermediate CAs) to keystore.
I think that p12 was imported fine. What I am suggesting is import of the chain to keystore. At least that is what the error message is saying.
I presume that:
the root CA in the chain is not trusted so chain building fails or
there is no AIA section in certificates in the chain so no certificates up to trusted root CA can be fetched so chain building fails or
the certificates are not being fetched based on AIA because it is not implemented in java (I am not a java programmer) so chain building fails
You could use portecle to import missing trusted CA certificates (not end entity cartificate that you have in .p12 or in separate .cer file that you received from issuing CA). It is more user friendly than keytool. Just follow this guide.
I would suggest you use the *.der format instead of the .p12 format.
Here's an overall summary of how to import certificates to fix the following error:
Error while trying to execute request.
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target
How to import certificates
Go to URL in your browser, click on HTTPS certificate chain (little lock symbol next to URL address) to export the certificate
Click "more info" > "security" > "show certificate" > "details" > "export..".
Save as .der
Repeat for any certificates you need to import
Locate $JAVA_HOME/jre/lib/security/cacerts
Import all *.der files into the cacerts file using the following:
sudo keytool -import -alias mysitestaging -keystore $JAVA_HOME/jre/lib/security/cacerts -file staging.der
sudo keytool -import -alias mysiteprod -keystore $JAVA_HOME/jre/lib/security/cacerts -file prod.der
sudo keytool -import -alias mysitedev -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev.der
The default keystore password is 'changeit'
You can view the change that you made with this command that shows the Certificate fingerprint.
keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts
If this doesn't solve the problem, try adding these java options as arguments:
-Djavax.net.ssl.trustStore="$JAVA_HOME/jre/lib/security/cacerts"
-Djavax.net.ssl.trustStorePassword="changeit"

Lost Code Signing Certificate Alias

Our company purchased a code signing certificate from Thawte a few weeks ago. When we finally received the certificate from the purchasing team they didn't know the alias for the certificate!
I don't seem to be able to import the cert without the alias and they have no clue at all what it is. Is there a way of retrieving the alias? Has anybody else run into this problem? Is there any way of importing without the alias?
The alias is specified during the creation of the private key of the RSA certificate. It is not decided by the certificate signing authority, rather by the person creating the private and public keys.
I can't speak on whether your purchasing department ought to know this, but you'll need to check with the person/department who generated the CSR to determine the toolkit used to generate the CSR, and the key store format.
Now, assuming that the Java keytool utility was utilized to create the CSR, and that the private key is managed in a JKS keystore, you can utilize the keytool command to determine the contents (and hence the alias) of the keystore. This can be done using the keytool -list as indicated in the other answer. A sample run is demonstrated below, with the alias appearing in the output:
keytool -list -v -keystore foo.jks
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 1 entry
Alias name: foo
Creation date: Sep 1, 2010
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=foo, OU=foo, O=foo, L=foo, ST=foo, C=foo
Issuer: CN=foo, OU=foo, O=foo, L=foo, ST=foo, C=foo
Note that you do not need to know the keystore password to read the contents of the keystore, in which case a warning will be displayed.
In case you are using another toolkit and/or keystore format, you'll need to adopt a similar approach to determine the contents of the keystore, for the alias is not bound to appear in the CSR.
Try with:
keytool -list -keystore certificate.jks
(Note that if your keystore isn't JKS, for example, PKCS12, you can add an optional -storetype option to change the keystore type:)
keytool -list -keystore certificate.p12 -storetype PKCS12
You'll have something like:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 1 entry
mykey, Feb 1, 2010, trustedCertEntry,
Certificate fingerprint (MD5): 0F:73:59:5C:35:8C:F2:F0:27:7E:F7:B7:AF:0A:95:B4
Your certificate alias is shown on the first line of the certificate description, here 'mykey'.

Categories