My colleague set up a (Bluemix) secure gateway using mutual auth for our project to use. He tested it with Ruby and CURL and it works fine. but when configuring my Liberty server to use it, I am running in to many issues.
I used the instructions found here.
Basically...
To create a key store for the client, enter the following command. In the following example, key.p.12 is created.
openssl pkcs12 -export -in "[client]_cert.pem" -inkey "[client]_key" -out "sg_key.p12" -name BmxCliCert -noiter –nomaciter –password pass:<password>
Which creates a PKCS12 store. (I use this in server.xml below)
I then added the certs into my keystore.
I then changed my server.xml to have a trust store as referenced in my
<ldapRegistry baseDN="o=ibm.com" host="bluepages.ibm.com" id="bluepages" ignoreCase="true"
ldapType="IBM Tivoli Directory Server" port="636" realm="w3" sslEnabled="true" sslRef="SSLSettings">
<idsFilters groupFilter="(&(cn=%v)(objectclass=groupOfUniqueNames))" groupIdMap="*:cn" groupMemberIdMap="groupOfUniqueNames:uniquemember" userFilter="(&(emailAddress=%v)(objectclass=person))" userIdMap="*:emailAddress"/>
</ldapRegistry>
<ssl id="SSLSettings" keyStoreRef="defaultKeyStore" trustStoreRef="defaultTrustStore"/>
<keyStore id="defaultKeyStore" password="xxxxxx"
location="${server.output.dir}/resources/security/key.jks"/>
<keyStore id="defaultTrustStore"
location="${server.output.dir}/resources/security/sg_key.p12"
type="PKCS12" password="xxxxxx" />
Here's issue #1
When I add the trust store, I can no longer authenticate via my LDAP server. It just says invalid user or password. I remove the trust store.. and I can authenticate again. So adding the truststore has some type of affect.
Issue #2. When I remove my LDAP server and just use basic user registry... I can login in.. but when I try and use the secure gateway, I get..
[err] javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
I have imported the certificate from the secure gateway so not sure why I get this?
So two issues.. Using a truststore.. I can no longer auth via LDAP... and second.. cannot connect to the secure gateway even after importing all certs...
Anyone had success using Bluemix with a Secure Gateway (Mutual Auth) from Java?
Requested info (edited)
Enter Import Password:
MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
friendlyName: portal
localKeyID: 5F A0 D5 5D 68 C5 39 65 7D 24 D7 78 9B CD 7D 01 FB 1B 00 6D
subject=/ST=NC/C=US/L=RTP/O=IBM Corporation/OU=SWG/CN=*.integration.ibmcloud.com
issuer=/ST=NC/C=US/L=RTP/O=IBM Corporation/OU=SWG/CN=*.integration.ibmcloud.com
-----BEGIN CERTIFICATE-----
INFO
4Q==
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
Bag Attributes
friendlyName: portal
localKeyID: 5F A0 D5 5D 68 C5 39 65 7D 24 D7 78 9B CD 7D 01 FB 1B 00 6D
Key Attributes: <No Attributes>
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----BEGIN ENCRYPTED PRIVATE KEY-----
INFO
-----END ENCRYPTED PRIVATE KEY-----
Finally got this to work.
previous code..
. . . .
connection = (HttpsURLConnection) url.openConnection();
Where url was the URL of the Secure Gateway.
Added before this...
KeyStore clientStore = KeyStore.getInstance("PKCS12");
clientStore.load(new FileInputStream(KEY_STORE_PATH), "xxxxxx".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, "xxxxxx".toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream(TRUST_STORE_PATH), "xxxxxx".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext sslContext = null;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kms, tms, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());`
connection = (HttpsURLConnection) url.openConnection();
Now it works... tx
Some good info in this thread.. LINK
Related
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>
Fabric Version: v2.2.4
Fabric Gateway Version: v2.2.0
Currently, I am not using Fabric CA and docker. Instead, I am using OpenSSL to generate my own certificates. There is no problem using command line to join channel or invoke chaincode with TLS enabled (Server TLS).
However, when I try to invoke my chaincode using Fabric Gateway Java SDK with TLS, the peer shows:
2021-10-20 23:53:51.571 EDT [core.comm] ServerHandshake -> ERRO 411 Server TLS handshake failed in 731.664253ms with error remote error: tls: internal error server=PeerServer remoteaddress=127.0.0.1:48920
2021-10-20 23:53:51.648 EDT [core.comm] ServerHandshake -> ERRO 412 Server TLS handshake failed in 17.623962ms with error remote error: tls: internal error server=PeerServer remoteaddress=127.0.0.1:48924
2021-10-20 23:53:52.389 EDT [core.comm] ServerHandshake -> ERRO 413 Server TLS handshake failed in 31.834126ms with error remote error: tls: internal error server=PeerServer remoteaddress=127.0.0.1:48928
2021-10-20 23:53:53.013 EDT [core.comm] ServerHandshake -> ERRO 414 Server TLS handshake failed in 20.97883ms with error remote error: tls: internal error server=PeerServer remoteaddress=127.0.0.1:48932
2021-10-20 23:53:53.453 EDT [core.comm] ServerHandshake -> ERRO 415 Server TLS handshake failed in 27.840631ms with error remote error: tls: internal error server=PeerServer remoteaddress=127.0.0.1:48936
if I disable the TLS, the chaincode can be invoked and queried but it shows an error message and display the certificate of the peer:
04:45:56.020 [main] ERROR org.hyperledger.fabric.sdk.security.CryptoPrimitives - Cannot
validate certificate. Error is: Path does not chain with any of the trust anchors
Certificate[
[
Version: V3
Subject: CN=peer-telecom, OU=peer, O=peer0.telecom.com, ST=Wilayah Persekutuan Kuala Lumpur, C=MY
Signature Algorithm: SHA256withECDSA, OID = 1.2.840.10045.4.3.2
Key: Sun EC public key, 256 bits
public x coord: 63258922835963897769642318382353579773301130246303245867091942631050654760639
public y coord: 17014436126955018341557373411142402131278326611630973049174140241981148702177
parameters: secp256r1 [NIST P-256, X9.62 prime256v1] (1.2.840.10045.3.1.7)
Validity: [From: Mon Oct 18 04:30:10 EDT 2021,
To: Tue Oct 18 04:30:10 EDT 2022]
Issuer: CN=hyperledger-telecom, O=ica.hyperledger.telecom.com, ST=Wilayah Persekutuan Kuala Lumpur, C=MY
SerialNumber: [ 1000]
Certificate Extensions: 4
[1]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 70 2B 57 B5 7C 6A 38 DE AB 6F DD 7E C4 63 FE 39 p+W..j8..o...c.9
0010: 54 22 D9 F9 T"..
]
]
[2]: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:false
PathLen: undefined
]
[3]: ObjectId: 2.5.29.15 Criticality=true
KeyUsage [
DigitalSignature
]
[4]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 62 C2 4A FB 13 54 44 DF 15 AB 2B 09 78 4F 79 4A b.J..TD...+.xOyJ
0010: CB 37 1D D7 .7..
]
]
]
Algorithm: [SHA256withECDSA]
Signature:
0000: 30 44 02 20 2D 20 15 9D 53 D4 DE EF 56 0D E6 6D 0D. - ..S...V..m
0010: 04 DA 99 F8 0C AC D5 A7 87 66 51 04 23 A0 4D C2 .........fQ.#.M.
0020: C8 98 95 5C 02 20 5C A5 5A 2D 19 43 FA E8 C0 E1 ...\. \.Z-.C....
0030: 49 4E C0 DF C9 59 F8 10 34 D6 94 05 51 38 E9 17 IN...Y..4...Q8..
0040: C5 F1 20 1F 0C EC .. ...
]
Java Application code:
package org.example.contract;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.concurrent.TimeoutException;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.hyperledger.fabric.gateway.Identities;
import org.hyperledger.fabric.gateway.Identity;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
public class Sample {
X509Certificate[] clientCert = null;
PrivateKey clientKey = null;
private static X509Certificate readX509Certificate(final Path certificatePath) throws IOException, CertificateException {
try (Reader certificateReader = Files.newBufferedReader(certificatePath, StandardCharsets.UTF_8)) {
return Identities.readX509Certificate(certificateReader);
}
}
private static PrivateKey getPrivateKey(final Path privateKeyPath) throws IOException, InvalidKeyException {
try (Reader privateKeyReader = Files.newBufferedReader(privateKeyPath, StandardCharsets.UTF_8)) {
return Identities.readPrivateKey(privateKeyReader);
}
}
public static void main(String[] args) throws IOException {
// Load an existing wallet holding identities used to access the network.
// A wallet stores a collection of identities
Path walletPath = Paths.get(".", "wallet");
Wallet wallet = Wallets.newFileSystemWallet(walletPath);
try {
Path credentialPath = Paths.get("/root","fabric","localtls","crypto-config", "peerOrganizations",
"org1.telecom.com", "users", "Admin#org1.telecom.com", "msp");
System.out.println("credentialPath: " + credentialPath.toString());
Path certificatePath = credentialPath.resolve(Paths.get("signcerts",
"Admin#org1.telecom.com-cert.pem"));
System.out.println("certificatePem: " + certificatePath.toString());
Path privateKeyPath = credentialPath.resolve(Paths.get("keystore",
"Admin#telecom.com.key"));
X509Certificate certificate = readX509Certificate(certificatePath);
PrivateKey privateKey = getPrivateKey(privateKeyPath);
Identity identity = Identities.newX509Identity("Org1MSP", certificate, privateKey);
String identityLabel = "Admin#org1.telecom.com";
wallet.put(identityLabel, identity);
System.out.println("Write wallet info into " + walletPath.toString() + " successfully.");
} catch (IOException | CertificateException | InvalidKeyException e) {
System.err.println("Error adding to wallet");
e.printStackTrace();
}
// Path to a common connection profile describing the network.
Path networkConfigFile = Paths.get("/root","fabric","localtls","connection.yaml");
String userName = "Admin#org1.telecom.com";
// Configure the gateway connection used to access the network.,
Gateway.Builder builder = Gateway.createBuilder()
.identity(wallet, userName)
.networkConfig(networkConfigFile);
// Create a gateway connection
try (Gateway gateway = builder.connect()) {
// Obtain a smart contract deployed on the network.
Network network = gateway.getNetwork("mychannel");
Contract contract = network.getContract("chaincode");
// Submit transactions that store state to the ledger.
byte[] createCarResult = contract.createTransaction("createMyAsset")
.submit("CAR", "Honda");
System.out.println(new String(createCarResult, StandardCharsets.UTF_8));
byte[] queryCar = contract.submitTransaction("readMyAsset", "CAR");
System.out.println(new String(queryCar, StandardCharsets.UTF_8));
} catch (ContractException | TimeoutException | InterruptedException e) {
e.printStackTrace();
}
}
}
connection.yaml:
name: "Network-Config-Test"
description: "The network used in the integration tests"
version: 1.0.0
client:
organization: telecom
organizations:
telecom:
mspid: Org1MSP
peers:
- peer0.org1.telecom.com
#adminPrivateKey:
#path: '/root/fabric/localtls/crypto-config/peerOrganizations/org1.telecom.com/users/Admin#org1.telecom.com/msp/keystore/Admin#telecom.com.key'
#signedCert:
#path: '/root/fabric/localtls/crypto-config/peerOrganizations/org1.telecom.com/users/Admin#org1.telecom.com/msp/signcerts/Admin#org1.telecom.com-cert.pem'
orderers:
orderer.example.com:
url: grpcs://localhost:6050
#client:
#keyfile: '/root/fabric/localtls/crypto-config/peerOrganizations/org1.telecom.com/users/Admin#org1.telecom.com/tls/client-o.key'
#certfile: '/root/fabric/localtls/crypto-config/peerOrganizations/org1.telecom.com/users/Admin#org1.telecom.com/tls/client-o.crt'
grpcOptions:
hostnameOverride: orderer.example.com
grpc-max-send-message-length: 15
grpc.keepalive_time_ms: 360000
grpc.keepalive_timeout_ms: 180000
negotiationType: TLS
sslProvider: openSSL
tlsCACerts:
path: /root/fabric/localtls/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt
peers:
peer0.org1.telecom.com:
url: grpcs://localhost:7051
#client:
#keyfile: '/root/fabric/localtls/crypto-config/peerOrganizations/org1.telecom.com/users/Admin#org1.telecom.com/tls/client.key'
#certfile: '/root/fabric/localtls/crypto-config/peerOrganizations/org1.telecom.com/users/Admin#org1.telecom.com/tls/client.crt'
grpcOptions:
ssl-target-name-override: peer0.org1.telecom.com
grpc.http2.keepalive_time: 15
hostnameOverride: peer0.org1.telecom.com
negotiationType: TLS
sslProvider: openSSL
tlsCACerts:
path: /root/fabric/localtls/crypto-config/peerOrganizations/org1.telecom.com/peers/peer0.org1.telecom.com/tls/ca.crt
What am I missing? Any answer is welcomed!
Update 1.0
These are the certificates generated by using openSSL, they work when I use command line (I ommitted the hf thing in the Subject Alternative Name, not sure is it important for the application to work?):
The tlscacert:
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
1f:a5:9f:1a:01:ed:c7:3d:30:ca:27:b6:79:9c:82:10:b8:94:84:23
Signature Algorithm: ecdsa-with-SHA256
Issuer: C = MY, ST = Wilayah Persekutuan Kuala Lumpur, L = Kuala Lumpur, O = rca.verisign.com, CN = tls-verisign
Validity
Not Before: Oct 21 03:11:13 2021 GMT
Not After : Oct 19 03:11:13 2031 GMT
Subject: C = MY, ST = Wilayah Persekutuan Kuala Lumpur, L = Kuala Lumpur, O = rca.verisign.com, CN = tls-verisign
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey
Public-Key: (256 bit)
pub:
04:34:b5:ac:a3:42:8c:d4:17:97:ca:16:d5:2f:7a:
00:32:bf:fd:dd:02:8a:33:28:ed:c0:53:5d:e0:42:
79:0d:08:43:1c:22:83:1e:f0:71:91:08:d6:c3:ec:
eb:ac:9c:56:00:da:e8:08:cf:ad:4c:b3:46:e7:e1:
39:1c:5f:bf:fc
ASN1 OID: prime256v1
NIST CURVE: P-256
X509v3 extensions:
X509v3 Subject Key Identifier:
EB:7B:8E:23:26:A7:17:3D:E0:0B:8D:B4:6E:6C:5D:D5:EE:EF:80:AF
X509v3 Authority Key Identifier:
keyid:EB:7B:8E:23:26:A7:17:3D:E0:0B:8D:B4:6E:6C:5D:D5:EE:EF:80:AF
X509v3 Basic Constraints: critical
CA:TRUE
X509v3 Key Usage: critical
Digital Signature, Key Encipherment, Certificate Sign, CRL Sign
Signature Algorithm: ecdsa-with-SHA256
30:45:02:20:63:40:88:2d:c8:51:e5:42:2b:d3:98:60:6f:1e:
3c:d2:f6:59:48:bb:0c:7c:10:b6:28:27:86:20:58:35:0b:19:
02:21:00:c7:87:df:79:75:21:8d:bf:bc:be:aa:c9:44:53:b5:
b4:32:4d:06:2b:a0:05:eb:38:b7:9f:3d:71:80:17:77:69
The Peer TLS cert:
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 4097 (0x1001)
Signature Algorithm: ecdsa-with-SHA256
Issuer: C = MY, ST = Wilayah Persekutuan Kuala Lumpur, L = Kuala Lumpur, O = rca.verisign.com, CN = tls-verisign
Validity
Not Before: Oct 21 03:11:13 2021 GMT
Not After : Oct 21 03:11:13 2022 GMT
Subject: C = MY, ST = Wilayah Persekutuan Kuala Lumpur, O = tls.peer.telecom.com, CN = tls-peer-telecom
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey
Public-Key: (256 bit)
pub:
04:76:c2:e9:94:10:03:2c:3b:2d:90:56:e8:b5:30:
bf:67:f6:b5:b8:9c:73:cd:28:b3:f2:f7:21:e9:f7:
6c:66:38:a9:e8:7c:b0:ea:67:fb:f7:db:72:29:9d:
aa:56:20:92:ab:b1:e5:53:2a:a1:19:0b:0c:8b:65:
36:fe:98:aa:e1
ASN1 OID: prime256v1
NIST CURVE: P-256
X509v3 extensions:
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage: critical
Digital Signature, Key Encipherment
X509v3 Extended Key Usage:
TLS Web Client Authentication, TLS Web Server Authentication
X509v3 Subject Key Identifier:
08:9D:B8:81:4B:39:0D:B1:D4:BD:EC:49:E5:AC:BA:FB:F1:7A:58:51
X509v3 Authority Key Identifier:
keyid:EB:7B:8E:23:26:A7:17:3D:E0:0B:8D:B4:6E:6C:5D:D5:EE:EF:80:AF
X509v3 Subject Alternative Name:
IP Address:127.0.0.1
Signature Algorithm: ecdsa-with-SHA256
30:46:02:21:00:c0:d7:26:b4:e9:30:08:b5:37:46:66:0f:fb:
b6:36:22:04:5f:78:ab:ae:ff:7f:48:e0:7b:ff:e8:f0:88:b4:
e5:02:21:00:86:64:ec:c8:9b:b4:06:b5:3d:d3:c1:54:4f:d2:
a2:bb:1a:e1:a7:e7:84:28:9a:ef:ac:db:ab:65:95:0d:10:2d
The only thing I am missing in the cert is:
1.2.3.4.5.6.7.8.1:
{"attrs":{"hf.Affiliation":"","hf.EnrollmentID":"peer0","hf.Type":"peer"}}
Is this only being used by the Fabric CA? Or it is a must to include?
Fabric TLS certificates are very fiddly. For instance, we've found several cases where the peer and chaincode will accept a malformed cert, but the gateway client refuses to connect using the same certificate. What is probably happening is that you have a problem with the openssl generated cert, but the peer is too lax to report the error. (It also doesn't help that the client TLS libraries simply disconnect, without reporting on the root failure during the handshake.)
In the example above, the cert output shows some differences in PathLen and KeyUsage attributes that differ from what are normally generated by a Fabric CA.
Here are some ideas and techniques that we've found to be useful in debugging TLS handshake issues with the gateway / client SDKs. Try to use these techniques to close any gaps between your certs and the reference certs generated by the Fabric CAs:
Use the Fabric CAs. Even if you plan to generate a certificate chain using OpenSSL and an external authority, you can use the Fabric CAs to generate TLS enrollments and certificates, and compare the reference certs against what you have built up with OpenSSL.
Use curl, or other TLS-enabled clients to help verify the correctness of a certificate. In many cases the errors output by an independent client are directly applicable to the failed TLS handshake when connecting the fabric client.
Use the test-network-k8s system as a reference for setting up the TLS and CA infrastructure. In addition to a "push button" test network, this will provide CA endpoints that can be used to generate reference enrollments / certificates for study.
Inspect the certificates generated by the Fabric CAs, and compare against your hand-crafted certs. For example, here is a certificate dump from a TLS cert generated with the Kube test network - make sure your OpenSSL certs have the same, or similar feature sets and attributes.
$ openssl x509 -in /tmp/ca-cert.pem -text
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
4c:63:74:d5:99:29:ce:e0:b6:28:a2:b5:a4:0e:a0:c1:f3:e9:a9:d5
Signature Algorithm: ecdsa-with-SHA256
Issuer: C=US, ST=North Carolina, O=Hyperledger, OU=Fabric, CN=fabric-ca-server
Validity
Not Before: Oct 21 10:36:00 2021 GMT
Not After : Oct 17 10:36:00 2036 GMT
Subject: C=US, ST=North Carolina, O=Hyperledger, OU=Fabric, CN=fabric-ca-server
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey
Public-Key: (256 bit)
pub:
04:53:f4:ad:e6:6b:4c:75:7e:4a:6d:6e:cd:73:b0:
81:a8:d7:d7:55:c0:fd:22:92:15:fc:2d:20:44:c6:
ec:55:c9:cc:88:3a:14:09:77:e5:4f:4b:b8:98:ee:
71:09:da:e6:f8:7c:f7:39:fa:41:fc:f3:a2:fe:a4:
1e:34:ec:a9:b5
ASN1 OID: prime256v1
NIST CURVE: P-256
X509v3 extensions:
X509v3 Key Usage: critical
Certificate Sign, CRL Sign
X509v3 Basic Constraints: critical
CA:TRUE, pathlen:1
X509v3 Subject Key Identifier:
AB:AF:85:A3:D3:2E:9A:A9:03:49:F5:5C:30:32:2B:92:EC:92:B3:D0
X509v3 Subject Alternative Name:
IP Address:127.0.0.1
Signature Algorithm: ecdsa-with-SHA256
30:45:02:21:00:bf:cc:c1:d2:29:b1:04:3f:55:31:c6:b7:69:
ca:72:12:d7:67:55:14:cd:23:f7:75:16:6c:b1:63:7f:e6:9c:
24:02:20:5d:ff:e3:7e:84:22:d3:f3:52:bd:96:fa:dc:2d:94:
2f:6b:a3:bc:ab:3e:b3:87:10:fd:30:51:a2:4a:ca:ce:b4
-----BEGIN CERTIFICATE-----
MIICKDCCAc6gAwIBAgIUTGN01ZkpzuC2KKK1pA6gwfPpqdUwCgYIKoZIzj0EAwIw
aDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMRQwEgYDVQQK
EwtIeXBlcmxlZGdlcjEPMA0GA1UECxMGRmFicmljMRkwFwYDVQQDExBmYWJyaWMt
Y2Etc2VydmVyMB4XDTIxMTAyMTEwMzYwMFoXDTM2MTAxNzEwMzYwMFowaDELMAkG
A1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMRQwEgYDVQQKEwtIeXBl
cmxlZGdlcjEPMA0GA1UECxMGRmFicmljMRkwFwYDVQQDExBmYWJyaWMtY2Etc2Vy
dmVyMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEU/St5mtMdX5KbW7Nc7CBqNfX
VcD9IpIV/C0gRMbsVcnMiDoUCXflT0u4mO5xCdrm+Hz3OfpB/POi/qQeNOyptaNW
MFQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYE
FKuvhaPTLpqpA0n1XDAyK5LskrPQMA8GA1UdEQQIMAaHBH8AAAEwCgYIKoZIzj0E
AwIDSAAwRQIhAL/MwdIpsQQ/VTHGt2nKchLXZ1UUzSP3dRZssWN/5pwkAiBd/+N+
hCLT81K9lvrcLZQva6O8qz6zhxD9MFGiSsrOtA==
-----END CERTIFICATE-----
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.
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>
***
I am trying to send push notification to iPhone using Java-pns but I am getting the following error...
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
This is my code...
String token="95076d2846e8979b46efd1884206a590d99d0f3f6139d947635ac4186cdc5942";
String host = "gateway.sandbox.push.apple.com";
int port = 2195;
String payload = "{\"aps\":{\"alert\":\"Message from Java o_O\"}}";
NotificationTest.verifyKeystore("res/myFile.p12", "password", false);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(getClass().getResourceAsStream("res/myFile.p12"), "password".toCharArray());
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(keyStore, "password".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
String[] cipherSuites = sslSocket.getSupportedCipherSuites();
sslSocket.setEnabledCipherSuites(cipherSuites);
sslSocket.startHandshake();
char[] t = token.toCharArray();
byte[] b = Hex.decodeHex(t);
OutputStream outputstream = sslSocket.getOutputStream();
outputstream.write(0);
outputstream.write(0);
outputstream.write(32);
outputstream.write(b);
outputstream.write(0);
outputstream.write(payload.length());
outputstream.write(payload.getBytes());
outputstream.flush();
outputstream.close();
System.out.println("Message sent .... ");
For NotificationTest.verifyKeystore I am getting that this valid is File and Keystore.
I am not understanding why I am getting this error.
This is my error log...
** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Cert Authorities:
<empty>
[read] MD5 and SHA1 hashes: len = 10
0000: 0D 00 00 06 03 01 02 40 00 00 .......#..
** ServerHelloDone
[read] MD5 and SHA1 hashes: len = 4
0000: 0E 00 00 00 ....
** Certificate chain
**
** ClientKeyExchange, RSA PreMasterSecret, TLSv1
[write] MD5 and SHA1 hashes: len = 269
...
main, READ: TLSv1 Alert, length = 2
main, RECV TLSv1 ALERT: fatal, handshake_failure
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
I am not understanding why Cert Authorities is empty?
I recommend that you use keytool -list to compare the keystore on the client with those known to the server. The handshake error you are getting is because the Server has done it's hello and is expecting a Client Certificate in reply. You are not sending one. To fix this the PKCS12 certificate should be converted to PEM format (using openssl is one way) and then imported into a keystore using the keytool.
I suspect if you fix this by importing a client certificate into the keystore, then you will hit a second error. The second error will be about the empty CA certs - probably because you don't have a CA cert that is known to your server in your keystore. Import your CA and try again.
Looks like you need to install "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files". This solved the issue for me.
To Send Push Notification to iPhone/ iPad I have used JavaPNS.
It is very easy to use and It worked for me.
We can simply follow This to use it.