I want to use PBE to encrypt my data. So far, I have written the following code :
moteurCryptage = Cipher.getInstance("PBEWithMD5AndDES");
PBEKeySpec spécifClé=new PBEKeySpec(mdp.toCharArray());
SecretKeyFactory usineàClefs=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey clé=null;
try {
clé = usineàClefs.generateSecret(spécifClé);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(DiskUtilView.class.getName()).log(Level.SEVERE, null, ex);
}
moteurCryptage.init(Cipher.ENCRYPT_MODE,clé);
byte[] paramètresEncodage;
try {
paramètresEncodage=moteurCryptage.getParameters().getEncoded();
} catch (IOException ex) {
paramètresEncodage=null;
}
destination=moteurCryptage.update(source1.getBytes());
destination=moteurCryptage.doFinal(source2.getBytes());
moteurCryptage.init(Cipher.DECRYPT_MODE,clé,paramètresEncodage);
source=new String(moteurCryptage.doFinal(destination));
Encryption seems to work (I don’t get any error, neither during compilation nor execution) but the initialisation of the Cipher object for decryption doesn’t accept the javax.crypto.SecretKey class (compilation error). It instead asks for a java.security.key.
What can I do?
Thanks in advance for the time you will spend trying to help me.
The problem is the line
which should be
Also, as you pointed out, it then doesn’t work for some strings (works only for those really short). The problem is that when you call
update(), it saves some data into the resultingbyte[]. When you calldoFinal()on the same variable, it overwrites the data and they are lost forever. ThedoFinal()method doesn’t do all the encrypting again, it only does the remaining part!That means, that you
destinationafterupdate(), makedestination2fordoFinal()and then both decrypt the same way –update()destinationanddoFinal()destination2destinationanddestination2, concatenate them (here’s how, e.g.) into a singlecompleteDestinationarray and do decryptingdoFinal()on that.If you would like to see the code for all the above, just say a word.