Home > I O Error > I/o Error Reading Keystore/truststore File

I/o Error Reading Keystore/truststore File

Contents

Save This Page Home » apache-cxf-2.2.7 » org.apache.commons.httpclient.contrib » ssl » [javadoc | source] 1 /** 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. Two complicating factors made this a bit interesting. The keystore must show that it has a "trustedCertEntry." This is the incantation I used to build a server truststore file in Java Keystore ("JKS") format using the keytool command that comes with Java; after keytool shows the details you have to tell it to trust the certificate: keytool -importcert -alias "server" -file server.crt -keystore server.keystore -deststorepass password1 I had to save the client's private key in a Java keystore file, and it must appear in that keystore as a "PrivateKeyEntry" (not a certificate entry). First, the server requires access via HTTPS, and for that it uses a self-signed server certificate. http://orgias.org/i-o-error/i-o-error-reading-keystore-truststore-file-invalid-keystore-format.html

This is the .pem used for the Intermediate Certificate field. 1) Rename RapidSSL_CA_pkcs7_bundle.pem to RapidSSL_CA_pkcs7_bundle.pkcs7 2) Run this openssl command below from any system which has openssl installed. Forgive me for assuming UTF-8 encoding for the server response! Otherwise SSL context initialization error will result. 180 * 181 * @param keystoreUrl URL of the keystore file. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream keyStream = new FileInputStream(keystoreFile); try { System.out.println("Loading client keystore from file " + keystoreFile.getPath()); keyStore.load(keyStream, keystorePassword.toCharArray()); System.out.println("Keystore certificate count: " + keyStore.size()); } catch (Exception ex) { System.err.println("Failed to load keystore: " + ex.toString()); return; } finally { try { keyStream.close(); } catch (Exception ignore) { } } // Create and register a socket factory for all HTTPS connections SSLSocketFactory socketFactory = null; try { // http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html // This constructor has zero words of documentation in the // version 4.1.2 javadoc; I only figured it out by googling.

Authsslprotocolsocketfactory Example Httpclient

AHbhEm5OSxYShjAGsoEIz/AIx8dxfmbuwu3UOx//8PDITtZDOLC5MH0Y0FWDomrL NhGc6Ehmo21/uBPUR/6LWlxz/K7ZGzIZOKuXNBSqltLroxwUCEm2u+WR74M26x1W b8ravHNjkOR/ez4iyz0H7V84dJzjA1BOoa+Y7mHyhD8S -----END CERTIFICATE----- There is an internal bug 57955 created for this problem. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 20 package org.apache.commons.httpclient.contrib.ssl; 21 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.net.InetAddress; 25 import java.net.InetSocketAddress; 26 import java.net.Socket; 27 import java.net.SocketAddress; 28 import java.net.URL; 29 import java.net.UnknownHostException; 30 import java.security.GeneralSecurityException; 31 import java.security.KeyStore; 32 import java.security.KeyStoreException; 33 import java.security.NoSuchAlgorithmException; 34 import java.security.UnrecoverableKeyException; 35 import java.security.cert.Certificate; 36 import java.security.cert.CertificateException; 37 import java.security.cert.X509Certificate; 38 import java.util.Enumeration; 39 40 import org.apache.commons.httpclient.ConnectTimeoutException; 41 import org.apache.commons.httpclient.params.HttpConnectionParams; 42 import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; 43 import org.apache.commons.logging.Log; 44 import org.apache.commons.logging.LogFactory; 45 46 import javax.net.SocketFactory; 47 import javax.net.ssl.KeyManager; 48 import javax.net.ssl.KeyManagerFactory; 49 import javax.net.ssl.SSLContext; 50 import javax.net.ssl.TrustManager; 51 import javax.net.ssl.TrustManagerFactory; 52 import javax.net.ssl.X509TrustManager; 53 54 /** 55 *

56 * AuthSSLProtocolSocketFactory can be used to validate the identity of the HTTPS 57 * server against a list of trusted certificates and to authenticate to the HTTPS 58 * server using a private key. 59 *

60 * 61 *

62 * AuthSSLProtocolSocketFactory will enable server authentication when supplied with 63 * a {@link KeyStore truststore} file containg one or several trusted certificates. 64 * The client secure socket will reject the connection during the SSL session handshake 65 * if the target HTTPS server attempts to authenticate itself with a non-trusted 66 * certificate. 67 *

68 * 69 *

70 * Use JDK keytool utility to import a trusted certificate and generate a truststore file: 71 *

 72  * keytool -import -alias "my server cert" -file server.crt -keystore my.truststore 73  * 
74 *

75 * 76 *

77 * AuthSSLProtocolSocketFactory will enable client authentication when supplied with 78 * a {@link KeyStore keystore} file containg a private key/public certificate pair. 79 * The client secure socket will use the private key to authenticate itself to the target 80 * HTTPS server during the SSL session handshake if requested to do so by the server. 81 * The target HTTPS server will in its turn verify the certificate presented by the client 82 * in order to establish client's authenticity 83 *

84 * 85 *

86 * Use the following sequence of actions to generate a keystore file 87 *

88 *
    89 *
  • 90 *

    91 * Use JDK keytool utility to generate a new key 92 *

    keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore
    93 * For simplicity use the same password for the key as that of the keystore 94 *

    95 *
  • 96 *
  • 97 *

    98 * Issue a certificate signing request (CSR) 99 *

    keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore
    100 *

    101 *
  • 102 *
  • 103 *

    104 * Send the certificate request to the trusted Certificate Authority for signature. 105 * One may choose to act as her own CA and sign the certificate request using a PKI 106 * tool, such as OpenSSL. 107 *

    108 *
  • 109 *
  • 110 *

    111 * Import the trusted CA root certificate 112 *

    keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore
    113 *

    114 *
  • 115 *
  • 116 *

    117 * Import the PKCS#7 file containg the complete certificate chain 118 *

    keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore
    119 *

    120 *
  • 121 *
  • 122 *

    123 * Verify the content the resultant keystore file 124 *

    keytool -list -v -keystore my.keystore
    125 *

    126 *
  • 127 *
128 *

129 * Example of using custom protocol socket factory for a specific host: 130 *

 131  * Protocol authhttps = new Protocol("https", 132  * new AuthSSLProtocolSocketFactory( 133  * new URL("file:my.keystore"), "mypassword", 134  * new URL("file:my.truststore"), "mypassword"), 443); 135  * 136  * HttpClient client = new HttpClient(); 137  * client.getHostConfiguration().setHost("localhost", 443, authhttps); 138  * // use relative url only 139  * GetMethod httpget = new GetMethod("/"); 140  * client.executeMethod(httpget); 141  * 
142 *

143 *

144 * Example of using custom protocol socket factory per default instead of the standard one: 145 *

 146  * Protocol authhttps = new Protocol("https", 147  * new AuthSSLProtocolSocketFactory( 148  * new URL("file:my.keystore"), "mypassword", 149  * new URL("file:my.truststore"), "mypassword"), 443); 150  * Protocol.registerProtocol("https", authhttps); 151  * 152  * HttpClient client = new HttpClient(); 153  * GetMethod httpget = new GetMethod("https://localhost/"); 154  * client.executeMethod(httpget); 155  * 
156 *

157 * @author Oleg Kalnichevski 158 * 159 *

160 * DISCLAIMER: HttpClient developers DO NOT actively support this component. 161 * The component is provided as a reference material, which may be inappropriate 162 * for use without additional customization. 163 *

164 */ 165 166 public class AuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory { 167 168 /** Log object for this class. */ 169 private static final Log LOG = LogFactory.getLog(AuthSSLProtocolSocketFactory.class); 170 171 private URL keystoreUrl = null; 172 private String keystorePassword = null; 173 private URL truststoreUrl = null; 174 private String truststorePassword = null; 175 private SSLContext sslcontext = null; 176 177 /** 178 * Constructor for AuthSSLProtocolSocketFactory. This requirement can be met in a couple of ways: either the HttpClient can be told to trust all servers no matter what, or the server certificate can be cached locally for comparison. To enable this, the caller must supply a * keystore file containing the expected user certificate. * * Built and tested using Apache HTTP Components version 4.1.2. * * Used Java's keytool to create the server truststore from a .crt file: * *
 * keytool -importcert -alias "server" -file server.crt -keystore server.keystore -deststorepass password1 * 
* * Used Java's keytool to creaet the client keystore from a .p12 file: * *
 * keytool -v -importkeystore -srckeystore user.p12 -srcstoretype PKCS12 -srcstorepass changeit -destkeystore user.keystore -deststoretype JKS -deststorepass password2 * 
* * Note that JDK versions 1.6.0_19 thru JDK 1.6.0_23 prohibit SSL renegotiation. * Reopen this possible security hole by supplying this JVM argument: * -Dsun.security.ssl.allowUnsafeRenegotiation=true * * This is a revised version of ClientCustomSSL, an example program contributed * to the Apache Http Client project, and available here:
* http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/ * http/examples/client/ClientCustomSSL.java * * @author Chris Lott, http://www.maultech.com/chrislott/ */ public class ServerClientCustomSSL { public final static void main(String[] args) throws Exception { if (args.length != 6) { System.err .println("Usage: server-truststore-file-name server-truststore-password client-keystore-file-name client-keystore-password client-key-password target-URI"); return; } File truststoreFile = new File(args[0]); if (!truststoreFile.exists() || !truststoreFile.isFile()) { System.err.println("Not found or not a file: " + truststoreFile.getPath()); return; } System.out.println("Truststore file with server cert is " + truststoreFile.getPath()); String truststorePassword = args[1]; if (truststorePassword.length() == 0) { System.err.println("Empty truststore password, giving up"); return; } System.out.println("Truststore password is " + truststorePassword); File keystoreFile = new File(args[2]); if (!keystoreFile.exists() || !keystoreFile.isFile()) { System.err.println("Not found or not a file: " + keystoreFile.getPath()); return; } System.out.println("Keystore file with client private key is " + keystoreFile.getPath()); String keystorePassword = args[3]; if (keystorePassword.length() == 0) { System.err.println("Empty keystore password, giving up"); return; } System.out.println("Keystore password is " + truststorePassword); String privateKeyPassword = args[4]; if (privateKeyPassword.length() == 0) { System.err.println("Empty private key password, giving up"); return; } System.out.println("Private key password is " + privateKeyPassword); URI targetURI = new URI(args[5]); String protocol = targetURI.getScheme(); if (!"https".equals(protocol)) { System.err .println("URI does not begin with expected protocol name"); return; } System.out.println("URI to fetch is " + targetURI.toString()); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // The expected server certificate must be in a *trust* store. // keytool must report "trustedCertEntry" when listing the contents.

I found example code at the Apache site, but it was for version 3 and no longer works in v4. The certificate is available in a .crt file (x509 * format?). System.err .println("Get failed, possible missing or invalid certificate: " + ex.toString()); return; } catch (SSLException sx) { // Renegotiation must be allowed in certain JDK versions via the // JVM argument -Dsun.security.ssl.allowUnsafeRenegotiation=true System.err .println("Get failed, possible missing JVM argument: " + sx.toString()); return; } catch (Exception x) { // Something I have not seen (yet) System.err.println("Get failed unexpectedly: " + x.toString()); return; } HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println("Response status: " + response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); if (entity.getContentLength() > 0) { byte[] first100 = new byte[100]; int howMany = entity.getContent().read(first100); // Hope that the encoding is sane String hundred = new String(first100, 0, howMany, "UTF-8"); System.out.println("First " + howMany + " characters of the response:"); System.out.println(hundred); } } // read the rest and close the stream EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } Blog index United States English English IBM® Site map IBM IBM Support Check here to start a new keyword search. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License.

May be null if HTTPS client 182 * authentication is not to be used. 183 * @param keystorePassword Password to unlock the keystore. A blog post by Tim Sawyer was extremely helpful in pointing out that this scenario requires both a *keystore* and a *truststore*, but I still struggled to get the keystore and truststore files set up appropriately. Document information More support for: IBM BigFix family Software version: Version Independent Operating system(s): Platform Independent Reference #: 1640148 Modified date: 2013-06-18 Site availability Site assistance Contact and feedback Need support? Visit Website I learned from googling that keytool can read a PKCS12 file and import its contents appropriately.

So I supplied the correct password to load the keystore, but not the right password to decrypt the private key within the keystore. May be null if HTTPS server 186 * authentication is not to be used. 187 * @param truststorePassword Password to unlock the truststore. 188 */ 189 public AuthSSLProtocolSocketFactory(final URL keystoreUrl, final String keystorePassword, 190 final URL truststoreUrl, final String truststorePassword) { 191 super(); 192 this.keystoreUrl = keystoreUrl; 193 this.keystorePassword = keystorePassword; 194 this.truststoreUrl = truststoreUrl; 195 this.truststorePassword = truststorePassword; 196 } 197 198 private static KeyStore createKeyStore(final URL url, final String password) throws KeyStoreException, 199 NoSuchAlgorithmException, CertificateException, IOException { 200 if (url == null) { 201 throw new IllegalArgumentException("Keystore url may not be null"); 202 } 203 LOG.debug("Initializing key store"); 204 KeyStore keystore = KeyStore.getInstance("jks"); 205 InputStream is = null; 206 try { 207 is = url.openStream(); 208 keystore.load(is, password != null ? Either a keystore or truststore file 179 * must be given. java.security.UnrecoverableKeyException: Cannot recover key When I botched the user private key certificate by supplying a keystore file with the wrong content, I hit this exception: org.apache.http.impl.client.DefaultRequestDirector handleResponse WARNING: Authentication error: Unable to respond to any of these challenges: {} I used Java version 1.6.0_20, and apparently this VM has an SSL implementation that blocks SSL renegotation, which presented itself as this exception: javax.net.ssl.SSLException: HelloRequest followed by an unexpected handshake message I frankly don't understand all the ramifications of this, but again googling yielded the answer.

Authsslprotocolsocketfactory Maven

IMPORTANT: this implementation 184 * assumes that the same password is used to protect the key and the keystore itself. 185 * @param truststoreUrl URL of the truststore file. https://community.oracle.com/thread/2170853 But note that his only appears *if some other problem is also present*; it's not necessary when all the keystores and passwords are correct. -Dsun.security.ssl.allowUnsafeRenegotiation=true Putting all the pieces together yields the following demonstration code. Authsslprotocolsocketfactory Example Httpclient This is the incantation I used to build a client keystore file in JKS format using the keytool command; again you have to approve import of the data: keytool -v -importkeystore -srckeystore user.p12 -srcstoretype PKCS12 -srcstorepass changeit -destkeystore user.keystore -deststoretype JKS -deststorepass password2 Along the way I hit various stumbling blocks of course. Authsslprotocolsocketfactory Javadoc If socket constructor does not return until the 326 * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException} 327 *

328 * 329 * @param host the host name/IP 330 * @param port the port on the host 331 * @param clientHost the local host name/IP to bind the socket to 332 * @param clientPort the port on the local machine 333 * @param params {@link HttpConnectionParams Http connection parameters} 334 * 335 * @return Socket a new socket 336 * 337 * @throws IOException if an I/O error occurs while creating the socket 338 * @throws UnknownHostException if the IP address of the host cannot be 339 * determined 340 */ 341 public Socket createSocket(final String host, final int port, final InetAddress localAddress, 342 final int localPort, final HttpConnectionParams params) throws IOException, 343 UnknownHostException, ConnectTimeoutException { 344 if (params == null) { 345 throw new IllegalArgumentException("Parameters may not be null"); 346 } 347 int timeout = params.getConnectionTimeout(); 348 SocketFactory socketfactory = getSSLContext().getSocketFactory(); 349 if (timeout == 0) { 350 return socketfactory.createSocket(host, port, localAddress, localPort); 351 } else { 352 Socket socket = socketfactory.createSocket(); 353 SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); 354 SocketAddress remoteaddr = new InetSocketAddress(host, port); 355 socket.bind(localaddr); 356 socket.connect(remoteaddr, timeout); 357 return socket; 358 } 359 } 360 361 /** 362 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) 363 */ 364 public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) 365 throws IOException, UnknownHostException { 366 return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); 367 } 368 369 /** 370 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) 371 */ 372 public Socket createSocket(String host, int port) throws IOException, UnknownHostException { 373 return getSSLContext().getSocketFactory().createSocket(host, port); 374 } 375 376 /** 377 * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) 378 */ 379 public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, 380 UnknownHostException { 381 return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); 382 } 383 } Save This Page Home » apache-cxf-2.2.7 » org.apache.commons.httpclient.contrib » ssl » [javadoc | source] Server and Client Certificates in HTTPS for Apache Client 7 Jan 2012 I'm working on a client to access a RESTful (representation state transfer AKA http) web service.

And just to make it fun, the javadoc for the critical constructor in the SSLSocketFactory class is utterly free of any description, and the parameter names are barely helpful. news However, the port 443 is not listening on the MDM Extender. Supposedly other versions don't have this problem but I have not yet tested them. Currently, the code that parses certificate bundles expects a flat list of PEM-encoded of X509 certificates.

password.toCharArray() : null); 209 } finally { 210 if (is != null) 211 is.close(); 212 } 213 return keystore; 214 } 215 216 private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password) 217 throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { 218 if (keystore == null) { 219 throw new IllegalArgumentException("Keystore may not be null"); 220 } 221 LOG.debug("Initializing key manager"); 222 KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); 223 kmfactory.init(keystore, password != null ? I had to save the server's certificate in a Java keystore file. That yielded the following exception. have a peek at these guys Apache offers example code to demonstrate caching a self-signed certificate so that was no sigificant problem.

The client key was available in a PKCS12 (".p12") format and that was critical. Launching the program with this additional VM argument turns this off. To allow this, the caller must supply a truststore file containing * the expected server certificate. *

  • The user must supply a private key to the server for authentication.

    The controller thread attempts to create a new socket 325 * within the given limit of time.

    See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. openssl pkcs7 -in RapidSSL_CA_pkcs7_bundle.pkcs7 -print_certs -out RapidSSL_CA_pkcs7_bundle.pem 3) Now use this converted RapidSSL_CA_pkcs7_bundle.pem certificate file in the Intermediate Certificate field. Please drop me a line if it helps you.

     package of.your.choice; import java.io.File; import java.io.FileInputStream; import java.net.URI; import java.security.KeyStore; import java.security.UnrecoverableKeyException; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; /** * Demonstrates use of the Apache HTTP Client version 4 to access a web site via * HTTPS, with special conditions: * 
      *
    1. The server presents a self-signed certificate (not signed by a trusted * certificate authority). password.toCharArray() : null); 224 return kmfactory.getKeyManagers(); 225 } 226 227 private static TrustManager[] createTrustManagers(final KeyStore keystore) throws KeyStoreException, 228 NoSuchAlgorithmException { 229 if (keystore == null) { 230 throw new IllegalArgumentException("Keystore may not be null"); 231 } 232 LOG.debug("Initializing trust manager"); 233 TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory 234 .getDefaultAlgorithm()); 235 tmfactory.init(keystore); 236 TrustManager[] trustmanagers = tmfactory.getTrustManagers(); 237 for (int i = 0; i < trustmanagers.length; i++) { 238 if (trustmanagers[i] instanceof X509TrustManager) { 239 trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager)trustmanagers[i]); 240 } 241 } 242 return trustmanagers; 243 } 244 245 private SSLContext createSSLContext() { 246 try { 247 KeyManager[] keymanagers = null; 248 TrustManager[] trustmanagers = null; 249 if (this.keystoreUrl != null) { 250 KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); 251 if (LOG.isDebugEnabled()) { 252 Enumeration aliases = keystore.aliases(); 253 while (aliases.hasMoreElements()) { 254 String alias = (String)aliases.nextElement(); 255 Certificate[] certs = keystore.getCertificateChain(alias); 256 if (certs != null) { 257 LOG.debug("Certificate chain '" + alias + "':"); 258 for (int c = 0; c < certs.length; c++) { 259 if (certs[c] instanceof X509Certificate) { 260 X509Certificate cert = (X509Certificate)certs[c]; 261 LOG.debug(" Certificate " + (c + 1) + ":"); 262 LOG.debug(" Subject DN: " + cert.getSubjectDN()); 263 LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); 264 LOG.debug(" Valid from: " + cert.getNotBefore()); 265 LOG.debug(" Valid until: " + cert.getNotAfter()); 266 LOG.debug(" Issuer: " + cert.getIssuerDN()); 267 } 268 } 269 } 270 } 271 } 272 keymanagers = createKeyManagers(keystore, this.keystorePassword); 273 } 274 if (this.truststoreUrl != null) { 275 KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); 276 if (LOG.isDebugEnabled()) { 277 Enumeration aliases = keystore.aliases(); 278 while (aliases.hasMoreElements()) { 279 String alias = (String)aliases.nextElement(); 280 LOG.debug("Trusted certificate '" + alias + "':"); 281 Certificate trustedcert = keystore.getCertificate(alias); 282 if (trustedcert != null && trustedcert instanceof X509Certificate) { 283 X509Certificate cert = (X509Certificate)trustedcert; 284 LOG.debug(" Subject DN: " + cert.getSubjectDN()); 285 LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); 286 LOG.debug(" Valid from: " + cert.getNotBefore()); 287 LOG.debug(" Valid until: " + cert.getNotAfter()); 288 LOG.debug(" Issuer: " + cert.getIssuerDN()); 289 } 290 } 291 } 292 trustmanagers = createTrustManagers(keystore); 293 } 294 SSLContext sslcontext = SSLContext.getInstance("SSL"); 295 sslcontext.init(keymanagers, trustmanagers, null); 296 return sslcontext; 297 } catch (NoSuchAlgorithmException e) { 298 LOG.error(e.getMessage(), e); 299 throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); 300 } catch (KeyStoreException e) { 301 LOG.error(e.getMessage(), e); 302 throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); 303 } catch (GeneralSecurityException e) { 304 LOG.error(e.getMessage(), e); 305 throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); 306 } catch (IOException e) { 307 LOG.error(e.getMessage(), e); 308 throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " 309 + e.getMessage()); 310 } 311 } 312 313 private SSLContext getSSLContext() { 314 if (this.sslcontext == null) { 315 this.sslcontext = createSSLContext(); 316 } 317 return this.sslcontext; 318 } 319 320 /** 321 * Attempts to get a new socket connection to the given host within the given time limit. 322 *

      323 * To circumvent the limitations of older JREs that do not support connect timeout a 324 * controller thread is executed.

      Reviewed the contents of this PKCS7 file with any text editor before and after the conversion: Before: ======= -----BEGIN PKCS7----- MIIHhwYJKoZIhvcNAQcCoIIHeDCCB3QCAQExADALBgkqhkiG9w0BBwGgggdaMIID 1TCCAr2gAwIBAgIDAjbRMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVTMRYw FAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwg Q0EwHhcNMTAwMjE5MjI0NTA1WhcNMjAwMjE4MjI0NTA1WjA8MQswCQYDVQQGEwJV . .. 1Dsf//DwyE7WQziwuTB9GNBVg6JqyzYRnOhIZqNtf7gT1Ef+i1pcc/yu2RsyGTir lzQUqpbS66McFAhJtrvlke+DNusdVm/K2rxzY5Dkf3s+Iss9B+1fOHSc4wNQTqGv mO5h8oQ/EqEAMQA= -----END PKCS7----- After: ====== subject=/C=US/O=ComanyName, Inc./CN=RapidSSL CA issuer=/C=US/O=CompanName, Inc./CN=CompanyName Global CA -----BEGIN CERTIFICATE----- MIID1TCCAr2gAwIBAgIDAjbRMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i . . . 04BqIhPSLT90T+qvjF+0OJzbrs6vhB6m9jRRWXnT43XcvNfzc9+S7NIgWW+c+5X4 knYYCnwPLKbK3opie9jzzl9ovY8+wXS7FXI6FoOpC+ZNmZzYV+yoAVHHb1c0XqtK LEL2TxyJeN4mTvVvk0wVaydWTQBUbHq3tw== -----END CERTIFICATE----- subject=/C=US/O=ComanyName Inc./CN=ComanyName Global CA issuer=/C=US/O=Equifax/OU=Equifax Secure Certificate Authority -----BEGIN CERTIFICATE----- MIIDfTCCAuagAwIBAgIDErvmMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0 aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDIwNTIxMDQwMDAwWhcNMTgwODIxMDQwMDAw . . . All straightforward so far, right? The second requirement, presenting a user certificate to the server, was a bit tricker. http://orgias.org/i-o-error/i-o-error-reading-bcp-format-file.html If other format is used such as PKCS7, the above error will be generated.

      Stackoverflow offered pieces of code but not the full solution. Watson Product Search Search None of the above, continue with my search Error reading certificate: java.io.IOException: DerInputStream.getLength(): lengthTag=127, too big Technote (FAQ) Question Error reading certificate: java.io.IOException: DerInputStream.getLength(): lengthTag=127, too big Cause In Setup Enrollment and Apple iOS Management Extender | Configure Extender | SSL settings | selected "Use my own externally signed SSL files" option | filled in all the SSL cert file, SSL private key file and Intermediate certificate file, the Configuration iOS Management Extender task completed successfully. I find the Java keytool fairly inscrutable but that's prolly because I'm not a crypto person. Maybe that's just the buzzword of choice these days, but the system seems to conform to Wikipedia's list of REST architecture constraints.

      You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. It traps all the exceptions that I hit and tries to give helpful messages :). To resolve this, do the following steps: Note: using this 3rd party SSL certificate "RapidSSL_CA_pkcs7_bundle.pem" as example. It should resolve the issue.

      Initially I supplied the wrong server certificate, and I hit this exception: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated At least once I gave the wrong password for a keystore and this exception is what happens: java.io.IOException: Keystore was tampered with, or password was incorrect While I knew that the private key is protected by a password, I didn't quite grasp that this protection is preserved when it's imported into the destination keystore, which of course is protected by a different password. I'm reusing version 4.1.2 libraries provided by the Apache HttpComponents project. Without this https.jks file, the SSL service can't start up and port 443 won't be listening. Because this file holds the server info, the proper term is a *truststore*, which is the term used in the Apache HttpClient javadoc.

      socketFactory = new SSLSocketFactory(keyStore, privateKeyPassword, trustStore); } catch (UnrecoverableKeyException ke) { System.err .println("Failed to create SSLSocketFactory, possible wrong password on client private key"); return; } // This is the default port number only; others are allowed Scheme sch = new Scheme("https", 443, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet httpget = new HttpGet(targetURI); System.out.println("Executing request " + httpget.getRequestLine()); HttpResponse response = null; try { response = httpclient.execute(httpget); } catch (SSLPeerUnverifiedException ex) { // Message "peer not authenticated" means the server presented // a certificate that was not found in the local truststore. The * key is available in PCKS12 format. In the jetty.log, it had the following error: [2013-05-23 14:13:58 PDT] ERROR [com.bigfix.mdm.JettyLauncher] - Error configuring service for IOS: org.mortbay.util.MultiException[java.io.FileNotFoundException: C:\Program Files (x86)\BigFix Enterprise\Management Extender\MDM Provider\private\https.jks (The system cannot find the file specified.), java.io.FileNotFoundException: C:\Program Files (x86)\BigFix Enterprise\Management Extender\MDM Provider\private\https.jks (The system cannot find the file specified.)] The mdm_tasks.log file showed this error: [2013-05-23 14:13:58 EDT] INFO [MDM.Tasks] - --------------------------------------------------------------- [2013-05-23 14:13:58 EDT] INFO [MDM.Tasks] - Starting IBM Endpoint Manager iOS Server configuration utility [2013-05-23 14:13:58 EDT] INFO [MDM.Tasks] - --------------------------------------------------------------- [2013-05-23 14:13:58 EDT] INFO [MDM.Tasks.ConfigManager] - Config: 'android_relay' = '*.hostname.com:52311' [2013-05-23 14:14:22 EDT] INFO [MDM.Tasks] - --------------------------------------------------------------- [2013-05-23 14:14:22 EDT] INFO [MDM.Tasks] - Starting IBM Endpoint Manager iOS Server configuration utility [2013-05-23 14:14:22 EDT] INFO [MDM.Tasks] - --------------------------------------------------------------- [2013-05-23 14:14:22 EDT] INFO [MDM.Tasks] - Recreating keystore [2013-05-23 14:14:22 EDT] INFO [MDM.Tasks.CertManager] - Removing old SSL Keystore... [2013-05-23 14:14:22 EDT] ERROR [MDM.Tasks] - Unknown error: # C:/Windows/TEMP/war4086365017205288127extract/WEB-INF/gems/gems/mdm-plat form-2.2.9/lib/mdm_platform/cert_manager.rb:118:in `recreate_keystore' Answer If a 3rd party or any SSL certificate is in a PKCS7 format, it will fail with the above error causing the https.jks file to be generated in C:\Program Files (x86)\BigFix Enterprise\Management Extender\MDM Provider\private\ folder. KeyStore trustStore = KeyStore.getInstance(KeyStore .getDefaultType()); FileInputStream trustStream = new FileInputStream(truststoreFile); try { System.out.println("Loading server truststore from file " + truststoreFile.getPath()); trustStore.load(trustStream, truststorePassword.toCharArray()); System.out.println("Truststore certificate count: " + trustStore.size()); } catch (Exception ex) { System.err.println("Failed to load truststore: " + ex.toString()); return; } finally { try { trustStream.close(); } catch (Exception ignore) { } } // The required user key must be in a *key* store. // keytool must report "PrivateKeyEntry" when listing the contents.

      Submit feedback to IBM Support 1-800-IBM-7378 (USA) Directory of worldwide contacts Contact Privacy Terms of use Accessibility