2

我是颤振开发的新手,我正在尝试使用颤振中的公钥在服务器上发送加密数据。我有 .cer 证书,并且我有 RSA 公钥。现在在 Java 中,我使用 RSA 公钥加密纯文本,我已经成功地做到了这一点。我怎么能在颤动中做到这一点?

public String encrypt(String string, final X509Certificate x509Certificate) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
    Cipher a = Cipher.getInstance("RSA");
    final KeyGenerator instance;
    (instance = KeyGenerator.getInstance("AES")).init(256);
    byte[] b = instance.generateKey().getEncoded();
    System.out.println("print encoded key"+b);
    printUnsignedBytes(b);
    aesKey = b;
    new SecretKeySpec(b, "AES");
    a.init(1, x509Certificate.getPublicKey());
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final CipherOutputStream cipherOutputStream;
    (cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, a)).write(b);
    cipherOutputStream.close();
    byte[] c = byteArrayOutputStream.toByteArray();
    final byte[] array = new byte[16];
    new SecureRandom().nextBytes(array);
    final Cipher instance2;
    (instance2 = Cipher.getInstance("AES/CBC/NOPADDING")).init(1, new SecretKeySpec(b, "AES"),
            new IvParameterSpec(array));
    byte[] bytes = s.getBytes();
    int remainder = 16 - (bytes.length % 16);
    byte[] remainderFilledWithSpaces = new byte[remainder];
    for (int i = 0; i < remainderFilledWithSpaces.length; i++) {
        remainderFilledWithSpaces[i] = " ".getBytes()[0];
    }
    int totalLength = bytes.length + remainder;
    ByteBuffer bb = ByteBuffer.allocate(totalLength);
    bb.put(bytes);
    bb.put(remainderFilledWithSpaces);
    bb.position(0);
    byte[] blockToEncrypt = new byte[16];
    ByteBuffer encrypted = ByteBuffer.allocate(totalLength);
    while (bb.hasRemaining()) {
        bb.get(blockToEncrypt);
        byte[] update = instance2.update(blockToEncrypt);
        encrypted.put(update);
    }
    instance2.doFinal();
    final ByteArrayOutputStream byteArrayOutputStream2 = new ByteArrayOutputStream();
    final byte[] array2;
    (array2 = new byte[4])[0] = 0;
    array2[1] = 1;
    array2[3] = (array2[2] = 0);
    byteArrayOutputStream2.write(array2, 0, 4);
    array2[0] = 16;
    array2[1] = 0;
    array2[3] = (array2[2] = 0);
    byteArrayOutputStream2.write(array2, 0, 4);
    byteArrayOutputStream2.write(c, 0, 256);
    byteArrayOutputStream2.write(array, 0, 16);
    byteArrayOutputStream2.write(encrypted.array());
    return s = new String(Base64.getMimeEncoder().encode(byteArrayOutputStream2.toByteArray()));
}

现在,我想在 Dart 中使用相同的解决方案。请帮助,非常感谢。

4

0 回答 0