noprotocol / php-mysql-aes-crypt

Encrypt/decrypt data in PHP to a format compatible with MySQL AES_ENCRYPT & AES_DECRYPT functions.
MIT License
23 stars 9 forks source link

Be able to switch between 128-bit and 256-bit #8

Closed ghost closed 6 years ago

ghost commented 6 years ago

Hi!

As it is right now, the class will only encrypt in 128-bit AES. In order to change it to 256-bit, you must change AES-128-ECB on the rows 39, 45, and 65 to AES-256-ECB. When the class is being updated, you must change it manually once more.

To prevent this, add a extra variable to the class, like this:

    public function encrypt($data, $bit)
    {
        $chiperIvLength = openssl_cipher_iv_length('AES-'.$bit.'-ECB');
        $iv = openssl_random_pseudo_bytes($chiperIvLength);
        $padValue = 16 - (strlen($data) % 16);
        return openssl_encrypt(
            str_pad($data, (16 * (floor(strlen($data) / 16) + 1)), chr($padValue)),
            'AES-'.$bit.'-ECB',
            $this->key,
            OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
            $iv
        );
    }
    public function decrypt($data, $bit)
    {
        $data = openssl_decrypt(
            $data,
            'AES-'.$bit.'-ECB',
            $this->key,
            OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
        );

Then use $crypter->decrypt($string, '256'); to encrypt the string with 256-bit AES.

I have no idea if this will work, but you get the idea. So, please add this!

annejan commented 6 years ago

I have a different (nicer) idea to solve this, will get back on this tomorrow :-)

ghost commented 6 years ago

Sweet! How's it going with the idea? :)

verschuur commented 6 years ago

Nice one AJ 👌🏼

annejan commented 6 years ago

You can now optionally choose a cypher in the constructor, eg:

<?php
$crypter = new Crypter('mykeystring', 'AES-256-ECB');
ghost commented 6 years ago

Really nice!