Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Implement AES-CTR encryption

843811Oct 23 2009 — edited Oct 25 2009
Hi
I'm new to java cryptography. I am trying to do a very basic encryption with Counter mode but dont know how to start.
The encryptions i have done so far use the simple : Cipher.getInstance("AES/CBC/PKCS5Padding");
from what i understand, a counter needs to be used in CTR mode that somehow gets encrypted and XOR'ed with the plaintext?

For e.g. if i had :

String plaintext = "I am Sam !";
String mykey = "Have you failed?";
String myiv = "This is your IV!";

int nonce=0;
//define a key

SecretKeySpec keyspec = new SecretKeySpec(mykey.getBytes(), "AES");

//define the IV
IvParameterSpec ivspec = new IvParameterSpec(myiv.getBytes());

//set the cipher to desired operations
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

//Encrypt
byte[] encrypted = cipher.doFinal(plaintext.getBytes());

//Encode
String encoded = new sun.misc.BASE64Encoder().encode(encrypted);
System.out.println(encoded);

//Decode
byte[] decoded = new sun.misc.BASE64Decoder().decodeBuffer(encoded);

//get algorithm parameters for decrypting
AlgorithmParameters aparam = cipher.getParameters();
System.out.println("Params" + aparam.toString());

//Decrypt using the same key
cipher.init(Cipher.DECRYPT_MODE, keyspec, aparam);
byte[] decrypted = cipher.doFinal(decoded);
System.out.println(new String(decrypted));

So if nonce was the counter, how would it be used. i suppose it could be encrypted just as the plaintext is encrypted in the above example. What then? Do i use the XOR() function (that only xor's two bytes though).

I have no idea where to begin.
I'd appreciate any help or direction.

Thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 22 2009
Added on Oct 23 2009
4 comments
1,223 views