在AES CTR模式下,输入数据必须是密码块大小的倍数 [英] Input data must be multiple of cipher block size in AES CTR mode
问题描述
当我使用Dart的加密包使用AES CTR模式解密某些内容时,会出现此异常:
I get this exception when I use Dart's encrypt package to decrypt something using AES CTR mode:
E/flutter (19095): Invalid argument(s): Input data length must be a multiple of cipher's block size
E/flutter (19095): #0 PaddedBlockCipherImpl.process (package:pointycastle/padded_block_cipher/padded_block_cipher_impl.dart:55:9)
E/flutter (19095): #1 AES.decrypt (package:encrypt/src/algorithms/aes.dart:38:20)
这是我的代码:
final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.ctr));
final decrypted = encrypter.decrypt(encrypt.Encrypted.fromBase16(cipher), iv: iv);
密码
是长度为10的十六进制字符串。我以为AES CTR模式不需要任何填充。如果确实需要填充,我应该用什么填充?我试过了:
cipher
is hexadecimal string of length 10. I thought AES CTR mode did not require any padding. If it does require padding, what do I pad with? I tried this:
final decrypted = encrypter.decrypt(encrypt.Encrypted.fromBase16(cipher.padRight(16, null)), iv: iv);
但我得到以下例外:
E/flutter (19095): FormatException: Invalid radix-16 number (at character 1)
E/flutter (19095): nu
E/flutter (19095): ^
使用'0'
作为填充会导致我描述的第一个异常。
Using '0'
as the padding results in the first exception I describe.
推荐答案
这是Dart加密程序包中的问题。如果不是块大小的倍数,它将无法处理使用AES CTR模式加密的内容。该程序包是 Pointy Castle 的包装,我可以成功地使用它解密使用AES加密的字符串点击率模式。代码如下:
This is a problem in Dart's encrypt package. It cannot handle something encrypted using AES CTR mode if it isn't a multiple of the block size. This package is wrapper for Pointy Castle, which I was able to use successfully to decrypt a string encrypted using AES CTR mode. Here's the code:
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:pointycastle/export.dart' as pc;
String decrypt(String cipher, Uint8List key, Uint8List iv) {
final encryptedText = encrypt.Encrypted.fromBase16(cipher);
final ctr = pc.CTRStreamCipher(pc.AESFastEngine())
..init(false, pc.ParametersWithIV(pc.KeyParameter(key.bytes), iv.bytes));
Uint8List decrypted = ctr.process(encryptedText.bytes);
print(String.fromCharCodes(decrypted));
return String.fromCharCodes(decrypted);
}
密码
是十六进制字符串。加密的程序包仍然有用,因为它提供了将十六进制字符串转换为Uint8List的实用程序
cipher
is a hexadecimal string. encrypt's package is still useful because it provides utilities for converting a hexadecimal string to a Uint8List
这篇关于在AES CTR模式下,输入数据必须是密码块大小的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!