Hey everyone:
I'm trying to use the JCE to encrypt and then decrypt some text.
Ultimately I want to be able to store an encrypted password in a file
and retrieve it later to be used in an application. The problem I'm
having is that the values I'm getting back are not the same values. ie,
the decrypted byte array is not the same as the original byte array.
Here is my code:
code:
public class Test {
public static void main(String[] args) {
try{
String keyStr= "This is a test key to use for testing" ;
DESKeySpec keySpec = new DESKeySpec(keyStr.getBytes());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("DES");
SecretKey sKey = keyFac.generateSecret(keySpec);
Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");
c1.init(Cipher.ENCRYPT_MODE, sKey);
byte[] bPW = "testPassword".getBytes();
byte[] ciphertext = c1.doFinal(bPW);
System.out.println("secret key: " + sKey.getEncoded());
System.out.println("cipher text: " + ciphertext);
c1.init(Cipher.DECRYPT_MODE, sKey);
System.out.println("original text: " + bPW);
byte[] decipheredtext = c1.doFinal(ciphertext);
System.out.println("plain text: " + decipheredtext);
} catch (Exception e){
System.out.println(e.getMessage());
}
}
}
I am an absolute newbie as far as encryption so I may be completely off
in my implementation and/or making a really stupid mistake, so if anyone
can help I'd appreciate it. My next question would be can I store the
key in a file and would it be secure? Meaning, I've got all these
encrypted passwords in a file now I need to get them and decrypt them so
I'll need to get the key from somewhere. Or would it be better to
generate the key from a string in the code each time, then the key isn't
available but the original string would be if they decompile the code.
Any suggestions, tips, pointers, or shoves in the right direction would
be great.
Thanks
Dave
JK - 19 Nov 2003 15:49 GMT
You are printing the objects rather than their values. The cipher should
construct a new byte array containing the same bytes (a different
object with the same content).
Additionally, you should specify an encdoing (how to convert characters
into bytes), e.g. UTF-8. Try something like
...
byte[] bPW = "testPassword".getBytes("UTF-8");
...
System.out.println("original text:" + new String(bPW, "UTF-8");
...
System.out.println("decrypted text:" + new String(decipheredtext, "UTF-8"));
Hope it works now
Jan.
> Hey everyone:
>
[quoted text clipped - 53 lines]
>
> Dave
Dave Vick - 19 Nov 2003 16:02 GMT
Jan:
That was perfect, it works great now. Thanks for your help, I was fairly
sure it was something simple. Thanks also for the encoding tip too.
Dave