HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpModerate

AES encryption in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
encryptionphpaes

Problem

PHP doesn't have a built-in functions for AES (specifically, AES-128) encoding/decoding, so I've had to implement my own, and this is what I have come up to (of course, taken from different many sources, mostly not coded by me).

My question is, are these correct? Not the code itself, but what they do. The correctness of the algorithm. I have tested them, and they apparently do work. But there might be a subtle error that I'm overlooking...

Encoding algorithm:

function aes128_encode($data, $mode)
{
        switch ($mode) {
        case "ECB":
        case "CBC":
            if ($mode === "ECB") {
                $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
            } else {
                $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
            }

            $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_RAND);
            $key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher));

            if (mcrypt_generic_init($cipher, $key, $iv) != 1) {
                $cipherData = mcrypt_generic($cipher, $data);

                mcrypt_generic_deinit($cipher);
                mcrypt_module_close($cipher);

                if ($mode === "ECB") {
                    $sanitizedCipherData = trim(base64_encode($cipherData)); 
                } else {
                    $sanitizedCipherData = trim(base64_encode($iv)."_".base64_encode($cipherData));
                }

                return $sanitizedCipherData;
            } else {
                return false;
            }
            break;

        default:
            return false;
            break;
        }
    }


Decoding algorithm:

```
function aes128_decode($data, $mode)
{
switch ($mode) {
case "ECB":
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher));

// Fake iv to call mcrypt_generic_init
$iv

Solution

Implementing AES alone is very risky, mainly because it is very easy to make a mistake. I strongly recommend you use phpseclib for this.

Also you should not use ECB mode unless you are encrypting only 1 block.

Context

StackExchange Code Review Q#5432, answer score: 10

Revisions (0)

No revisions yet.