简体   繁体   English

如何使用JSch库在ec2连接中将.pem文件内容用作字符串

[英]How can I use .pem files content as a string in ec2 connection using JSch library

Here is the code to get the connection to amazon instance using .pem file. 这是使用.pem文件连接到亚马逊实例的代码。

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. 我想将.pem文件( jsch.addIdentity(privateKey); )中的私钥设置为来自数据库的字符串。 Now it is a file name. 现在它是一个文件名。 Is this possible, any help would be appreciable. 如果有可能,任何帮助都是可取的。 I have got this code from the link click here 我从链接中获得了此代码, 请点击此处

The Jsch class provides this method which takes both the private and the public key as byte array: Jsch类提供了以下方法该方法将私钥和公钥都作为字节数组:

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

So you can read your database fields into a String and then pass it, eg 因此,您可以将数据库字段读取为字符串,然后将其传递,例如

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

final JSch jsch = new JSch();
jsch.addIdentity("my key", privateKey.getBytes(), publicKey.getBytes(), passphrase.getBytes());

I just put pem file name as the "my key" and pass the content of the pem file as a byte[] as follows. 我只是将pem文件名作为“我的密钥”,并将pem文件的内容作为byte []传递如下。 jsch.addIdentity("privateKeyFile.pem", pemString.getBytes(), null, null); 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. 注意,我必须在pem内容的第一行上附加“ + System.getProperty(“ line.separator”)“。 The other lines do not need the line separator but unless the first line ends in a separator, it errors out. 其他行不需要行分隔符,但是除非第一行以分隔符结尾,否则它会出错。 eg "-----BEGIN RSA PRIVATE KEY-----" + System.getProperty("line.separator") 例如,“ ----- BEGIN RSA PRIVATE KEY -----” + System.getProperty(“ line.separator”)

Calling JSCH 调用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM