HTTPS connection with Java to the self-signed certificate server

It's a niche content, but I'm really into it.

Thing you want to do

Newly created "WEB server" and "Java client application". Here, I want to test the HTTPS connection from the Java client application to the WEB server.

The wall you have to overcome

Assumed reader

Suppose you know the following: I will not explain in particular.

version information

Work procedure

1. Issuance of server certificate

1.1. Install openSSL

[Here] Download the installer from [] and install it. It seems better to use the one that matches the number of bits of the target server. Either normal / light version is acceptable. [Here]: http://slproweb.com/products/Win32OpenSSL.html

1.2. Directory / file preparation

For simplification, create a certificate with the default settings of openSSL, so create a fixed directory / file. Create the following.

1.2.1. Directory

1.2.2. File

1.3. Variable preparation

The optional items are summarized below. You can freely decide as appropriate, but there are restrictions that must be the same, so I will clarify here. (A little addictive point)

Variable name: Description * Enclosed in'' for clarity, but no entry is actually required. 'cakey.pem': Certificate authority private key file name. 'cacert.pem': Certificate authority public key file name. 'capassword': Certificate authority password. 'ST': Region name. __ Please note that you cannot sign unless the certificate authority and the server are the same! __ 'caname': The name of the certificate authority. __ Note that you cannot sign unless the certificate authority'caname'and the server'servername' are different! __ 'sarvername': The name of the web server. __ Note that you cannot sign unless the certificate authority'caname'and the server'servername' are different! __ 'CN': The domain name of the server for which you want to create a certificate. "localhost" and IP address are also acceptable. '.server_keystore': WEB server keystore name. 'serverpassword': WEB server keystore password 'server.crt': WEB server certificate 'server.x509': WEB server certificate (X509 format) 'server.p12': Personal information exchange file name

1.4. Creating a private certificate authority

Create a private / public key pair for the certificate authority. The standard is X509 (same below)

openssl req -keyout ca/'cakey.pem' -out ca/'cacert.pem' -new -x509
writing new private key to 'ca/cakey.pem'
Enter PEM pass phrase:'capassword'
Verifying - Enter PEM pass phrase:'capassword'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:'ST'
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:'caname'
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:'CN'
Email Address []:

Import the created certificate authority certificate as a Java "trusted root certificate authority". (Password is "change it")

keytool -import -file ca/'cacert.pem' -trustcacerts -alias 'caname' -keystore server/cacerts

1.5. Creating a server certificate

Create a server key pair. (The encryption key algorithm is RSA)

keytool -genkey -keyalg RSA -alias 'servername' -keystore server/'.server_keystore'
Please enter the keystore password:'serverpassword'
Please re-enter your new password:'serverpassword'
What is your first and last name?
  [Unknown]:  'CN'
What is the organizational unit name?
  [Unknown]:
What is your organization name?
  [Unknown]:  'servername'
What is the city or region name?
  [Unknown]:
What is the state or state name?
  [Unknown]:  'ST'
What is the two-letter country code for this unit?
  [Unknown]:
CN=CN, OU=Unknown, O=servername, L=Unknown, ST=ST, C=Are you sure you want Unknown?
  [No]:Yes

<servername>Please enter your key password
        (Press RETURN if it is the same as the keystore password):

Create a certificate request (CSR).

keytool -certreq -alias servername -keystore server/.server_keystore -file server/server.csr
Please enter the keystore password:'serverpassword'

Sign the server certificate from the certificate request using the (created) certificate authority.

openssl ca -keyfile ca/'cakey.pem' -cert ca/'cacert.pem' -in server/server.csr -out server/'server.crt'
Using configuration from C:/OpenSSL-Win64/bin/openssl.cfg
Enter pass phrase for ca/cakey.pem:'capassword'                         
Check that the request matches the signature                                   
Signature ok                                      
Certificate Details:
        Serial Number: 1 (0x1)
        Validity                                                                  
            Not Before: May 17 02:20:49 2017 GMT                                  
            Not After : May 17 02:20:49 2018 GMT                                  
        Subject:                                                                  
            countryName               = Unknown                                   
            stateOrProvinceName       = ST                                     
            localityName              = Unknown                                   
            organizationName          = servername                                
            organizationalUnitName    = Unknown                                   
            commonName                = CN                                
        X509v3 extensions:                                                        
            X509v3 Basic Constraints:                                             
                CA:FALSE                                                          
            Netscape Comment:                                                     
                OpenSSL Generated Certificate                                     
            X509v3 Subject Key Identifier:                                        
                EE:1E:F6:4B:55:BF:59:4D:B9:A0:20:F7:CE:E9:C8:F0:B3:65:05:02       
            X509v3 Authority Key Identifier:                                      
                keyid:BC:57:86:E6:B0:E0:BE:CA:2D:47:6F:93:13:DE:0B:85:01:7B:DA:67 
                                                                                  
Certificate is to be certified until May 17 02:20:49 2018 GMT (365 days)          
Sign the certificate? [y/n]:y                                                     
                                                                                  
                                                                                  
1 out of 1 certificate requests certified, commit? [y/n]y                         
Write out database with 1 new entries                                             
Data Base Updated                                                                 

Here, if the following error appears at the end and a 0-byte server certificate is created, it is a failure. (Addictive point)

The stateOrProvinceName field needed to be the same in the
CA certificate (ST) and the request (ST)

It is a restriction that the certificate authority and the server must be in the same area, but sometimes __ the same area __ also causes the error as described above. In this case, add "-policy policy_anything" and re-execute.

openssl ca -keyfile ca/'cakey.pem' -cert ca/'cacert.pem' -in server/server.csr -out server/'server.crt' -policy policy_anything

Put the certificate in X509 format.

openssl x509 -in server/'server.crt' -out server/'server.x509'

Import into the keystore. First, import the certificate of the certificate authority

keytool -import -file ca/'cacert.pem' -alias 'caname' -keystore server/'.server_keystore'
Please enter the keystore password:'serverpassword'
owner: CN=CN, O=caname, ST=ST, C=Unknown
Issuer: CN=CN, O=caname, ST=ST, C=Unknown
Serial number: 9310226b2ad5ebe7
Validity start date: Fri Apr 28 20:17:20 JST 2017 end date: Sun May 28 20:17:20 JST 2017
Certificate finger print:
         MD5:  48:CA:F9:A9:85:88:44:5A:56:F3:9C:3E:16:D6:14:E1
         SHA1: 0F:F1:74:E3:C8:C9:0D:7D:3B:43:E0:7D:1A:10:D5:19:5B:72:8D:69
         SHA256: D6:C4:E0:78:BA:16:AF:A8:9C:23:51:18:31:E0:38:FC:57:2F:29:9C:BB:B8:3B:F4:83:85:D2:14:98:7D:2C:64
Signature algorithm name: SHA256withRSA
version: 3

Expansion:

#1: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: BC 57 86 E6 B0 E0 BE CA   2D 47 6F 93 13 DE 0B 85  .W......-Go.....
0010: 01 7B DA 67                                        ...g
]
]

#2: ObjectId: 2.5.29.19 Criticality=true
BasicConstraints:[
  CA:true
  PathLen:2147483647
]

#3: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: BC 57 86 E6 B0 E0 BE CA   2D 47 6F 93 13 DE 0B 85  .W......-Go.....
0010: 01 7B DA 67                                        ...g
]
]

Do you trust this certificate?[No]:Yes
Certificate added to keystore

Next, import the certificate of the WEB server

keytool -import -file server/'server.x509' -alias 'servername' -keystore server/'.server_keystore'
Please enter the keystore password:'serverpassword'
Certificate added to keystore

Create a PKCS # 12 format certificate from the keystore.

keytool -importkeystore -srckeystore server/'.server_keystore' -destkeystore server/'server.p12' -deststoretype PKCS12 -srcalias 'servername'
Please enter the password of the output keystore:'serverpassword'
Please re-enter your new password:'serverpassword'
Please enter the password for the source keystore:'serverpassword'

2. Set the certificate on the application server

2.1. What to use

2.2. Modifications

application.yml


server:
  ssl:
    key-store: 'server.p12'
    key-store-password: 'serverpassword'
    keyStoreType: PKCS12
    keyAlias: tomcat

3. Make the Java client app trust the certificate

3.1. What to use

3.2. What to do

Set the following in the Java VM argument.

-Djavax.net.ssl.trustStore=(Arbitrary directory)/server/cacerts -Djavax.net.ssl.keyStore=(Arbitrary directory)/server/'server.p12' -Djavax.net.ssl.keyStorePassword='serverpassword'

You should now be able to communicate HTTPS from your Java client app to your web server.

At the end

It was a long time, but the procedure for creating a server certificate is a general one. The method of setting to the root certificate authority information trusted by Java is a little irregular, and I think it will be a limited task during development. It's a simple task that requires only a few clicks to do with a browser. .. If possible, I think it's easier to create a legitimate certificate instead of a self-signed certificate during development.

Recommended Posts

HTTPS connection with Java to the self-signed certificate server
Oreore certificate https (2020/12/19) for the first time with nginx
[Template] MySQL connection with Java
Java to play with Function
Connect to DB with Java
Connect to MySQL 8 with Java
Check https connection in Java
Input to the Java console
[Java] Change the process according to the situation with the Strategy pattern
Be sure to compare the result of Java compareTo with 0
Whether to make the server side at the time of system rebuild with Kotlin or Java
Create a simple web server with the Java standard library com.sun.net.httpserver
Java to learn with ramen [Part 1]
[java8] To understand the Stream API
[Java] Points to note with Arrays.asList ()
I want to return to the previous screen with kotlin and java!
I tried to build the environment of PlantUML Server with Docker
Dare to challenge Kaggle with Java (1)
Connecting to a database with Java (Part 1) Maybe the basic method
Follow the link with Selenium (Java)
I tried to check the operation of gRPC server with grpcurl
HTTPS connection using tls1.2 in Java 6
Connect to Rails server with iPhone
Server processing with Java (Introduction part.1)
[Java] I want to perform distinct with the key in the object
ngrok --https communication in local environment (exposing the server to the outside)
The road from JavaScript to Java
Java, arrays to start with beginners
How to interact with a server that does not crash the app
[Java] How to retrieve the parameters passed from html on the server side
How to check before sending a message to the server with Spring Integration
[Amateur remarks] I tried to automate SSL possible (self-signed certificate) with Docker-Compose
How to compile Java with VsCode & Ant
Java reference to understand in the figure
Java SE8 Silver ~ The Road to Pass ~
[Java] How to use the HashMap class
Kick ShellScript on the server from Java
About the procedure for java to work
Introduction to algorithms with java --Search (depth-first search)
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
[Java] Connection with local DB (IntelliJ + SpringBoot)
[Java] How to set the Date time to 00:00:00
[Java] How to get the current directory
[Processing × Java] How to use the class
How to install the legacy version [Java]
How to get the date in java
Output of the book "Introduction to Java"
[Processing × Java] How to use the function
I went to the Java Women's Club # 1
[Java] Color the standard output to the terminal
[Java] How to use the Calendar class
Easy to trip with Java regular expressions
Try using the Wii remote with Java
[Java] Get the date with the LocalDateTime class
Introduction to algorithms with java --Search (breadth-first search)
Try connecting to the Autonomous Database with JDK6 (Java) + JDBC OCI Driver (type 2).
How to deploy a system created with Java (Wicket-Spring boot) to an on-campus server
Initialize Ruby array with 0 like Java, that is, set the default value to 0
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java