Hi,
I would like to encrypt some data, store it in a DB (as a
string), then get the data and decrypt it. My code fails with a paddingexception. I can see why - in the code below the bytearray []encryptedBAFromDB is only 16 bytes long. Regardless, even if I pad it to 32 bytes (same as encrypted[]), the values are completely different.
If I use the original bytearray (c.doFinal(encrypted)) then there is no problem - the toString() does not work obviously - though I havent been able to understand why....
Any hints appreciated.
rgds
jim
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
public class CipherTest {
public static void main(String args[]) {
try {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
Key key = kg.generateKey();
c.init(Cipher.ENCRYPT_MODE, key);
byte input[] = "This is a string to encrypt....".getBytes();
byte encrypted[] = c.doFinal(input);
byte iv[] = c.getIV();
System.out.println("Encrypted string: [" + encrypted + "]");
//Store this in the DB
String encryptedString=encrypted.toString();
IvParameterSpec dps = new IvParameterSpec(iv);
c.init(Cipher.DECRYPT_MODE, key, dps);
//Now 'get' from the DB as a string
String encryptedStringFromDB=encryptedString;
byte []encryptedBAFromDB=encryptedStringFromDB.getBytes();
int numBytes=encryptedBAFromDB.length;
byte[] paddedByteArray =null;
if ((numBytes % 8) != 0) {
paddedByteArray = new byte[numBytes+(8-(numBytes%8))];
for(int i = 0; i<numBytes; i++) {
paddedByteArray[i] = encryptedBAFromDB[i];
}
for(int i = numBytes; i<paddedByteArray.length; i++) {
paddedByteArray[i] = 0;
}
byte output[] = c.doFinal(paddedByteArray);
System.out.print("Decrypted string: [" + new String(output) + "]");
} else {
byte output[] = c.doFinal(encryptedBAFromDB);
System.out.print("Decrypted string: [" + new String(output) + "]");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}