6
votes

I am trying to SSH to EC2 using JSch Library from Java code. I referred this link in SO How can I use .pem files content as a string in ec2 connection using JSch library and tried couple of things as mentioned below but in vain. Can someone please guide me on how to achieve my objective?

Objective

I have a PEM file like this. I dont want to store my PEM file anywhere in AWS, hence my approach is to extract an equivalent string that I can encode and store in database and decode it from java for passing the parameter to addIdentity method that takes these parameters:

addIdentity(String name, byte[] prvkey, byte[] pubkey, byte[] passphrase)
    throws JSchException
-----BEGIN RSA PRIVATE KEY-----
MIIepsdfAIBAAKCAQEAtBk068z
...
xVNdhlDy6asdk9wsdQ==
-----END RSA PRIVATE KEY-----

For my objective, my addIdentity method would be like this I believe:

addIdentity ("username","{privatekey string converted to byte array}",null, null)

I am trying to understand how that string can be formed? I am very new to cryptography, but during this process I learnt that since my PEM has BEGIN RSA PRIVATE KEY, it's PKCS1 format. Does JSch support PKCS1 format or it needs to be converted to PKSC8?

Secondly, I learnt that the body is encoded with Base64, so I even tried decoding the string with Base64 after stripping off all the carriage returns, header and footer, which gave me error like this

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence

Below are some of the additional links I tried following up but have not been able to resolve.

Hope someone can guide me in the right direction.

Thanks!

1

1 Answers

5
votes

I figured out the answer. Below post gave me a direction.

JSch: addIdentity from private key stored on hdfs

To anyone else who is looking to solve a similar requirement, ensure that you are not stripping off the header, footer information. This took most of my time to debug as most of the blogs/SO posts directed towards stripping those characters. In Java, your string must have the carriage returns else you might get a very different byte array.

String  x = "-----BEGIN RSA PRIVATE KEY-----\r\n" + 
            "MIIEpAIBAAKCAQEAtBk\Q/z4QAgk+LN3IUajqjUv7IucsCd4SebbQvah5t4WJ\r\n"

Convert the string to byte array using "US-ASCII" charset. Use following JSch method if you don't have a passphrase:

jsch.addIdentity("username",{bytearray of x},null, null)

Note: ensure that you are passing an unsigned byte array like:
Array (45, 45, 69,...)
and NOT
Array (45, -35, -125,...)