I have to store in a DB table the connection details to another databases, I must encrypt the passwords to those DBs and one must be able to "manually" insert data into that table via SQL scripts...
I need to encrypt and decrypt it because my app must be able to use those data and connect to other databases, so MD5 and similar are not useful..
I thought of Blowfish, AES, etc... but if I store the password as VARCHAR in the DB the decrypt part doesn't work... so I stored it as BYTE, but if I do so no one can write a script to pre-load data on the table..
Maybe I'm missing something here...
Here's the code I used when the registry in the table was defined as VARCHAR:
package main;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Prueba {
private static final String keyValue = "fd<[;.7e/OC0W!d|";
private static final String ALG = "Blowfish";
public static void main(String[] args) {
String text = "some random text";
try {
SecretKeySpec key = new SecretKeySpec(keyValue.getBytes(), ALG);
Cipher cipher = Cipher.getInstance(ALG);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(text.getBytes());
String encrypted = new String(encryptedBytes);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes = cipher.doFinal(encrypted.getBytes());
String recovered = new String(recoveredBytes);
} catch (NoSuchAlgorithmException nsa) {
nsa.printStackTrace();
} catch (NoSuchPaddingException nspe) {
nspe.printStackTrace();
} catch (InvalidKeyException ike) {
ike.printStackTrace();
} catch (BadPaddingException bpe) {
bpe.printStackTrace();
} catch (IllegalBlockSizeException ibse) {
ibse.printStackTrace();
}
}
}
And I get the exception:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA12275)
at javax.crypto.Cipher.doFinal(DashoA12275)
at main.Prueba.main(Prueba.java:30)
If instead of:
byte[] recoveredBytes = cipher.doFinal(encrypted.getBytes());
I do
byte[] recoveredBytes = cipher.doFinal(encryptedBytes);
I get no exception, but then I must store the password as byte[] soooo no script posible...
Any ideas?