我用Dart的加密包加密一个字符串。我加密的代码如下。
String encrypt(String kelime) {
final key = Key.fromUtf8('H4WtkvK4qyehIe2kjQfH7we1xIHFK67e'); //32 length
final iv = IV.fromUtf8('HgNRbGHbDSz9T0CC');
final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
final encrypted = encrypter.encrypt(kelime, iv: iv);
return encrypted.base64;
}然后我用相同的包对加密的数据进行解码,得到的错误输入数据长度必须是密码块大小的倍数。经过一些研究,我了解到加密包在破解AES加密算法时有困难。我了解到加密的单词可以用Pointy城堡包解密。代码如下
String decryptt(String cipher) {
final key = Key.fromUtf8('H4WtkvK4qyehIe2kjQfH7we1xIHFK67e');
final iv = IV.fromUtf8('HgNRbGHbDSz9T0CC');
final encryptedText = Encrypted.fromUtf8(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);
}当我解密用切入点加密的数据时,我会得到这样的输出。
có原Ò,có原,Ò,Ò,r,r.9
我加密的词是
Hello
我用的一包飞镖
发布于 2021-04-24 16:42:30
在用AES/CTR和加密包解密时,我无法重现这个问题。
下列具有加密和相关解密的代码在我的计算机上运行良好:
final key = enc.Key.fromUtf8('H4WtkvK4qyehIe2kjQfH7we1xIHFK67e'); //32 length
final iv = enc.IV.fromUtf8('HgNRbGHbDSz9T0CC');
// Encryption
String kelime = 'The quick brown fox jumps over the lazy dog';
final encrypter = enc.Encrypter(enc.AES(key, mode: enc.AESMode.ctr, padding: null));
final encrypted = encrypter.encrypt(kelime, iv: iv);
final ciphertext = encrypted.base64;
print(ciphertext);
// Decryption
final decrypter = enc.Encrypter(enc.AES(key, mode: enc.AESMode.ctr, padding: null));
final decrypted = decrypter.decryptBytes(enc.Encrypted.fromBase64(ciphertext), iv: iv);
final decryptedData = utf8.decode(decrypted);
print(decryptedData);CTR是一种不需要填充的流加密模式。与大多数库不同,加密包不会隐式禁用CTR模式的填充,因此必须显式(padding: null)。否则,当与其他库(如PointyCastle)解密时,填充字节通常不会被删除。
请注意,在发布的代码中,您使用的是CBC模式加密,而不是CTR模式。也许你用来加密和解密的模式不匹配。
顺便说一句,静态IV通常是不安全的,特别是对于CTR (但为了测试目的可以),s. 这里。
如果将上述代码中的解密块替换为用PointyCastle解密,则解密也有效。
// Decryption
final encryptedText = enc.Encrypted.fromBase64(ciphertext);
final ctr = pc.CTRStreamCipher(pc.AESFastEngine())..init(false, pc.ParametersWithIV(pc.KeyParameter(key.bytes), iv.bytes));
final decrypted = ctr.process(encryptedText.bytes);
final decryptedData = utf8.decode(decrypted);
print(decryptedData);https://stackoverflow.com/questions/67244624
复制相似问题