Search code examples
phpencryptionaeshaxe

How to use AES 256 in CTR mode?


As I am trying to encrypt in haxe & decrypt in php using AES 256, CTR, I've noticed that if data to be encrypted longer than 15 character, the result of decryption would be blank, any idea about this restriction?

I encrypt in haxe like:

var input:String = "abcdefghijklmno"; // limited to 15 char to be decrypted, other wise, I get blank result..
var utf8Bytes:Array<Int> = UTF8.textToBytes(input);

var aes256iv:Array<Int> = UTF8.textToBytes("1234567890123456");
        var aes256key:Array<Int> = UTF8.textToBytes("12345678901234561234567890123456");
        var aes256enc:Array<Int> = AES.encrypt(aes256key, PKCS7.pad(utf8Bytes, 16), OperationMode.CTR, aes256iv); // Encrypt in CTR mode. Needs padding.
        var aes256dec:Array<Int> = PKCS7.unpad(AES.decrypt(aes256key, aes256enc, OperationMode.CTR, aes256iv)); // Decrypt in CTR mode. Needs unpadding.

writeLine("AES-256 (CTR mode) encrypted in UTF-8: " + Base64.encode(aes256enc));
        writeLine("AES-256 (CTR mode) decrypted in UTF-8: " + UTF8.bytesToText(aes256dec));         

In PHP, I decrypt:

$aes256i = "1234567890123456";
        $aes256k = "12345678901234561234567890123456";

        //print $input;

        $aes256e = Base64::decode($input);
        //print "Base64: " . $aes256e . "<br/><br/>\n";
        $aes256d = PKCS7::unpad(AES::decrypt($aes256k, $aes256e, "ctr", $aes256i)); // Needs unpadding.
        //
        print "AES-256 (CTR mode) decrypted in UTF-8: " . $aes256d . "<br/><br/>\n";


public static function decrypt($key, $text, $mode = "ecb", $iv = null)
    {
        $size = MCRYPT_RIJNDAEL_128; // AES fixed to 128 bits
        if (isset($iv)) return mcrypt_decrypt($size, $key, $text, $mode, $iv);
        return @mcrypt_decrypt($size, $key, $text, $mode);
    }

So, any one can help? p.s: if I decrypt in haxe lib, there is no limits of data encrypted, what would I miss at PHP side? I am using the same keys both sides..


Solution

  • public static function decrypt($key, $text, $mode = "ecb", $iv = null)
    

    Changing $mode = "ecb" to $mode = "ctr" would solve your immediate problem.

    However, there are deeper problems here:

    1. You're using mcrypt.
    2. You're using unauthenticated encryption.

    If you're trying to encrypt data, you'll be better served using libsodium instead.

    Regardless of which configuration you go with, you'll want to refer to the libsodium quick reference to figure out which function to use (and how).