Follow us

May the source be with you!

Blog about the light side of the *.java

  • Home
  • Java
  • JavaFX
  • Spring
  • JavaScript
  • About me
  • Contacts
    • via mail
    • twitter
    • facebook
Home Archive for April 2019
As a follow up of the http://gochev.blogspot.com/2019/04/convert-pfx-certificate-to-jks-p12-crt.html we now have a keystore and a truststore (if anyone needs) and we will use this keystore to send client side authentication using Spring's RestTemplate .

First copy your keystore.jks and truststore.jks in your classpath, no one wants absolute paths right ?:)

Again a reminder The difference between truststore and keystore if you are not aware is(quote from the JSSE ref guide): 
TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted.
KeyManager: Determines which authentication credentials to send to the remote host.

The magic happens in the creation of SSLContext. Keep in mind the Spring Boot have a nice RestTemplateBuilder but I will not gonna use it, because someone of you might have an older version or like me, might just use a plain old amazing Spring.

If you just want to use the keystore:

final String allPassword = "123456";
SSLContext sslContext = SSLContextBuilder
                .create()
                .loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"),
                                    allPassword.toCharArray(), allPassword.toCharArray())
                .build();

if you just want to use the truststore

final String allPassword = "123456";
SSLContext sslContext = SSLContextBuilder
                .create()
                .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword.toCharArray())
                .build();

I guess you know how to use both ;), if you want to IGNORE the truststore certificate checking and trust ALL certificates (might be handy for testing purposes and localhost)

final String allPassword = "123456";
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = SSLContextBuilder
                .create()
                .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword.toCharArray())
                .loadTrustMaterial(null, acceptingTrustStrategy) //accept all
                .build();


Ones you have the sslContext you simply do :

HttpClient client = HttpClients.custom()
                                .setSSLContext(sslContext)
                                .build();

HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

requestFactory.setHttpClient(client);

RestTemplate restTemplate = new RestTemplate(requestFactory);

return restTemplate;

And Voala, now each time you make a get/post or exchange with your restTemplate you will send the client side certificate.

Full example (the "tests" version) that sends client side certificate and ignores the SSL certificate



private RestTemplate getRestTemplateClientAuthentication()
                throws IOException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException,
                KeyStoreException, KeyManagementException {

    final String allPassword = "123456";
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    SSLContext sslContext = SSLContextBuilder
                    .create()
                    .loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"),
                                        allPassword.toCharArray(), allPassword.toCharArray())
//.loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword.toCharArray())
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

    HttpClient client = HttpClients.custom()
                                    .setSSLContext(sslContext)
                                    .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(client);

    RestTemplate restTemplate = new RestTemplate(requestFactory);

    return restTemplate;
}

Hope this is handy for someone :) Also this should be extremely handy if you integrate BNP Paribas Leasing : ) 
I recently had to use a PFX certificate for client authentication (maybe another post will be coming) and for that reason I had to convert it to a Java keystore (JKS). 

We will create BOTH a truststore and a keystore, because based on your needs you might need one or the other. 
The difference between truststore and keystore if you are not aware is(quote from the JSSE ref guide:

TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted.
KeyManager: Determines which authentication credentials to send to the remote host.

Ok that's enough what you will need is openssl and Java 7+ ;) !

First let's generate a key from the pfx file, this key is later used for p12 keystore.

openssl pkcs12 -in example.pfx -nocerts -out example.key  
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:

As shown here you will be asked for the password of the pfx file, later you will be asked to enter a PEM passphase lets for example use 123456 for everything here.
The second commands is almost the same but it is about nokey and a crt this time

openssl pkcs12 -in example.pfx -clcerts -nokeys -out example.crt
Enter Import Password:
MAC verified OK

Now we have a key and and a crt file
Next step is to create a truststore.

keytool -import -file example.crt -alias exampleCA -keystore truststore.jks
Enter keystore password:
Re-enter new password:
Owner: CN=.....
.......
Trust this certificate? [no]:  yes
Certificate was added to keystore

As you can see here you just import this crt file into a jks truststore and set some password. For the question do you trust this certificate you say yes, so it is added in the truststore.

We are done if you only need a truststore. 
The last step(s) is to create a keystore

openssl pkcs12 -export -in example.crt -inkey example.key -certfile example.crt -name "examplecert" -out keystore.p12
Enter pass phrase for example.key:
Enter Export Password:
Verifying - Enter Export Password:

This p12 keystore is enough in many cases, still if you need a JKS keystore you need one additional command

keytool -importkeystore -srckeystore keystore.p12 -srcstoretype pkcs12 -destkeystore keystore.jks -deststoretype JKS
Importing keystore keystore.p12 to keystore.jks...
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
Entry for alias examplecert successfully imported.
Import command completed:  1 entries successfully imported, 0 entries failed or cancelled

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.jks -deststoretype pkcs12".

That is all folks ! I hope this helps someone :) 

ls                                                                        
example.pfx  example.key            keystore.p12
example.crt  keystore.jks           truststore.jks

See you in post 2 how to use this keystore for client side authentication. Also how to use the truststore if you need to use it.

Subscribe to: Posts ( Atom )

ABOUT AUTHOR

Superhero with Java powers && Gamer && (Sci-Fi & Star Wars geek) && Bulgarian Java User Group Leader && nerds2nerds podcaster && (link: http://java.beer) java.beer guy ? this : null

Social

Twitter
Facebook

LATEST POSTS

  • Use Client Certificate Authentication with Java and RestTemplate
    As a follow up of the  http://gochev.blogspot.com/2019/04/convert-pfx-certificate-to-jks-p12-crt.html  we now have a keystore and a truststo...
  • Convert PFX certificate to JKS, P12, CRT
    I recently had to use a PFX certificate for client authentication (maybe another post will be coming) and for that reason I had to convert i...
  • Use Multiple JVM versions on Mac OS and Linux
    Linux Download multiple Java versions and put them into /opt/ If you already have some JDK from ubuntu repo or etc not a big deal, just f...
  • Hibernate Generic DAO.
    When you use Hibernate and DAO pattern it is a good idea to use a Generic Base Dao. The fallowing code snippet contains GenericDAO that is a...
  • Youtube video channel of the Bulgarian Java User Group
    Bad news everyone, as you already have noticed I do not have time to write blogs :( However I would recommend you to check and keep an ey...
  • Patching a Maven library with your custom class.
    Sometimes you use a library that has a bug. Or maybe it doesn’t has a bug but you want to change something. Of course if it is an open sourc...
  • RichFaces server-side paging with DataTable.
    Most of the component toolkits have build in support for server-side paging this days but in rest of the cases you need to customize a littl...
  • JSF, RichFaces, Spring, Hibernate – lets make development easy.
    The goal of this article is to show you how you can use Hibernate, Spring and JSF 1.2 in the most easiest way. Used technologies : ma...
  • spring-loaded rocks !
    Today I found spring loaded ( https://github.com/spring-projects/spring-loaded ) in short this is a java agent that enables class reloading...

Categories

  • .net
  • AboutMe
  • appengine
  • blogspot
  • conf
  • CV
  • gwt
  • java
  • java.javaee
  • javaee
  • javafx
  • javascript
  • other
  • photoshop
  • ria
  • spring

What I read ?

  • Baeldung
  • Java Code Geeks
  • Vlad Mihalcea
  • Javarevisited
  • Pushing Pixels
  • Vanilla #Java
  • Antonio's Blog
  • Oracle Blogs | Oracle The Aquarium Blog
  • JavaWorld
  • blog@CodeFX
  • Jonathan Giles
  • JavaFX News, Demos and Insight // FX Experience
  • Eclipse Papercuts
  • Codedependent
  • Caffeine Induced Ramblings - Jasper Potts's Blog
  • Joshua Marinacci's Blog

Search This Blog

Blog Archive

  • November 2019 (2)
  • July 2019 (1)
  • April 2019 (2)
  • February 2019 (1)
  • January 2019 (1)
  • May 2016 (1)
  • October 2015 (1)
  • September 2015 (1)
  • June 2015 (2)
  • May 2015 (2)
  • February 2015 (1)
  • October 2014 (1)
  • July 2014 (2)
  • April 2014 (1)
  • June 2013 (1)
  • July 2011 (2)
  • May 2011 (1)
  • March 2011 (1)
  • July 2010 (1)
  • June 2010 (1)
  • October 2009 (3)
  • September 2009 (6)
  • August 2009 (9)
  • June 2009 (1)
Powered by Blogger.

Blog info

My photo
jNayden
View my complete profile

About us

Labels

  • .net
  • AboutMe
  • appengine
  • blogspot
  • conf
  • CV
  • gwt
  • java
  • java.javaee
  • javaee
  • javafx
  • javascript
  • other
  • photoshop
  • ria
  • spring

Advertisement

Popular Posts

    no image Use Client Certificate Authentication with Java and RestTemplate
    no image Convert PFX certificate to JKS, P12, CRT
    no image Use Multiple JVM versions on Mac OS and Linux
    no image Hibernate Generic DAO.
    no image Youtube video channel of the Bulgarian Java User Group
    Patching a Maven library with your custom class. Patching a Maven library with your custom class.
    RichFaces server-side paging with DataTable. RichFaces server-side paging with DataTable.
    no image JSF, RichFaces, Spring, Hibernate – lets make development easy.
    no image spring-loaded rocks !

FOLLOW US @ INSTAGRAM

About Me

  • Normal Link 01
  • Normal Link 02
  • Custom Menu 01
  • Custom Menu 02
  • Disclaimer
  • Terms
  • Policy
  • Home
  • About
  • Contact
  • Home
  • Features
  • _Multi DropDown
  • __DropDown 1
  • __DropDown 2
  • __DropDown 3
  • _ShortCodes
  • _SiteMap
  • _Error Page
  • Documentation
  • _Web
  • _Video
  • Download This Template

Menu Footer Widget

  • Home
  • About
  • Contact

Social Plugin

Tags

Advertisement

Responsive Advertisement
May the source be with you!

Popular Posts

java

Convert PFX certificate to JKS, P12, CRT

Use Client Certificate Authentication with Java and RestTemplate

Use Multiple JVM versions on Mac OS and Linux

Hibernate Generic DAO.

Copyright 2014 May the source be with you!.
Blogger Templates Designed by OddThemes