Java – CTR mode uses initial vector (IV)

As far as I know, CTR mode does not use initial vectors

Other block cipher modes, such as CBC, XOR plaintext using initial vectors before encryption

So this is my problem I use the following code in Java (using the bouncycastle Library):

Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding","BC");

cipher.init(Cipher.ENCRYPT_MODE,key);

byte[] result = cipher.doFinal("Some plaintext");

Each different call of the above code uses the same key to give different output! But in doing so:

byte[] IV = new byte[]{0,0};

Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding",key,IV);

byte[] result = cipher.doFinal("Some plaintext");

I get the same result in every call of the above code But why? I mean, CTR doesn't need IV, so why do I get different results when I don't give IV in each call, and it returns the same result when I give IV? If I always use the above IV (all zeros) when using the click through rate, will it be safe?

Any idea will be very useful thank you

Solution

The most important warning of CTR mode is that you will never reuse the same counter value with the same key If you do, you have effectively abandoned your plaintext

In order to solve this problem, in some practical implementations of CTR mode, the block to be passed to the block cipher is divided into two parts, marked as IV and counter (instead of calling the whole event counter) IV is randomly generated, and the counter starts from 0

This allows you to start the "counter" section at zero in multiple messages, as long as you never reuse the "IV" section

Please note that this is just a label convention Mathematically, it is the same as calling the whole thing "counter", and starts the counter at a random multiple of an integer in each message

I'm not sure how the bouncy castle implementation works - it may let you set the entire initial block, counters and all with the IV value If you don't provide an IV that obviously produces a reasonable IV for you, that's why you get different outputs with the same input Most importantly, it's good, and it's exactly what you want - providing all zeros is bad, not what you want

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>