java - java中是否有以下Aes加密函数的Dart等价物
问题描述
我已经设置了一个服务器,它通过下面提到的 java 函数侦听加密的字节数组。早些时候我使用java(android)来构建我的应用程序,因此使用相同的java函数很容易,但我无法弄清楚该函数的dart等效(颤振)是什么,它将字符串作为输入并返回AES加密字节数组作为输出,我可以将其写入 tcp 套接字。
此外,我非常感谢帮助了解如何将生成的字节数组写入服务器,然后读取类似的响应并通过 dart (flutter) 对其进行解密
我已经成功地编写了简单的字符串并通过 dart 接收简单的字符串作为输入和输出到 tcp 服务器,但不能对加密的字节数组做同样的事情。在java中,我使用 DataOutputStream 像这样将响应发送到服务器
DataOutputStream dOut = newDataOutputStream(socket.getOutputStream());
byte[] s2 = Encrypt3.encrypt2(myString);
dOut.writeInt(s2.length); // write length of the message
dOut.write(s2);
这是我用于aes加密的java函数
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Encrypt3 {
public static String key = "mykey";
public static byte[] encrypt2(String text ){
String encrypt ="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
return encrypted ;
}catch(Exception e){
System.out.println(e);
}
return null ;
}
public static String decrypt2(byte[] encrypted2){
String decrypt ="";
try{
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decrypt = new String(cipher.doFinal(encrypted2));
}catch(Exception e){
System.out.println(e);
}
return decrypt ;
}
}
我希望在提供字符串作为输入时在 dart 中生成等效的字节数组,然后将字节数组写入 tcp 服务器。
先感谢您
解决方案
您配置 Java 密码的方式默认为电子密码本 (ECB) 模式,不应该在真正的密码系统中使用。您还依赖于默认填充 - PKCS5。
使用该pointycastle
包,并导入以下内容:
import 'package:pointycastle/api.dart';
import 'package:pointycastle/block/aes_fast.dart';
import 'package:pointycastle/paddings/pkcs7.dart';
import 'package:pointycastle/padded_block_cipher/padded_block_cipher_impl.dart';
import 'package:pointycastle/block/modes/ecb.dart';
Dart 中的近似等价物是:
List<int> encrypt2(String text) {
// key must be 16 or 32 bytes - not sure how "mykey" could work
// key should really be binary, not a String! Better to use a KDF.
Uint8List key = Uint8List.fromList(
utf8.encode('0123456789abcdef'),
);
PaddedBlockCipher cipher = PaddedBlockCipherImpl(
PKCS7Padding(), // Java defaults to PKCS5 which is equivalent
ECBBlockCipher(AESFastEngine()), // Very weak mode - don't use this in the real world
);
cipher.init(
true,
PaddedBlockCipherParameters<CipherParameters, CipherParameters>(
KeyParameter(key),
null,
),
);
return cipher.process(utf8.encode(text)); // this isn't the same as .toBytes, except for ASCII
}
推荐阅读
- ios - 使用全局变量和常量是一种好习惯吗?(斯威夫特 5)
- android - 华为推送套件:令牌在华为手机上返回为空
- docker - 无法通过 docker 中的 ssh 连接到 Corda 节点
- jquery - 如何用正确的 jquery 3.x 代码替换 thise .live 函数代码?
- javascript - 离子:在离子菜单中隐藏背景
- clickhouse - Clickhouse 中的 AggregateFunction 与 simpleAggregateFunction
- python - (又一个)'ImportError:没有名为 my_module 的模块'
- sql - 我可以创建一个 SQL 数据库架构,而不是使用主键,而是为每个场景创建新表吗?它的缺点是什么?
- javascript - 如何在 d3.js 工具提示中换行?
- flutter - Flutter 中的 Algolia 手动自动完成