AES encryption with Java
The following code is for encrypting short messages (it acts on byte arrays and not streams so the whole message needs to fit in memory). It creates a random Initialisation Vector (IV) for each message which is prepended to the start of the encrypted stream.
It is safe to leave your IV in the open so long as your key is kept secure (think salt on a password hash). This means that the same key can be used throughout without the same data being encrypted in the same way twice. This does add 16 bytes to the length of each message so if your throughput is high volume but small messages, that could be a factor. This implementation also uses GCM for message authentication though so that is an additional 16 bytes again. This means your encrypted message will be 32 bytes (or 2x 128 bits) longer than the input. The string used below in the test is 152 bytes originally but 184 after GCM and the IV payload.
Disclaimer: I am not a cryptography guru nor do I mean to imply that the following code is suitable for use without more than a passing understanding of the concepts therein.
Firstly the test. This test takes a string and encrypts it twice with the same key (the class AesUniqueIv will generate a key if none is provided which is made available by the getKey() method). It should be fairly obvious but the assertions are that the same message can be encrypted twice and decrypted twice and that the two encrypted messages are not the same. It also asserts that the length of the encrypted message is indeed 32 bytes longer as stated earlier.