java中是否存在以下Aes加密函数的Dart等效项

时间:2019-04-25 21:25:08

标签: java flutter serversocket tcpsocket

我已经设置了一个服务器,该服务器正在通过下面提到的java函数监听加密的字节数组。早些时候我使用Java(android)来构建我的应用程序,因此使用相同的Java函数很容易,但是我无法弄清楚该函数的dart等效项(flutter)是什么,该函数将字符串作为输入并返回AES加密字节数组作为输出,我可以将其写入tcp套接字。

我也非常感谢帮助我们了解如何将生成的字节数组写入服务器,然后读取类似的响应并通过dart(颤振)对其解密

我已经成功地编写了简单的字符串,并通过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服务器。

提前谢谢

1 个答案:

答案 0 :(得分:1)

配置Java密码的方式默认为电子密码簿(ECB)模式,该模式不应在实际的密码系统中使用。您还依赖默认填充PKCS5。

使用pointcastle软件包,并进行以下导入:

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
}