11

I know there are already a few posts about this error, but I couldn't find an answer fitting my problem :

I created an AES key with the following command :

keytool -genseckey -alias TEST -keyalg AES -keysize 128 -storepass "a#b$c<d>" 
-storetype JCEKS -keystore /usr/my/path/test.jck

I then try to access the keystore from java code :

String password = "a#b$c<d>";

char[] passwordChars= password.toCharArray(); 

// loading the file containing the key
InputStream inputStreamFichierCle;
try {
    inputStreamFichierCle = new FileInputStream(filePath);
    keyStore.load(inputStreamFichierCle, passwordChars);
}

And there I get an IOException : keystore was tampered with or password was incorrect.

Note that I tried with normal password (ex : pass) and this works perfectly, so I guess the problem here has to do with the special characters I use in my password.

What is happening, and how can I fix this?

realUser404
  • 2,111
  • 3
  • 20
  • 38

1 Answers1

21

The cause of this problem is the dollar sign in combination with bash command line.

Basically "$c" is substituted with the content of a variable with the name "c". Unfortunately there is no variable with this name, so it is replaced with an empty string.

You can avoid the variable substitution by using single quotes. See the difference:

$ echo "a#b$c<d>"
a#b<d>
$ echo 'a#b$c<d>'
a#b$c<d>

If you use the password "a#b<d>" in your java code, it will work.

Community
  • 1
  • 1
Omikron
  • 4,072
  • 1
  • 27
  • 28
  • you saved me from another wasted day! Thank you! – Jonas Stawski Nov 30 '17 at 22:22
  • My keyPassword also contained a "\$n" part. Using this password always caused this error: java.security.UnrecoverableKeyException: Cannot recover key. I removed the backslash in this password and the password worked! – GedankenNebel May 09 '18 at 09:39
  • @GedankenNebel Good point, the escape character "\" also removes the special meaning from the "$" like single quotes do, so the $ is part of the password, but because the \ itself is a special character, it is missing in the resulting password. – Omikron May 09 '18 at 11:14
  • 2
    @GedankenNebel That's why it is recommended to use single quotes instead. You can then put any character in the password and nothing changes unexpectedly. – Omikron May 09 '18 at 11:21