0

I am trying to send an encrypted text with each HttpResponse and when I get the next HttpRequest with the encrypted text, I decrypt it and do some stuff :) with it.

I am curious about the best practices surrounding the storage/retrievel of the keys and ivSpec's (or nonce's) in general, but specifically looking at the code posted by @sherif based on @VoidPointer 's suggestions in How to encrypt String in Java,

a) Do we have to initialize ivSpec with random bytes for each string that I want to encrypt?

b) If so, do we store the generated ivSpec in some db and look it up when I need to decrypt using that?

c) If so, how do we look it up? When an encrypted string needs to be decrypted how do we pick the correct ivSpec from db?

d) One suggestion is to send ivParameter along with the encrypted string! itself (which is probably what is happening with @sherif 's implementation!). If we chose to do so, how can I modify the class provided by @sherif to decrypt and separate the iv parameter and encrypted string instead of providing the iv parameter while initializing decrypt cipher?

Community
  • 1
  • 1
user2023507
  • 1,153
  • 12
  • 23

1 Answers1

0

A. If you do not change the vector, each time you encrypt the same string, you get the same encrypted result. By changing the IV each time, you make it so that every single encrypted output looks different (even if it's the same input). Think of it as a the "salt" you use when you are hashing a password.

so under normal circumstances it would be desirable to use a random iv.

B&C. You need to look the IV up, yes. But storing it into a DB isn't very useful. You already have a piece of information that you keep stored secretly: that's the password. IV is just here to increase randomness, no need to keep it, push it out with the output.

D. Sending it is the usual way to go.

One way is to concatenate it at the beginning of the ouput. (output = IV + encrypted data). Then before decrypting first split the input (IV = 32 first bytes of input) and decrypt the rest (crypt_data_to_decrpt = input after byte number 32)

Another way is to have a constant IV and a random part at the beginning: you simply use a string of NUL byte as an IV. Then you encrypt 32 bytes of pure random garbage Then you encrypt your input. (When using a good encryption method, this should always produce a different encrypted output because the beginning was different). For decryption, you use the same empty IV, then you decrypt everything. You ignore the 32bytes at the beginning. You split and only take the bytes after the 32nd. That's your decrypted output.

DrYak
  • 1,086
  • 1
  • 10
  • 15