This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 41036
Passing the key between machines is outside the scope of JCE. You can use any data transfer method you can think of.

Ping & DNS - my free Android networking tools app
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
Don't get me started about those stupid light bulbs.
subject: question about a JCE tutorial code snippet
Similar Threads
How to encrypt & decrypt Random DES key with DES?
Question on similar & identical of Objects
Java Security related question- Please Help
Algorithm DES not available