Wednesday, June 25, 2014

The Problem With Dynamically Type Programming Languages

Consider the following code in Java:
byte[] key = generateAES();
byte[] encrypted = encryptAES(key, "Hello World");
String b64Key = b64encode(key);
String b64enc = b64encode(encrypted);

Now consider the same code in PHP:

$key = generateAES();
$key = b64encode(key);
$encrypted = encryptAES($key, "Hello World");
$encrypted = b64encode(encrypted)
This is exactly what bit me in the A$$ this week. I kept getting the wrong results and since this was a port from Java to PHP, I kept expecting it to be an interoperability problem.
It's really easy and tempting to reuse the old variable key (which I did) and get the order wrong (which I did). Because you would use the base 64 key when trying to debug the problem, everything would appear to be correct, but now the PHP code is using the base 64 of the key instead of the key itself.
This wouldn't happen in Java or any other statically typed language.