Skip to content
Advertisement

how to descrypt an aes encryption from flutter in php

In my flutter app am using an encryption package called encrypt . and am able to encrypt my chat messages using this code

import 'package:encrypt/encrypt.dart';

class TextEncrypt {
  final _iv = IV.fromLength(16);
  final key = Key.fromLength(32);

  String decrypt(String text) {
    final enc = Encrypter(AES(key));
    final encrypted = Encrypted.fromBase64(text);
    return enc.decrypt(encrypted, iv: this._iv);
  }

  String encrypt(String text) {
    final enc = Encrypter(AES(key));
    return enc.encrypt(text, iv: _iv).base64;
  }
}

but the problem is that the encrypted part will be stored in mysql database and flutter local database (sqflite) too and when i want to build a website for the app using php mysql html css javascript. How will i be able to decrypt it back to its normal text using php or do you think that there might be a better way to encrypt it in the app and also be able to decrypt it in php aside from this method

Please if you don’t understand what am saying and need more explanation please tell me

Advertisement

Answer

This is the sample which can help you:

Flutter code:

import 'package:encrypt/encrypt.dart';

String decrypt(String encrypted) {
  final key = Key.fromUtf8("1245714587458888"); //hardcode combination of 16 character
  final iv = IV.fromUtf8("e16ce888a20dadb8"); //hardcode combination of 16 character

  final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
  Encrypted enBase64 = Encrypted.from64(encrypted);
  final decrypted = encrypter.decrypt(enBase64, iv: iv);
  return decrypted;
}

String encrypt(String value) {
  final key = Key.fromUtf8("1245714587458745"); //hardcode 
  final iv = IV.fromUtf8("e16ce888a20dadb8"); //hardcode 

  final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
  final encrypted = encrypter.encrypt(value, iv: iv);

  return encrypted.base64;
}

And the PHP code: (Enable openssl.dll Extension)

function encrypt($value){
    $key = '1245714587458888'; //combination of 16 character
    $iv = 'e16ce888a20dadb8'; //combination of 16 character
    $method = 'aes-128-cbc';
    $encryptedString = openssl_encrypt($value, $method,
        $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($encryptedString);
}

function decrypt($value){
    $key = '1245714587458888'; //combination of 16 character
    $iv = 'e16ce888a20dadb8'; //combination of 16 character
    $method = 'aes-128-cbc';
    $base64 = base64_decode($value);
    $decryptedString = openssl_decrypt($base64, $method,
        $key, OPENSSL_RAW_DATA, $iv);
    return $decryptedString;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement