You need to have an IV that is not predictable for a given message. Hard-coding the IV makes it predictable. So you need to devise some way to pass the IV with the ciphertext. The IV doesn't have to be kept secret though, unlike the key.
A block cipher operates on a block of plaintext of a fixed size. If you don't have enough plaintext to input, it has to be padded in such a way that a recipient can distinguish the padding from the data. The linked example completely ignores this, and that is an error. If a CipherOutputStream
is used, a partial final block will be truncated silently from the ciphertext. If the Cipher
object is used directly, an partial block will cause the doFinal
method to raise an exception. Instead, use something like PKCS5Padding.
A proper Java example would be something like this:
SecretKey secret = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters param = cipher.getParameters();
/* In addition to ciphertext in "cos", recipient needs IV. */
byte[] iv = param.getParameterSpec(IvParameterSpec.class).getIV();
CipherOutputStream cos = new CipherOutputStream(output, cipher);
byte[] buf = new byte[2048];
while (true) {
int n = input.read(buf, 0, buf.length);
if (n < 0)
break;
cos.write(buf, 0, n);
}
cos.flush();
Where is the JSP receiving plaintext to be encrypted? How do you want the JSP to format its output (including the IV)?