0

Here is the code to get the connection to amazon instance using .pem file.

import com.jcraft.jsch.*;

public class JConnectEC2shell{
  public static void main(String[] arg){

    try{
      JSch jsch=new JSch();

      String user = "ec2-user";
      String host = "Enter Ip address of your instance";
      int port = 22;
      String privateKey = "D:\\privateKeyFile.pem";

      jsch.addIdentity(privateKey);
      System.out.println("identity added ");

      Session session = jsch.getSession(user, host, port);
      System.out.println("session created.");

      // disabling StrictHostKeyChecking may help to make connection but makes it insecure
      // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
      // 
         java.util.Properties config = new java.util.Properties();
         config.put("StrictHostKeyChecking", "no");
         session.setConfig(config);

      session.connect();

      Channel channel=session.openChannel("shell");

      // Enable agent-forwarding.
      //((ChannelShell)channel).setAgentForwarding(true);

      channel.setInputStream(System.in);
      /*
      // a hack for MS-DOS prompt on Windows.
      channel.setInputStream(new FilterInputStream(System.in){
          public int read(byte[] b, int off, int len)throws IOException{
            return in.read(b, off, (len>1024?1024:len));
          }
        });
       */

      channel.setOutputStream(System.out);

      /*
      // Choose the pty-type "vt102".
      ((ChannelShell)channel).setPtyType("vt102");
      */

      /*
      // Set environment variable "LANG" as "ja_JP.eucJP".
      ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
      */

      //channel.connect();
      channel.connect(3*1000);
    }
    catch(Exception e){
      System.out.println(e);
    }
  }
}

I want to set the private key in .pem file (jsch.addIdentity(privateKey);) as a string coming from the data base. Now it is a file name. Is this possible, any help would be appreciable. I have got this code from the link click here

flavio.donze
  • 7,432
  • 9
  • 58
  • 91
Melvin Moses
  • 407
  • 2
  • 6
  • 17

3 Answers3

0

The Jsch class provides this method which takes both the private and the public key as byte array:

addIdentity(String name, byte[]prvkey, byte[]pubkey, byte[] passphrase)

So you can read your database fields into a String and then pass it, e.g.

// read db columns
String privateKey = ... 
String publicKey = ...
String passphrase = ...

final JSch jsch = new JSch();
jsch.addIdentity("my key", privateKey.getBytes(), publicKey.getBytes(), passphrase.getBytes());
thomas.mc.work
  • 6,404
  • 2
  • 26
  • 41
  • Could you please give me an example with the above method. That would be more grateful. – Melvin Moses Apr 19 '16 at 05:09
  • All I have is the .pem file, can we isolate the private key, public key and pass phrase from the .pem file. Any help would be grateful. – Melvin Moses Apr 19 '16 at 06:35
  • Check this to create the public key from your private key file: http://stackoverflow.com/questions/5244129/use-rsa-private-key-to-generate-public-key#5246045. After creation you can put the content in the DB too, same with the passphrase. If you haven't defined a passphrase then you can probably leave it empty (`null`). – thomas.mc.work Apr 19 '16 at 06:54
  • Thanks for your input, I have a confusion with the "my key"(first attribute of the addIdentity method). How can I get that one. – Melvin Moses Apr 20 '16 at 08:45
  • This is only the name of your key, so you can choose anything in here. (I've also added the link to the documentation of that interface in the answer) – thomas.mc.work Apr 20 '16 at 11:27
  • When I given a name for the key I have the exception. com.jcraft.jsch.JSchException: invalid privatekey:'the given name' – Melvin Moses Apr 21 '16 at 04:54
0

I just put pem file name as the "my key" and pass the content of the pem file as a byte[] as follows. jsch.addIdentity("privateKeyFile.pem", pemString.getBytes(), null, null);

Note, I had to append " + System.getProperty("line.separator")" on the first line of the pem content. The other lines do not need the line separator but unless the first line ends in a separator, it errors out. e.g. "-----BEGIN RSA PRIVATE KEY-----" + System.getProperty("line.separator")

h.ozawa
  • 71
  • 1
  • 2
0

Calling JSCH

String pemFormat = addMarkers(connectionParams.getIdentity());
jsch.addIdentity("TunnelPrivateKey.pem", pemFormat.getBytes(), null, null);

Remove space and add Markers

private static String addMarkers(String identity) {
        identity = identity.replaceAll("\\s+", "");
        String lineBreak = "\r\n";
        StringBuilder key = new StringBuilder();
        key.append("-----BEGIN RSA PRIVATE KEY-----");
        key.append(lineBreak);
        for (int i = 0; i< identity.length(); i+=76) {
            int len = Math.min(i+76 , identity.length());
            key.append(identity.substring(i, len));
            key.append(lineBreak);
        }
        key.append("-----END RSA PRIVATE KEY-----");
        return key.toString();
}
Deepak Kumar
  • 161
  • 1
  • 6