Plain text encryption using RSA Public Key in Dart

Viewed 410

I am new at flutter development, I am trying to use send ENCRYPTED data on server using a public key in flutter . I have .cer certificate and i have RSA public key in flutter. Now in Java I'm using for Encrypt the Plain Text using RSA public key i have done this successfully . How can i do this in flutter ?

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()));
}

Now , I want this same solution in Dart .Please help,thanks a lot.

0 Answers
Related