Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8578533
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T20:24:43+00:00 2026-06-11T20:24:43+00:00

How can one programmatically obtain a KeyStore from a PEM file containing both a

  • 0

How can one programmatically obtain a KeyStore from a PEM file containing both a certificate and a private key? I am attempting to provide a client certificate to a server in an HTTPS connection. I have confirmed that the client certificate works if I use openssl and keytool to obtain a jks file, which I load dynamically. I can even get it to work by dynamically reading in a p12 (PKCS12) file.

I’m looking into using the PEMReader class from BouncyCastle, but I can’t get past some errors. I’m running the Java client with the -Djavax.net.debug=all option and Apache web server with the debug LogLevel. I’m not sure what to look for though. The Apache error log indicates:

...
OpenSSL: Write: SSLv3 read client certificate B
OpenSSL: Exit: error in SSLv3 read client certificate B
Re-negotiation handshake failed: Not accepted by client!?

The Java client program indicates:

...
main, WRITE: TLSv1 Handshake, length = 48
main, waiting for close_notify or alert: state 3
main, Exception while waiting for close java.net.SocketException: Software caused connection abort: recv failed
main, handling exception: java.net.SocketException: Software caused connection abort: recv failed
%% Invalidated:  [Session-3, TLS_RSA_WITH_AES_128_CBC_SHA]
main, SEND TLSv1 ALERT:  fatal, description = unexpected_message
...

The client code :

public void testClientCertPEM() throws Exception {
    String requestURL = "https://mydomain/authtest";
    String pemPath = "C:/Users/myusername/Desktop/client.pem";

    HttpsURLConnection con;

    URL url = new URL(requestURL);
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(getSocketFactoryFromPEM(pemPath));
    con.setRequestMethod("GET");
    con.setDoInput(true);
    con.setDoOutput(false);  
    con.connect();

    String line;

    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

    while((line = reader.readLine()) != null) {
        System.out.println(line);
    }       

    reader.close();
    con.disconnect();
}

public SSLSocketFactory getSocketFactoryFromPEM(String pemPath) throws Exception {
    Security.addProvider(new BouncyCastleProvider());        
    SSLContext context = SSLContext.getInstance("TLS");

    PEMReader reader = new PEMReader(new FileReader(pemPath));
    X509Certificate cert = (X509Certificate) reader.readObject();        

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null);
    keystore.setCertificateEntry("alias", cert);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(keystore, null);

    KeyManager[] km = kmf.getKeyManagers(); 

    context.init(km, null, null);

    return context.getSocketFactory();
} 

I noticed the server is outputing SSLv3 in the log while the client is TLSv1. If I add the system property -Dhttps.protocols=SSLv3 then the client will use SSLv3 as well, but I get the same error message. I’ve also tried adding -Dsun.security.ssl.allowUnsafeRenegotiation=true with no change in outcome.

I’ve googled around and the usual answer for this question is to just use openssl and keytool first. In my case I need to read the PEM directly on the fly. I’m actually porting a C++ program that already does this, and frankly, I’m very surprised how difficult it is to do this in Java. The C++ code:

  curlpp::Easy request;
  ...
  request.setOpt(new Options::Url(myurl));
  request.setOpt(new Options::SslVerifyPeer(false));
  request.setOpt(new Options::SslCertType("PEM"));
  request.setOpt(new Options::SslCert(cert));
  request.perform();
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T20:24:45+00:00Added an answer on June 11, 2026 at 8:24 pm

    I figured it out. The problem is that the X509Certificate by itself isn’t sufficient. I needed to put the private key into the dynamically generated keystore as well. It doesn’t seem that BouncyCastle PEMReader can handle a PEM file with both cert and private key all in one go, but it can handle each piece separately. I can read the PEM into memory myself and break it into two separate streams and then feed each one to a separate PEMReader. Since I know that the PEM files I’m dealing with will have the cert first and the private key second I can simplify the code at the cost of robustness. I also know that the END CERTIFICATE delimiter will always be surrounded with five hyphens. The implementation that works for me is:

    protected static SSLSocketFactory getSocketFactoryPEM(String pemPath) throws Exception {        
        Security.addProvider(new BouncyCastleProvider());
    
        SSLContext context = SSLContext.getInstance("TLS");
    
        byte[] certAndKey = fileToBytes(new File(pemPath));
    
        String delimiter = "-----END CERTIFICATE-----";
        String[] tokens = new String(certAndKey).split(delimiter);
    
        byte[] certBytes = tokens[0].concat(delimiter).getBytes();
        byte[] keyBytes = tokens[1].getBytes();
    
        PEMReader reader;
    
        reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(certBytes)));
        X509Certificate cert = (X509Certificate)reader.readObject();        
    
        reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(keyBytes)));
        PrivateKey key = (PrivateKey)reader.readObject();        
    
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null);
        keystore.setCertificateEntry("cert-alias", cert);
        keystore.setKeyEntry("key-alias", key, "changeit".toCharArray(), new Certificate[] {cert});
    
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, "changeit".toCharArray());
    
        KeyManager[] km = kmf.getKeyManagers(); 
    
        context.init(km, null, null);
    
        return context.getSocketFactory();
    }
    

    Update: It seems this can be done without BouncyCastle:

        byte[] certAndKey = fileToBytes(new File(pemPath));
        byte[] certBytes = parseDERFromPEM(certAndKey, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
        byte[] keyBytes = parseDERFromPEM(certAndKey, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
    
        X509Certificate cert = generateCertificateFromDER(certBytes);              
        RSAPrivateKey key  = generatePrivateKeyFromDER(keyBytes);
    

    …

    protected static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) {
        String data = new String(pem);
        String[] tokens = data.split(beginDelimiter);
        tokens = tokens[1].split(endDelimiter);
        return DatatypeConverter.parseBase64Binary(tokens[0]);        
    }
    
    protected static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    
        KeyFactory factory = KeyFactory.getInstance("RSA");
    
        return (RSAPrivateKey)factory.generatePrivate(spec);        
    }
    
    protected static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
    
        return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));      
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I was wondering how can I programmatically copy all the discussion items from one
How can one programmatically sort a union query when pulling data from two tables?
Can any one help me in converting the .cs file into .dll programmatically?
Can one call a method from another model in a model in CodeIgniter? I
How can one best test a controller action which receives a file upload using
In iOS , programmatically, how can one find what top most UIView is? In
How can one programmatically determine logins/users that have permission to access specific SSRS reports?
jQuery.fn.jquery equivalent for jQuery Mobile? To programmatically check the version of jQuery one can
I'm utterly lost as to how one can programmatically publish a Google Document (specifically
How can I programmatically select one of the items in an NSMatrix? I believe

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.