Dropwizard Client Certificate Authentication via HttpClient Key/Trust store - java

I am running a dropwizard server, and a client leveraging Apache HttpClient 4.5.1.
Given a single .pfx file that contains both the public and private keys, how would I structure my key/trust stores on both the server and client to accept/trust and pass the certificate for authentication purposes?
What I'm running into is the client trusts the provided server certificate, but
after the server hello that includes the certificate request per tls spec, my client is unable to find a suitable certificate to send back.
My first thought was to run the server with the keystore and truststore as the same pfx file, but java throws a null cert chain error when loading the pfx file as a trust store in the server. So I had to go through the process of creating a trust store manually.
Here are the general steps I thought would allow this entire process to succeed:
Run the server with the .pfx file, with a PKCS12 keystore type.
Extract the cert from the pfx file, and create a java trust store using the cert.
Run the server with the above clientCerts.jks file as the trust store
Run the client with a keystore set to the clientCerts.jks file
Run the client with a truststore set to the .pfx PKCS12 keystore.
These steps didn't work, and I've tried other less obvious permutations and none of them worked. Is there something blatantly wrong with the way I'm approaching this? Does anyone have any advice on actually getting it to work?
Lots of details below (including ssl debug logs)
PFX cert info:
(its a valid corporate signed cert, but I don't have the root CA as trusted anywhere, which is why I just create a trust store so I can trust the client cert).
$ openssl pkcs12 -info -in cert.pfx
Enter Import Password:
MAC Iteration 1
MAC verified OK
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2000
Bag Attributes
Microsoft Local Key set: <No Values>
localKeyID: 01 00 00 00
friendlyName: xxx
Microsoft CSP Name: Microsoft RSA SChannel Cryptographic Provider
Key Attributes
X509v3 Key Usage: 10
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----BEGIN ENCRYPTED PRIVATE KEY-----
xxx
-----END ENCRYPTED PRIVATE KEY-----
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2000
Certificate bag
Bag Attributes
localKeyID: 01 00 00 00
friendlyName: my.domain.com
subject=/C=US/O=My Company/OU=Web Servers/CN=my.domain.com
issuer=/C=US/O=My Company
-----BEGIN CERTIFICATE-----
xxx
-----END CERTIFICATE-----
Java Trust store Creation:
//create pem file
openssl pkcs12 -in cert.pfx -out tempCert.crt -nokeys -clcerts
//convert to x509
openssl x509 -inform pem -in tempCert.crt -outform der -out tempx509Cert.cer
//create a java trust store
keytool -import -file tempx509Cert.cer -alias firstCA -keystore newJavaTrustStore.jks
Dropwizard Config:
applicationConnectors:
- type: https
port: 443
bindHost: localhost
keyStorePath: ./cert.pfx
keyStorePassword: pw
keyStoreType: PKCS12
trustStorePath: ./clientCerts.jks
trustStorePassword: pw
trustStoreType: JKS
supportedProtocols: [TLSv1, TLSv1.1, TLSv1.2]
excludedProtocols: [SSLv2Hello, SSLv3]
validateCerts: false
needClientAuth: true
wantClientAuth: true
HttpClient Config Values:
keyStorePath: ./clientCerts.jks
keyStorePassword: pw
keyStoreType: JKS
trustStorePath: ./cert.pfx
trustStorePassword: pw
trustStoreType: PKCS12
HttpClient Config:
public static CloseableHttpClient getSecurePooledHttpClient(
final String host,
final int port,
final boolean ssl,
final String keystorePath,
final String keystorePassword,
final String keystoreType,
final String trustStorePath,
final String trustStorePassword,
final String trustStoreType
) throws Exception {
//Setup the keystore that will hold the client certificate
KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(new FileInputStream(new File(keystorePath)),
keystorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, keystorePassword.toCharArray());
//Setup the Trust Store so we know what certificates
//we can trust that are hosting the service
KeyStore ts = KeyStore.getInstance((trustStoreType));
ts.load(new FileInputStream(new File(trustStorePath)),
trustStorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ts);
//setup our SSL context to be TLSv1.2, then setup the key and trust manager.
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
//Register the socket factory so that it uses the ssl Context and key
// manager we created above
Registry<ConnectionSocketFactory> socketFactoryRegistry =
RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE))
.build();
//Define an overridden routeplanner that setups up our default host
// so all our later calls can simply be
//sub-routes.
HttpRoutePlanner routePlanner =
new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE)
{
#Override
public HttpRoute determineRoute(
final HttpHost target,
final HttpRequest request,
final HttpContext context) throws HttpException {
return super.determineRoute(
target != null ? target : new HttpHost(host, port, ssl ? "https" : "http"),
request, context);
}
};
return BuildClientWithRoutePlanner(socketFactoryRegistry, routePlanner);
Client SSL debug:
...
*** ServerHello, TLSv1.2
RandomCookie: Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
Compression Method: 0
Extension renegotiation_info, renegotiated_connection: <empty>
***
%% Initialized: [Session-7, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256]
** TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
*** Certificate chain
chain [0] = [
[
Version: V3
Subject: CN=my.domain.com, OU=Web Servers, O=My Company, C=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
.........
***
Found trusted certificate:
[
[
Version: V3
Subject: CN=my.domain.com, OU=Web Servers, O=My Company, C=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 2048 bits
......
*** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Supported Signature Algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA
Cert Authorities:
<CN=my.domain.com, OU=Web Servers, O=My Company, C=US>
*** ServerHelloDone
Warning: no suitable certificate found - continuing without client authentication
*** Certificate chain
<Empty>
***

Related

Generate self-signed certificate and create keystore and generate JWT token in Java

I am trying to generate a jwt token from a keystore.
For this I downloaded "openssl-for-windows" https://code.google.com/archive/p/openssl-for-windows/downloads
Run the following commands in the command prompt as an administrator.
CLI comnd
Creating a sample CA certificate
openssl.exe req -config openssl.cnf -new -x509 -keyout private.pem -out certificate.pem -days 365
Create a kestore named keystore
keytool –keystore keystore –genkey –alias client -keyalg rsa
Generate certificate signing request
keytool –keystore keystore –certreq –alias client –keyalg rsa –file client.csr
Generate signed certificate for associated CSR
openssl.exe x509 -req -CA certificate.pem -CAkey private.pem -in client.csr -out client.cer -days 365 -CAcreateserial
Import CA certificate into keystore
keytool -import -keystore keystore -file certificate.pem -alias theCARoot
Import signed certificate for associated alias in the keystore
keytool –import –keystore keystore –file client.cer –alias client
Next, I created a java code to generate a token.
Main.java
public class StreamKey {
public static void main(String[] args) {
StreamKey key = new StreamKey();
key.getSer();
}
private void getSer() {
try {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("clientkeystore");
char[] password = "111111".toCharArray();
String alias = "client";
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(inputStream, password);
Key key = keyStore.getKey(alias, password);
LocalDateTime currentTime = LocalDateTime.now();
Date dat = Date.from(currentTime.plusMinutes(5).atZone(ZoneId.systemDefault()).toInstant());
Map<String, Object> claims = new HashMap<>();
claims.put("sub", alias);
claims.put("exp", dat.getTime());
String token = Jwts.builder()
.setHeaderParam("alg", "RS256")
.setHeaderParam("typ", "jwt")
.setClaims(claims)
.signWith(key, SignatureAlgorithm.RS256).compact();
System.out.println(token);
} catch (IOException | KeyStoreException | CertificateException | NoSuchAlgorithmException |
UnrecoverableKeyException e) {
throw new RuntimeException(e);
}
}
}
After creating the token, I went to the site https://jwt.io/ and pasted this token into the "Encoded PASTE A TOKEN HERE" field, then I opened the client.csr file in a text editor and copied the contents and pasted it into the "Public Key" field ".
After these steps, "Invalid Signature" is still highlighted in red
But if I take the content from the private.pem file and paste it into the "Private Key" field, then "Invalid Signature" is highlighted in blue.
The question is why when I use the public key, "Invalid Signature" is highlighted in red?
I took all the material from YouTube.
Man creates keys https://www.youtube.com/watch?v=nxowUHao9TI
The same person creates a jwt token using java https://www.youtube.com/watch?v=MWlDQaR-LLM
https://github.com/MyTestPerson/rsa-jwt
LOG
D:\test\openssl-0.9.8k_X64>.\bin\openssl.exe req -config openssl.cnf -new -x509 -keyout private.pem -out certificate.pem -days 365
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
........................++++++
..++++++
writing new private key to 'private.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
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]:qq
State or Province Name (full name) [Some-State]:ww
Locality Name (eg, city) []:ee
Organization Name (eg, company) [Internet Widgits Pty Ltd]:rr
Organizational Unit Name (eg, section) []:tt
Common Name (eg, YOUR name) []:yy
Email Address []:uu
D:\test\openssl-0.9.8k_X64>keytool -keystore keystore -genkey -alias client -keyalg rsa
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: uu
What is the name of your organizational unit?
[Unknown]: yy
What is the name of your organization?
[Unknown]: tt
What is the name of your City or Locality?
[Unknown]: rr
What is the name of your State or Province?
[Unknown]: ee
What is the two-letter country code for this unit?
[Unknown]: ww
Is CN=uu, OU=yy, O=tt, L=rr, ST=ee, C=ww correct?
[no]: yes
Generating 2 048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 90 days
for: CN=uu, OU=yy, O=tt, L=rr, ST=ee, C=ww
D:\test\openssl-0.9.8k_X64>keytool -keystore keystore -certreq -alias client -keyalg rsa -file client.csr
Enter keystore password:
D:\test\openssl-0.9.8k_X64>.\bin\openssl.exe x509 -req -CA certificate.pem -CAkey private.pem -in client.csr -out client.cer -days 365 -CAcreateserial
Loading 'screen' into random state - done
Signature ok
subject=/C=ww/ST=ee/L=rr/O=tt/OU=yy/CN=uu
Getting CA Private Key
Enter pass phrase for private.pem:
D:\test\openssl-0.9.8k_X64>keytool -import -keystore keystore -file certificate.pem -alias theCARoot
Enter keystore password:
Owner: EMAILADDRESS=uu, CN=yy, OU=tt, O=rr, L=ee, ST=ww, C=qq
Issuer: EMAILADDRESS=uu, CN=yy, OU=tt, O=rr, L=ee, ST=ww, C=qq
Serial number: a51a542a98afc4c9
Valid from: Sun Aug 14 17:33:41 SAKT 2022 until: Mon Aug 14 17:33:41 SAKT 2023
Certificate fingerprints:
SHA1: 45:E2:09:05:60:D6:AA:5A:21:6E:58:F3:4D:12:1E:85:14:1C:B8:7C
SHA256: 80:A5:C6:19:6B:F0:14:F0:9C:0F:8D:C0:80:96:AF:12:F7:6A:E3:25:F0:81:55:ED:32:52:BD:71:2D:5E:E9:38
Signature algorithm name: SHA1withRSA (weak)
Subject Public Key Algorithm: 1024-bit RSA key (weak)
Version: 3
Extensions:
#1: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 04 BA 9F 89 CE E3 9C 37 C8 0B 36 86 68 55 BD 5D .......7..6.hU.]
0010: CA 17 80 22 ..."
]
[EMAILADDRESS=uu, CN=yy, OU=tt, O=rr, L=ee, ST=ww, C=qq]
SerialNumber: [ a51a542a 98afc4c9]
]
#2: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:true
PathLen: no limit
]
#3: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 04 BA 9F 89 CE E3 9C 37 C8 0B 36 86 68 55 BD 5D .......7..6.hU.]
0010: CA 17 80 22 ..."
]
]
Warning:
The input uses the SHA1withRSA signature algorithm which is considered a security risk. This algorithm will be disabled in a future update.
The input uses a 1024-bit RSA key which is considered a security risk. This key size will be disabled in a future update.
Trust this certificate? [no]: yes
Certificate was added to keystore
D:\test\openssl-0.9.8k_X64>keytool -import -keystore keystore -file client.cer -alias client
Enter keystore password:
Certificate reply was installed in keystore
Warning:
Issuer <thecaroot> uses a 1024-bit RSA key which is considered a security risk. This key size will be disabled in a future update.
The input uses the SHA1withRSA signature algorithm which is considered a security risk. This algorithm will be disabled in a future update.
D:\test\openssl-0.9.8k_X64>

SSL issue: alert number 46 (sslv3 alert certificate unknown)

I am stuck with an issue of (SSL alert number 46)
140097325019584:error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate
unknown:../ssl/record/rec_layer_s3.c:1528:SSL alert number 46
Above issue comes when I give crl-file in haproxy config.
Usecase
I am using HAPROXY for ssl termination. I had self signed ca.crt,ca.pem,server.crt,server.pem and client.crt,client.key,crl.pem
Working Scenario
I had generated self signed certificate using Certificate Generate
Ha proxy config
global
log 127.0.0.1 local0 debug
tune.ssl.default-dh-param 2048
defaults
log global
listen mqtt
bind *:2883
bind *:8883 ssl crt /etc/ssl/certs/server.pem verify required ca-file /etc/ssl/certs/ca.pem crl-file /etc/ssl/certs/crl.pem
mode tcp
option tcplog
option clitcpka # For TCP keep-alive
tcp-request content capture dst len 15
timeout client 3h #By default TCP keep-alive interval is 2hours in OS kernal, 'cat /proc/sys/net/ipv4/tcp_keepalive_time'
timeout server 3h #By default TCP keep-alive interval is 2hours in OS kernal
balance leastconn
# MQTT broker 1
server broker_1 ray-mqtt:1883 check send-proxy-v2-ssl-cn
# MQTT broker 2
# server broker_2 10.255.4.102:1883 check
This above config working well with and without crl-file while I generate certificate using Certificate Generate
Non Working Scenario
I generate all certificate using Java bouncy castle library.
Client Certi Generate
public static X509Certificate generateClientCertificate(X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, KeyPair keyPair, X500Name dnName, BigInteger serialNumber) throws IOException, OperatorCreationException, CertificateException {
JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(SHA_256_WITH_RSA).setProvider("BC");
JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
issuerCertificate, //here intermedCA is issuer authority
serialNumber, new Date(),
Date.from(Instant.now().plus(100, ChronoUnit.DAYS)),
dnName, keyPair.getPublic());
builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
X509Certificate x509Certificate = new JcaX509CertificateConverter()
.getCertificate(builder
.build(signerBuilder.build(issuerPrivateKey)));// private key of signing authority , here it is signed by intermedCA
return x509Certificate;
}
CRL Generate
private static X509CRL generateCrl(X509Certificate ca, PrivateKey caPrivateKey, PublicKey caPublicKey,
X509Certificate... revoked) throws Exception {
X509v2CRLBuilder builder = new X509v2CRLBuilder(
new X500Name(ca.getSubjectDN().getName()),
new Date()
);
builder.setNextUpdate(Date.from(Instant.now().plus(100000l, ChronoUnit.HOURS)));
for (X509Certificate certificate : revoked) {
builder.addCRLEntry(certificate.getSerialNumber(), new Date(), CRLReason.PRIVILEGE_WITHDRAWN.ordinal());
}
builder.addExtension(Extension.cRLNumber, false, new CRLNumber(BigInteger.valueOf(4)));
// builder.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(ca.getEncoded()));
builder.addExtension(Extension.authorityKeyIdentifier, false,
new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(caPublicKey));
JcaContentSignerBuilder contentSignerBuilder =
new JcaContentSignerBuilder(SHA_256_WITH_RSA_ENCRYPTION);
contentSignerBuilder.setProvider(BC_PROVIDER_NAME);
X509CRLHolder crlHolder = builder.build(contentSignerBuilder.build(caPrivateKey));
JcaX509CRLConverter converter = new JcaX509CRLConverter();
converter.setProvider(BC_PROVIDER_NAME);
return converter.getCRL(crlHolder);
}
Here, In HAproxy config when I will not include crl-file then It works with the client certificates.
but when I include crl-file into the haproxy config then it will give alert number 46 (sslv3 alert certificate unknown) error.
I had verified using openssl
cat client3.pem | openssl verify -CAfile ca.crt
which returns OK.
Output of openssl s_client -connect haproxy:8883 -cert client3.crt -key client3.key -CAfile ca.crt
CONNECTED(00000005)
depth=1 CN = *.ray.life
verify return:1
depth=0 CN = haproxy
verify return:1
---
Certificate chain
0 s:CN = haproxy
i:CN = *.ray.life
1 s:CN = *.ray.life
i:CN = *.ray.life
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIBujCCASOgAwIBAgIBATANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDAoqLnJh
eS5saWZlMB4XDTIwMDEwNzExMzIyOFoXDTIwMDQxNjExMzIyOFowEjEQMA4GA1UE
AwwHaGFwcm94eTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0CAq/xYcCXWl
PJgs2+DeRRO5DRK813LIiRzdoMFeKrI9X5yXeNFzc6mSAS9EdFITM/HJYSvL/XhZ
p+Hu3N2f9ZR/zD2hpTq2PP0lK3Ev6gryXpWXoJU2SbtOyLsjPmw1y/+xHUjVv5B6
V+m7b0I3RYN8blcJIkjl7Gz83GMlMucCAwEAAaMdMBswDgYDVR0PAQH/BAQDAgeA
MAkGA1UdEwQCMAAwDQYJKoZIhvcNAQELBQADgYEAnmIG9SXICU78Dz2eGbNN2znY
OGCpt7TBDkuXthStAFAyzHxZFKqexkelnJNMg19CbWzxGrPk6lxJQ+ebCGEYZwiZ
/WB9C1fQm+07/FEKVc1TCKv0odpTGRyXno4NePnFz6MCJGfVmec0huVPMD9fAbeJ
DlcWed88CL1MdgmkKoQ=
-----END CERTIFICATE-----
subject=CN = haproxy
issuer=CN = *.ray.life
---
Acceptable client certificate CA names
CN = *.ray.life
Requested Signature Algorithms: ECDSA+SHA256:ECDSA+SHA384:ECDSA+SHA512:Ed25519:Ed448:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA+SHA256:RSA+SHA384:RSA+SHA512:ECDSA+SHA224:ECDSA+SHA1:RSA+SHA224:RSA+SHA1
Shared Requested Signature Algorithms: ECDSA+SHA256:ECDSA+SHA384:ECDSA+SHA512:Ed25519:Ed448:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA+SHA256:RSA+SHA384:RSA+SHA512
Peer signing digest: SHA256
Peer signature type: RSA-PSS
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 1440 bytes and written 1488 bytes
Verification: OK
---
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Server public key is 1024 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
139659759231424:error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown:../ssl/record/rec_layer_s3.c:1528:SSL alert number 46
Any help will be very useful for me.
You need to add the AKI and SKI extension in the CA certificate to validate the CRL by HA proxy.

Mutual SSL - client certificate chain emtpy when using java as a client

We are using java client(openJDK 1.8.0) to call an api that needs mutual authentication. For this we are using java standard JKS file as a keystore and truststore (same file for containing both trustcerts and identity certs/privatekey). Sample java we are using to test is as below ::
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
clientKeyStore.load(new FileInputStream("./client.keystore"),
password.toCharArray());
// create a client connection manager to use in creating httpclients
PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager();
SSLContext sslContext = SSLContextBuilder.create()
.loadKeyMaterial(clientKeyStore, password.toCharArray())
.loadTrustMaterial(clientKeyStore, null).build();
// create the client based on the manager, and use it to make the call
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(mgr)
.setSslcontext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpPost httppost = new HttpPost("https://someUrl");
String params = "";
StringEntity param = new StringEntity(params);
httppost.setEntity(param);
System.out.println("Sending request...............");
HttpResponse response = httpClient.execute(httppost);
During SSL handshake as a last step of "serverhello", server is requesting client's identity by issuing "certificaterequest" - please find below request ::
*** CertificateRequest
Cert Types: RSA, ECDSA, DSS
Supported Signature Algorithms: SHA512withRSA, Unknown (hash:0x6, signature:0x2), SHA512withECDSA, SHA384withRSA, Unknown (hash:0x5, signature:0x2), SHA384withECDSA, SHA256withRSA, SHA256withDSA, SHA256withECDSA, SHA224withRSA, SHA224withDSA, SHA224withECDSA, SHA1withRSA, SHA1withDSA, SHA1withECDSA
Cert Authorities:
<CN=Intermediate CA, OU=ourCA.com, O=ourCA Inc, C=US>
Right after this, we are seeing below lines indicating java's keyManager is not able to find anything signed with the same signer.
*** ServerHelloDone
[read] MD5 and SHA1 hashes: len = 4
0000: 0E 00 00 00 ....
Warning: no suitable certificate found - continuing without client authentication
*** Certificate chain
<Empty>
***
We have validated that the certificate is present in the keystore and its a valid certificate( by opening it in windows box, it wont open if its invalid cert). So our keystore has an chain : myIdentity >> signed by Intermediate CA >>signed by Root CA
A few things we have tried(without any luck) is :
Tried overriding keystoremanager to return a hardcoded alias ie alias of the certificate in keystore.jks
Tried splitting identity certs and CA certs in two separate files ie separate keystore.jks and truststore.jks
Its worth sharing that the same connectivity works well if we are using cURL. In case of cURL, we have to pass client certificate explicitly as an argument ( cURL has no concept of keystore) and we are using linux default keystore (/etc/pki/tls/certs/ca-bundle.crt)
curl -vvv GET https://api.someone.com/some/path -E /home/certificates/client.test.pem --key /home/certificates/client.test.key
I am not sure what other details can add value but I'll be happy to share all the possible details needed ( except my private key :-P )
I had the same problem as you described.
The issue I had was that I loaded the keystore in Java using:
System.setProperty("javax.net.ssl.keyStore", "/path/key.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "pass");
When the server requested a ClientCertificate all a got was:
*** CertificateRequest
Cert Types: RSA, DSS Supported Signature Algorithms: SHA512withRSA, SHA512withECDSA, SHA384withRSA, SHA384withECDSA, SHA256withRSA, SHA256withECDSA, Unknown (hash:0x4,signature:0x2), SHA224withRSA, SHA224withECDSA, Unknown (hash:0x3,signature:0x2), SHA1withRSA, SHA1withECDSA, SHA1withDSA
Cert Authorities:
&ltCN=HB Internal Issuing CA, DC=domainx, DC=hb, DC=bis>
*** ServerHelloDone
Warning: no suitable certificate found - continuing without client authentication
The solution for this was to load the keystore in a different way as described by:
Java SSLHandshakeException "no cipher suites in common"
Basically what I did was to change how I created the SSLContext:
From:
System.setProperty("javax.net.ssl.keyStore", "/path/key.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "pass");
System.setProperty("javax.net.ssl.trustStore", "/path/trust.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
SSLContext c = SSLContext.getInstance("TLSv1.2");
c.init(null, null, null);
To:
// instantiate a KeyStore with type JKS
KeyStore ks = KeyStore.getInstance("JKS");
// load the contents of the KeyStore
final char[] keyPasswd = "pass".toCharArray();
ks.load(new FileInputStream("/path/key.jks"), keyPasswd);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(ks, keyPasswd);
SSLContext c = SSLContext.getInstance("TLSv1.2");
c.init(keyManagerFactory.getKeyManagers(), null, null);
and the result then was:
*** CertificateRequest
Cert Types: RSA, DSS
Supported Signature Algorithms: SHA512withRSA, SHA512withECDSA, SHA384withRSA, SHA384withECDSA, SHA256withRSA, SHA256withECDSA, Unknown (hash:0x4, signature:0x2), SHA224withRSA, SHA224withECDSA, Unknown (hash:0x3, signature:0x2), SHA1withRSA, SHA1withECDSA, SHA1withDSA
Cert Authorities:
&ltCN=HB Internal Issuing CA, DC=domainx, DC=hb, DC=bis>
*** ServerHelloDone
matching alias: ibmwebspheremq01

Encryption and Decryption with X.509 public certificate

I want to encrypt my post payload with an X.509 certificate and the inherited public key. So far I have this java code to perform the encryption
private String encrypt(String str) throws Exception {
ClassPathResource classPathResource = new ClassPathResource("testcert1.crt");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)certificateFactory.generateCertificate(classPathResource.getInputStream());
PublicKey pk = certificate.getPublicKey();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, pk);
return Base64.encodeBase64String(cipher.doFinal(str.getBytes()));
}
which returns the base64 encoded string. From the endpoint I am always getting the result, that the certificate is not valid.
So I want to validate my encrypted string on the console using the openssl command, but failing to do so.
I can read out the certificate with: openssl x509 -in testcert1.crt -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 0 (0x0)
Signature Algorithm: md5WithRSAEncryption
Issuer: C=xxx, ST=xxx, L=xxx, O=xxx, OU=xxx, CN=xxx
Validity
Not Before: Jul 24 11:40:39 2013 GMT
Not After : Jul 24 11:40:39 2015 GMT
Subject: C=xxx, ST=xxx, L=xxx, O=xxx, OU=xxx, CN=xxx
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public Key: (4096 bit)
Modulus (4096 bit):
....
Exponent: 65537 (0x10001)
But I cannot figure out the command lines to encrypt/decrypt a text file using that certificate
You can validate your encrypted string using openssl with the following command:
echo -n 'string to encrypt' | openssl rsautl -encrypt -certin -inkey testcert1.crt | base64
As you are using asymmetric cryptography, if you encrypt using the public key of your certificate, you can only decrypt using the corresponding private key. Make sure you have that key and use it for decryption.

KeyStoreException: No private keys found in keystore with not-yet-commons-ssl-0.3.11.jar

In the course of using Client certificates for authentication, I decided to use not-yet-commons-ssl-0.3.11.jar. That has resulted in another issue - the simple act of invoking the constructor on EasySSLProtocolSocketFactory or StrictSSLProtocolSocketFactory will produce an exception.
The code, as isolated in a simple cmd line app:
public class CertTest {
public static void main(String[] args) {
System.setProperty("javax.net.debug", "ssl,handshake"); // SSL DEBUG INFO
String keystore = "/usr/java/jdk1.6.0_11/jre/lib/security/cacerts";
String keystorePassword = "changeit";
System.setProperty("javax.net.ssl.keyStore", keystore);
System.setProperty("javax.net.ssl.keyStorePassword", keystorePassword);
// System.setProperty("javax.net.ssl.trustStore", keystore);
// System.setProperty("javax.net.ssl.trustStorePassword", keystorePassword);
try {
org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory factory =
new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory();
}
catch (Exception e) {
System.out.println (e);
}
}
}
To isolate issues with older libs, I put the above code in a directory with these jars (these are the ONLY jars in the classpath):
httpclient-4.0.1.jar
not-yet-commons-ssl-0.3.11.jar
commons-httpclient-3.1.jar
httpcore-4.0.1.jar
So, with some client certificates in the cacerts keystore, I get:
org.apache.commons.ssl.ProbablyBadPasswordException: Probably bad JKS-Key password: java.security.UnrecoverableKeyException: Password must not be null
If I use keytool to delete all the client certificates that I have loaded, then the exception changes to
**Caused by: java.security.KeyStoreException: No private keys found in keystore!**
at org.apache.commons.ssl.KeyStoreBuilder.validate(KeyStoreBuilder.java:269)
at org.apache.commons.ssl.KeyStoreBuilder.build(KeyStoreBuilder.java:129)
at org.apache.commons.ssl.KeyMaterial.(KeyMaterial.java:179)
at org.apache.commons.ssl.KeyMaterial.(KeyMaterial.java:170)
at org.apache.commons.ssl.KeyMaterial.(KeyMaterial.java:160)
at org.apache.commons.ssl.KeyMaterial.(KeyMaterial.java:64)
at org.apache.commons.ssl.KeyMaterial.(KeyMaterial.java:114)
at org.apache.commons.ssl.KeyMaterial.(KeyMaterial.java:89)
at org.apache.commons.ssl.SSL.(SSL.java:142)
at org.apache.commons.ssl.SSLClient.(SSLClient.java:59)
at org.apache.commons.ssl.HttpSecureProtocol.(HttpSecureProtocol.java:55)
at org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory.(EasySSLProtocolSocketFactory.java:94)
Snippets in the output:
keyStore is : /usr/java/jdk1.6.0_11/jre/lib/security/cacerts
keyStore type is : jks
keyStore provider is :
init keystore
init keymanager of type SunX509
trustStore is: /usr/java/jdk1.6.0_11/jre/lib/security/cacerts
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert:
Subject: CN=SwissSign Platinum CA - G2, O=SwissSign AG, C=CH
Issuer: CN=SwissSign Platinum CA - G2, O=SwissSign AG, C=CH
Algorithm: RSA; Serial number: 0x4eb200670c035d4f
whole bunch of default trusted certs snipped here...
trigger seeding of SecureRandom
done seeding SecureRandom
########## EXCEPTION
java.security.KeyStoreException: No private keys found in keystore!
Any ideas?
java.security.KeyStoreException: No private keys found in keystore!
This exception specifically complains that there are no private keys in the keystore you are trying to load.
In the case of cacerts which is Java's default truststore this is true!
But with the code you have posted (meaning you have not posted any code really) or the fact that you don't say anything about the keystore you are trying to load it is not possible to help you on this.

Categories

Resources