Password decrypting exception - Very Urgent ---Help required
807580Aug 11 2009 — edited Aug 13 2009Hi All,
I know there are lots of post regarding this but I could not figure out the problem after reading the posts.
I am encrypting the password and keeping in the properties file. This encrypted password I am reading and decrypting in the program hence getting following exception:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.ibm.crypto.provider.DESedeCipher.engineDoFinal(Unknown Source)
at com.ibm.crypto.provider.DESedeCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Unknown Source)
at com.walmart.ems.webservice.encryptPassword.decrypt(encryptPassword.java:74)
at com.walmart.ems.webservice.encryptPassword.main(encryptPassword.java:56)
I know while storing in the properties file, it has to be converted into the Hexdecimal format otherwise you will get the exception called IllegalBlockSizedException, that I am already doing ....
I am also sure this is the problem with storing and accessing the password from properties file because If i do on fly means do not store in the properties file it works fine...
Here is the code:
public class encryptPassword {
private static String algorithm = "DESede";
private static Key key = null;
private static Cipher cipher = null;
private static void setUp() throws Exception {
key = KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance(algorithm);
}
public static void main(String args[]) throws Exception {
setUp();
if (args.length !=1) {
System.out.println(
"USAGE: java LocalEncrypter " +
"[String]");
System.exit(1);
}
String password = ResourceBundle.getBundle("WebServiceClientProps").getString("SYSTEM_PASSWORD");
byte[] decode = hexStringToByteArray(password);
System.out.println("Recovered: " + decrypt(decode).toString());
}
private static byte[] encrypt(String input)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes();
return cipher.doFinal(inputBytes);
}
private static String decrypt(byte[] encryptionBytes)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes =
cipher.doFinal(encryptionBytes);
String recovered =
new String(recoveredBytes);
return recovered;
}
public static String byteArrayToHexString(byte[] b){
StringBuffer sb = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++){
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
public static byte[] hexStringToByteArray(String s) {
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++){
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte)v;
}
return b;
}
}