using randomly generated IV for encryption

J

jimgardener

hi
in a text book by David Hook, I came across creation of random IV for
encryption.It goes like this
<code snippet>
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
int blksz=cipher.getBlockSize();
byte[] ivBytes=new byte[blksz];
SecureRandom random=new SecureRandom();
random.nextBytes(ivBytes);
IvParameterSpec ivSpec=new IvParameterSpec(ivBytes);
//encryption pass
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);

</code snippet>

then the example in the book takes the iv and encrypts it into
ciphertext and then works on the message to be encoded

<code snippet>
byte[] cipherText=new byte[cipher.getOutputSize(ivBytes.length
+input.length)];
int ctLength=cipher.update(ivBytes,0,ivBytes.length,cipherText,0);
ctLength+=cipher.update(input,0,input.length,cipherText,ctLength);
ctLength+=cipher.doFinal(cipherText,ctLength);
</code snippet>

In decryption pass,the ciphertext is decrypted and then the IV is
removed from the byte array to recover the plaintext bytes.

Is this the proper way to do this?Or is there a better alternative?
thanks
jim
 
A

Arne Vajhøj

jimgardener said:
hi
in a text book by David Hook, I came across creation of random IV for
encryption.It goes like this
<code snippet>
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
int blksz=cipher.getBlockSize();
byte[] ivBytes=new byte[blksz];
SecureRandom random=new SecureRandom();
random.nextBytes(ivBytes);
IvParameterSpec ivSpec=new IvParameterSpec(ivBytes);
//encryption pass
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);

</code snippet>

then the example in the book takes the iv and encrypts it into
ciphertext and then works on the message to be encoded

<code snippet>
byte[] cipherText=new byte[cipher.getOutputSize(ivBytes.length
+input.length)];
int ctLength=cipher.update(ivBytes,0,ivBytes.length,cipherText,0);
ctLength+=cipher.update(input,0,input.length,cipherText,ctLength);
ctLength+=cipher.doFinal(cipherText,ctLength);
</code snippet>

In decryption pass,the ciphertext is decrypted and then the IV is
removed from the byte array to recover the plaintext bytes.

Is this the proper way to do this?

No.

The other end needs to know iv to decrypt.

So there are absolutely no point in having iv in the message.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top