【问题标题】:How to use AES 256 in CTR mode?如何在 CTR 模式下使用 AES 256?
【发布时间】:2013-12-27 15:51:42
【问题描述】:

当我尝试使用 AES 256、CTR 在 haxe 中加密和在 php 中解密时,我注意到如果要加密的数据超过 15 个字符,则解密结果将为空白,对此限制有什么想法吗?

我像这样加密:

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));         

在 PHP 中,我解密:

$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);
    }

那么,任何人都可以提供帮助吗? ps:如果我在haxe lib中解密,加密的数据没有限制,我会在PHP端错过什么?我在两边都使用相同的键..

【问题讨论】:

  • 先尝试在相同的编程语言和相同的系统上进行加密和解密。如果可行,请在 stack overclow 中搜索有关跨不同字符集加密和解密的讨论。
  • 它可以正常工作,即使数据长度超过 15 个字符..
  • 定义“正常”。两边都测试了吗?
  • 是的,在 PHP 上,在 haxe 上,我确实对长文本进行了加密、解密,它工作正常,但是,在 haxe 中加密,在 PHP 中解密时会出现问题
  • 先去掉padding,CTR模式不需要。此外,点击率似乎未知,请尝试“流”。

标签: php encryption aes haxe


【解决方案1】:
public static function decrypt($key, $text, $mode = "ecb", $iv = null)

$mode = "ecb" 更改为$mode = "ctr" 将解决您的直接问题。

但是,这里还有更深层次的问题:

  1. 你是using mcrypt
  2. 您正在使用unauthenticated encryption

如果您尝试加密数据,则改用libsodium 会更好。

  • 对于 PHP,您可以使用 PHP 7.2+、PHP sodium_compat。
  • 对于 HaXe,您可以使用 the HaXe bindingssodium-plus 来加密数据。

无论您使用哪种配置,您都需要参考libsodium quick reference 以确定要使用的功能(以及如何使用)。

【讨论】:

  • 问题是6岁!感谢您的回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 2018-04-15
  • 2011-09-16
相关资源
最近更新 更多