Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about a JCE tutorial code snippet

 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();

System.out.println
("string has been encrypted");

System.out.println
("we are now decrypting");

IvParameterSpec spec =
new IvParameterSpec(initvector);

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

System.out.println(s2);

}
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic