How should I generate an initialization vector?

后端 未结 4 422
离开以前
离开以前 2020-12-28 08:50

I\'m sure there\'s not one answer to this question, but just trying to find out a general approach.

Using Java 1.4.2, I need to generate a key and IV for use in a sy

4条回答
  •  北海茫月
    2020-12-28 09:07

    It depends on the mode in which you are using your cipher. If you are using CBC, bytes from a SecureRandom are the easiest, and probably the most secure…as long as your RNG is good.

    Most Java providers will generate the required parameters automatically, but in order for you to figure out what was chosen, you need to understand the cipher and mode. For example, if you are using a mode that requires an IV, you'd do something like this:

    cipher.init(Cipher.ENCRYPT_MODE, secret);
    IvParameterSpec spec = 
       cipher.getParameters().getParameterSpec(IvParameterSpec.class);
    byte[] iv = spec.getIV();
    

    This allows the provider to choose a suitable method for generating the IV itself. But if you were to use the same method on cipher using ECB mode, it would fail.

    Using a counter mode obviously requires great care to avoid re-use of the counter.

提交回复
热议问题