views:

70

answers:

2

I am reading about encryption and having a lot of difficulty understanding these 3 Java statements of an encryption program.

    cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    encrypted = cipher.doFinal(str.getBytes())

Can somebody help?

+2  A: 

In simpler terms,

  • create a new Encrypting Device using the AES algorithm;
  • make it ready
  • get the bytes of the string str and encrypt them; return the result into the encrypted object, whatever that is.

what exactly did you not understand?

lorenzog
+1  A: 
cipher = Cipher.getInstance("AES");

Get a Cipher object that can encrypt/decrypt using the AES algorithm. Java's cryptography code is a bit weird - instead of directly creating objects, you generally use a getInstance call with a String argument. (Note that "cipher" means "way of encrypting something".)

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

Tell the cipher that you would like to encrypt something (Cipher.ENCRYPT_MODE), and give it the encryption key skeyspec.

encrypted = cipher.doFinal(str.getBytes())

The way ciphers work is that you feed them chunks of byte data using the update method, which causes the cipher to accumulate the encrypted data within itself. For the final block of data, doFinal is used, which tells the cipher that the encryption process is done. A different method is needed because the cipher often has to pad out the data returned to a particular length. doFinal then returns the final bit of encrypted information.

However, if there is a single readily available chunk of data, you can just call doFinal and it will give you all the encrypted bytes at once. But this explains why the method is called doFinal, not say, "process".

So in summary, the code above creates an AES encryption engine, gives it an encryption key, then uses it to encrypt the String str into the byte array encrypted.

Note that cryptography is very tricky business and very easy to get wrong. There's all kinds of things you need warning about that I haven't touched on because my wrists hurt now. So I would heavily recommend you get a copy of Beginning Cryptography with Java - it's where I learned to understand this stuff.

Zarkonnen