0

I want to use AES encryption in order to create a secure email. I followed the advice of this post: https://stackoverflow.com/a/12339418/787794

So far all works well, until I try to send the initialization vector (IV) along with the cipher text over email. I think the IV gets corrupted somehow in the email format, and that creates problems when I go to decrypt.

Community
  • 1
  • 1
Doug
  • 5,116
  • 10
  • 33
  • 42

2 Answers2

1

Normally the IV data is prefixed to the ciphertext. For CBC it is always the same size as the block size, so if the other party doesn't have mcrypt_get_iv_size it should not pose a problem.

Note that to create a secure email more is needed than just encryption; at least add a HMAC over the IV and ciphertext. Calling srand should be avoided as the random number generator should already be seeded. Furthermore that example is not using AES, use MCRYPT_RIJNDAEL_128 instead. Just a hash over a password is not a good Password Based Key Derivation Function.

For binary data you may want to take a look at the SMIME or PGP specifications. If you want to store everything in the message body, you need to at least base64 encode the IV, ciphertext and hopefully the authentication tag created using HMAC.


For an example that uses AES & CBC + prefixes the IV, just take a look at the mcrypt_encrypt sample code that I rewrote.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Looks like you have a lot of corrections. Would love to see your final code. Or a pointer to some good example. – Doug Dec 17 '14 at 16:49
  • @Doug Added pointer to my `mcrypt_encrypt` sample code (it got put in later by one of the PHP maintainers as the original code was insecure in many ways), which I pointed out in a bug report. – Maarten Bodewes Dec 17 '14 at 19:23
  • I have a couple of quick questions about the sample. Can I contact you somehow. I think these could potentially lead to improvements in the sample. Thanks for considering, Doug – Doug Dec 18 '14 at 05:35
  • You can post them here. Sorry, was out of the country doing some standardization work. – Maarten Bodewes Dec 20 '14 at 20:28
  • My questions are embedded in the code with ??? preceding them. Any help would be much appreciated. http://pastebin.com/5wsYJ8Gv – Doug Dec 23 '14 at 10:45
  • **1** 64 * 4 = 256 bits (/8=32 bytes) - I presume a miscalculation on your part **2** the 128 in MCRYPT_RIJNDAEL_128 is the block size, not the key size, the 256 in AES-256 is however the key size **3** zero padding: adding 0..15 bytes of value `"\0"` until the plaintext is x * 16 bytes or x blocks; `"\0"` byte values are stripped off during decryption, so if your plaintext ends with `"\0"` then it is stripped off too – Maarten Bodewes Dec 23 '14 at 11:52
0

Use base64_encode() and base64_decode. This will allow the IV to be sent over simpler text formats like email, HTML, whatever.

Doug
  • 5,116
  • 10
  • 33
  • 42