0

I'm trying to get an ssh private key data from command line.

./myProgram --prvKey '-----BEGIN RSA PRIVATE KEY-----\nxxx\n-----END RSA PRIVATE KEY-----\n'

In my Git class, I use the key data as below:

protected JSch createDefaultJSch(FS fs) throws JSchException {
    String prvKeyData = Main.getPrvKeyData();
    System.out.println(prvKeyData);
    JSch jSch = super.createDefaultJSch(fs);
    jSch.addIdentity("monitoring-configs", prvKeyData.getBytes(), null, "passphrase".getBytes());
    return jSch;
      }

But this fails with an invalid ssh key error message.

I checked that it works well when putting that string into the code directly.

And I also checked that the System.out.println result is exactly the same as the input I gave(containing \n).

I guess that bash does something with backslashes, so that in my Java program, the \n is not understood properly.

How can I debug and resolve this?

yoon
  • 1,177
  • 2
  • 15
  • 28
  • Yes, if you pass an argument `myprogrm '\n'` then the \n will be a two character string and not a new line. Did you try using a newline instead of \n? – matt Nov 30 '21 at 10:50
  • While bash 'does something with backslash' in some other cases, here it just passes it through; but when you put `\n` in a String (or char) literal _in Java sourcecode_ Java converts it to a single newline character, which is what is needed. – dave_thompson_085 Dec 01 '21 at 06:20
  • if I execute `echo 'foo\nbar'` or `echo "foo\nbar"` I see two lines of output, so bash is putting a newline character in the command parameter. – Bohemian Dec 01 '21 at 22:53

1 Answers1

0

If you can change the input string, just use enter instead of '\n' sequences.

/myProgram --prvKey '-----BEGIN RSA PRIVATE KEY-----
xxx
-----END RSA PRIVATE KEY-----
'

Then the java argument will contain new lines instead of the string "\n"

matt
  • 10,892
  • 3
  • 22
  • 34
  • I cannot give an input with a real newline because I'm giving it with a web UI which only supports a single line... Is there a way to replace such `a two character string` with a real newline character `\n`? – yoon Nov 30 '21 at 17:40
  • 1
    @yoon: `prvKeyData.replace("\\n","\n")` (not `replaceAll` because that uses regex aka `Pattern` syntax which is less convenient here). Or if you mean the UI takes a single-line _that is passed to and executed by bash_, use `$'stuff\nstuff\n'` -- _bash_ (but not necessarily other shells) will change those into real newlines – dave_thompson_085 Dec 01 '21 at 06:25
  • @yoon The only issue I would be worried about when using String.replace are the characters "\\n" valid values inside of the key. Is it a base64 encoded string of bytes? From this question it looks ok. https://stackoverflow.com/a/13195218/2067492 since only the / is valid base64. – matt Dec 01 '21 at 09:07