3

I generate randomly IV value everytime I encrypt when doing AES/CBC.

private static IvParameterSpec getRandomIvParameterSpec() {
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);
    return new IvParameterSpec(iv);
}

And I concat IV Value to cipher byte everytime I encrypt.

Is there any secure improvement if I hash (SHA-256) IV value before concat to cipher byte?

hanjoonk
  • 163
  • 1
  • 1
  • 12
  • 4
    **Don't try to roll your own security improvements.** This won't end well for the security of your application. – Makoto Jan 06 '17 at 03:07

1 Answers1

4

SHA-256 is injective. You give it the same input, it will give you the same output. It is not surjective, however. If m1 and m2 both hash to h, you cannot conclude that m1 = m2, even if you know that |m1| = |m2| (both messages are of the same length).

Therefore, applying SHA-256 (or any deterministic function) cannot increase the entropy of your data. At best, it won't decrease it. In other words: If your data is 16 purely random bytes, it won't be “more than purely random” after you hash it. And if your data was not purely random to begin with, then hashing it won't help making it random. You have to use a better entropy source in the first place.

Another problem that you didn't mention is that you currently have 16 random bytes but if you put them into your SHA-256 hash function, you'll get 32 bytes out. Which ones are you going to use? If you only use every second byte – due to injectivity – you won't get all possible bit patterns even if your input was perfectly random and the hash function was flawless. (If you did, then this would – by the pidgin hole principle – mean that the other half of the bytes would always be a function of the bytes you did chose. Only a really crappy hash function, which SHA-256 of course is not, would have such property.) If you try to be clever and combine the bytes in some “smart” way, chances are that you'll make things even worse.

So the short answer is: just don't do it. Generate as many random bytes as you need using the strongest non-deterministic entropy source you have available and use them directly.

5gon12eder
  • 21,864
  • 5
  • 40
  • 85