How to have a java program do the same thing as the ssh unix command (0) where the userName does not have a password associated with it?
(0) The unix command that works
ssh -i ~/.ssh/pemFile.pem -L 8000:ec2-0-0-0-0.compute-1.amazonaws.com:8000 userName@ec2-0-0-0-0.compute-1.amazonaws.com
(1) The pem file
-----BEGIN RSA PRIVATE KEY-----
SOMETEXSOMETEXTALJDLAJFAJFLADSFJASDFFDA
ALDFJALFJASLDFASFDASJDLFJASLDFJAJSSDLF
-----END RSA PRIVATE KEY-----
(2) Java program that currently does not work ( i think i need a user info object or something also I do not have both a cert and key in my pem file do I need to generate one of these?)
public static void main (String args []) throws Exception {
String pemPath = "/Users/username/.ssh/pemFile.pem";
String ec2 = "userName@ec2-0-0-0-0.compute-1.amazonaws.com";
SSLSocketFactory factory = null;
factory = getSocketFactoryPEM(pemPath);
InetAddress remote = InetAddress.getByName(ec2);
InetAddress local = InetAddress.getByName("localhost");
Socket socket = factory.createSocket(remote, 8000, local, 8000);
}
public static SSLSocketFactory getSocketFactoryPEM(String pemPath) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TLS");
byte[] certAndKey = getBytesFromFile(new File(pemPath));
String delimiter = "-----BEGIN RSA PRIVATE KEY-----";
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();
}
Here are some examples to look at
http://www.example-code.com/java/ssh.asp
http://www.beanizer.org/site/index.php/en/Articles/Java-ssh-tunneling-with-jsch.html
Hope this helps.
Regards,
Tomas Helgi