File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Security and the fly likes question about a JCE tutorial code snippet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Security
Bookmark "question about a JCE tutorial code snippet" Watch "question about a JCE tutorial code snippet" New topic

question about a JCE tutorial code snippet

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
try {
KeyGenerator kg = KeyGenerator.getInstance("DES");
// DES= Data Encryption Standard
Key key = kg.generateKey();
Cipher ci = Cipher.getInstance("DES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, key);

String s ="we are learning Java";
byte[] array1 = s.getBytes();
byte[] array2 = ci.doFinal(array1);
byte[] initvector = ci.getIV();

("string has been encrypted");

("we are now decrypting");

IvParameterSpec spec =
new IvParameterSpec(initvector);

(Cipher.DECRYPT_MODE, key, spec);
byte[] array3 = ci.doFinal(array2);
String s2 = new String(array3);


catch(Exception e1)

{ System.out.println(""+e1);}


Above is a short symmetric encrypt/decrypt code. If I have to encrypt the string in one machine and decrypt it on another machine, and want to follow this code snippet, I certainly don't want to use

byte[] initvector = ci.getIV();

because I don't want to pass this "initvector" to the other machine. How can I let two machines use a agreed key or "password" to accomplish the encrypt and decrypt ? any snippet to share ? This snippet isn't a good example I guess because it generates a key on one machine, but how do I pass to another ?

I am new to JCE world, but my guess is two machines should use a common "password" and algorithm to retrieve the key (or maybe the password itself can be the key), and then one side can encrypt using this key, and the other side can decrypt using the same key.. Any snippet matching this logic ? maybe I am totally wrong.

Thanks !
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
Passing the key between machines is outside the scope of JCE. You can use any data transfer method you can think of.
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
Have you looked into PBE (Password Based Encryption)? , this might help , where the password would help to create the keys and anyone knowing the password can decrypt the cipher.

Rahul Bhattacharjee
LinkedIn - Blog
I agree. Here's the link:
subject: question about a JCE tutorial code snippet
It's not a secret anymore!