James Sabre wrote:Your code for writing and reading the key is seriously flawed. You must close the key file when writing it and you cannot rely on the read() to read the whole of your key file when reading it. Read the Javadoc for InputStream.read(byte ) to see why. The safest way to read the file is to use DataInputStream.readFully(). For example -
Though failure of your read() to read the whole key could cause the BadPaddingException I have never seen this problem on a lightly loaded system.
The difficulty I had with your code is that you don't return the ciphertext or cleartext from your encrypt() and decrypt() methods yet you say your BadPaddingException occurs only when you do! After changing your code so it returns the cleartext/ciphertext I don't see your problem and don't get the BadPaddingException. There are three common causes of BadPaddingException. First if the key used is incorrect, second if the ciphertext is corrupted and third if you try to decrypt something that is not encrypted. From you test harness I suspect you are trying to decrypt something that has not been encrypted OR that your key is not being read or written propperly.
Note - it is considered insecure to encrypt and store passwords. It is normally better to use a randomly seeded hashing so that nobody can easily obtain the original password from the hashed password. Even if you do have to encrypt the passwords, it is not considered secure to use ECB mode (the mode you get by default) since it is open to fraud by splicing of ciphertext and more worryingly it will allow someone with access to the database to determine which people have the same password. You should use something like CBC mode with a random IV.