title: Using private RSA Key from .keystore File with Jsch
body: <p>I am trying to get private Key from a .keystore File that I created.</p>
  
  <p>So far, this is working:</p>
  
  <pre><code>        try {
          FileInputStream is = new FileInputStream("C:\\Program Files\\Java\\...mykeystore.keystore");
  
          KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
          keystore.load(is, "mypassword".toCharArray());
          Key privKey = keystore.getKey("alias", "mypassword".toCharArray());
  
          StringWriter stringWriter = new StringWriter();
          JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
          pemWriter.writeObject(privKey);
          pemWriter.close();
          System.out.println(stringWriter);
  </code></pre>
  
  <p>For the System.out.println(stringWriter) I get the following output:</p>
  
  <p>-----BEGIN RSA PRIVATE KEY-----</p>
  
  <p><strong>PRIVATE KEY IS HERE</strong></p>
  
  <p>-----END RSA PRIVATE KEY-----</p>
  
  <p>I now would like to use this private key to create a ssh connection to a Unix Server. On the unix server side I already put the public key in to the authorized_key files.</p>
  
  <p>For the ssh connection I use JSch.
  According to <a href="https://stackoverflow.com/questions/15332120/jsch-invalid-private-key">JSCH - Invalid private key</a> I now need to convert this key to PEM Format. I did this with the example from Abdelhameed Mahmoud:</p>
  
  <pre><code>        StringWriter stringWriter = new StringWriter();
          JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
          pemWriter.writeObject(privKey);
          pemWriter.close();
          System.out.println(stringWriter);
          byte[] privateKeyPEM = stringWriter.toString().getBytes();
  </code></pre>
  
  <p>And here it is where I am stuck.</p>
  
  <p>How can I use the privateKeyPEM byte object?
  I want to use this with the jsch.addIdentity()</p>
  
  <p>But I do not really understand how I can use this byte[] privateKeyPEM variable to set the identity?</p>
  
  <p>Here an Example for my JSch part:</p>
  
  <pre><code>     JSch jsch = new JSch();
          jsch.addIdentity(**What to put here??**);
          session = jsch.getSession(user, getIP(), getPort());
          session.setConfig("PreferredAuthentications", "publickey");
          //session.setPassword(pwd);
          session.setConfig("StrictHostKeyChecking", "no");
          session.connect(3000);
  </code></pre>
  
  <p>Has anyone experience with this? </p>
  
  <p>Sorry for the missing comments, as I am still figuring out how to get this working I did not add any comments yet.</p>
  
  <p>Thanks in advance for any helpful input.</p>
  
  <p>Cheers
  Armin</p>