2

Does anyone have an idea about encrypting response from my php api and decrypting data in local using dart. I'm using flutter for my mobile application.

Thank You!

1
  • 1
    Why can't you use HTTPS? Commented Sep 8, 2018 at 2:16

4 Answers 4

6

Here is a method for encrypting/decrypting in Flutter, PHP and C# using AES-256-CBC algorithm.

AES-256 is considered quantum-safe.

Flutter:

Include the package https://pub.dev/packages/encrypt

import 'dart:convert';

import 'package:encrypt/encrypt.dart';
import 'package:crypto/crypto.dart';

class Encryption {
  static final Encryption instance = Encryption._();
  
  late IV _iv;
  late Encrypter _encrypter;

  Encryption._() {
    const mykey = 'ThisIsASecuredKey';
    const myiv = 'ThisIsASecuredBlock';
    final keyUtf8 = utf8.encode(mykey);
    final ivUtf8 = utf8.encode(myiv);
    final key = sha256.convert(keyUtf8).toString().substring(0, 32);
    final iv = sha256.convert(ivUtf8).toString().substring(0, 16);
    _iv = IV.fromUtf8(iv);

    _encrypter = Encrypter(AES(Key.fromUtf8(key), mode: AESMode.cbc));
  }

  String encrypt(String value) {
    return _encrypter.encrypt(value, iv: _iv).base64;
  }

  String decrypt(String base64value) {
    final encrypted = Encrypted.fromBase64(base64value);
    return _encrypter.decrypt(encrypted, iv: _iv);
  }
}

Usage (Singleton Class):

var encrypted = Encryption.instance.encrypt('my value to be encrypted');
var decrypted = Encryption.instance.decrypt(encrypted);

PHP:

<?php

class Encryption
{
    private string $encryptMethod = 'AES-256-CBC';
    private string $key;
    private string $iv;

    public function __construct()
    {
        $mykey = 'ThisIsASecuredKey';
        $myiv = 'ThisIsASecuredBlock';
        $this->key = substr(hash('sha256', $mykey), 0, 32);
        $this->iv = substr(hash('sha256', $myiv), 0, 16);
    }

    public function encrypt(string $value): string
    {
        return openssl_encrypt(
            $value,
            $this->encryptMethod,
            $this->key,
            0,
            $this->iv
        );
    }

    public function decrypt(string $base64Value): string
    {
        return openssl_decrypt(
            $base64Value,
            $this->encryptMethod,
            $this->key,
            0,
            $this->iv
        );
    }
}

Usage:

$encryption = new Encryption();
$encrypted = $encryption->encrypt('my value to be encrypted');
$decrypted = $encryption->decrypt($encrypted);

C#:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public class Encryption
{
    byte[] key;
    byte[] iv;

    private Encryption instance;
    public Encryption Instance
    {
        get
        {
            if (instance == null)
                instance = new Encryption();
            return instance;
        }
    }

    private Encryption()
    {
        var Key = "ThisIsASecuredKey";
        var Iv = "ThisIsASecuredBlock";

        using (var sha256 = SHA256.Create())
        {
            key = Encoding.UTF8.GetBytes(
                 ToHex(sha256.ComputeHash(Encoding.UTF8.GetBytes(Key)))
                    .Substring(0, 32)
            );
            iv = Encoding.UTF8.GetBytes(
                 ToHex(sha256.ComputeHash(Encoding.UTF8.GetBytes(Iv)))
                    .Substring(0, 16)
            );
        }
    }
    
    public string Encrypt(string input)
    {
        using (var aesManaged = new AesManaged())
        using (var ms = new MemoryStream())
        {
            using (var cs = new CryptoStream(
                ms,
                aesManaged.CreateEncryptor(key, iv),
                CryptoStreamMode.Write
            ))
            {
                var inputBytes = Encoding.UTF8.GetBytes(input);
                cs.Write(inputBytes, 0, inputBytes.Length);
            }

            return Convert.ToBase64String(ms.ToArray());
        }
    }

    public string Decrypt(string base64value)
    {
        using (var aesManaged = new AesManaged())
        using (var decryptor = aesManaged.CreateDecryptor(key, iv))
        using (var ms = new MemoryStream(Convert.FromBase64String(base64value)))
        using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
        using (var sr = new StreamReader(cs))
        {
            return sr.ReadToEnd();
        }
    }

    private string ToHex(byte[] bytes, bool upperCase = false)
    {
        var result = new StringBuilder(bytes.Length * 2);
        for (int i = 0; i < bytes.Length; i++)
            result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));
        return result.ToString();
    }
}

Usage (Singleton Class):

var encrypted = Encryption.Instance.Encrypt("my value to be encrypted");
var decrypted = Encryption.Instance.Decrypt(encrypted);
Sign up to request clarification or add additional context in comments.

5 Comments

i am getting this error The class 'Encryption' doesn't have an unnamed constructor. when calling Encryption instance in flutter. Here is how i have called it Encryption().encrypt("value");
i am using php 7, i am not experiencing any issue in my php side i was asking for the flutter/dart part
@EmmanuelNjorodongo I have added usage examples to the answer
for php 7 just declare the variables like private $key; instead of private string $key;
@EmmanuelNjorodongo I have used PHP 7.4 in the above PHP code.
1

You can use AES encrypt/decrypt that supported on both sides.

flutter_string_encryption

PHP

2 Comments

Does this work if I want to encrypt-decrypt an array? because it said string
@Azhar you can convert array to json and then encrypt /decrypt data.
1

You can use Cipher2 library for cryptography in flutter with the help of library you can encrypt and decrypt string with "aes-128-cbc" method

    //Make sure you import the library, stringEncryption is a user define function you can define your own
    stringEncryption() async { //call this method 
    String plainText ='String to encrypt';
    String key = '1245714587458745'; //combination of 16 character
    String iv = 'e16ce913a20dadb8'; ////combination of 16 character
    String encryptedString =
    await Cipher2.encryptAesCbc128Padding7(plainText, key, iv);
    print("key:$key");
    print("iv:$iv");
    print("String:$encryptedString");

    //for decrypt use decrypt function 
    decryptedString = await Cipher2.decryptAesCbc128Padding7(encryptedString, key, iv);
    //parameters: encryptedString,sameKey,SameIv
    }

    //To decrypt in PHP
    $method = 'aes-128-cbc';
    $decryptedString = openssl_decrypt("encryptedString", $method, "SameKeyUsedInFlutter", 0, "SameIvUsedInFlutter");

    //To encrypt in PHP
    $encryptedString = openssl_encrypt("Text to encrypt", $method, "SameKeyUsedInFlutter", 0, "SameIvUsedInFlutter");
    //Key and IV must need to match

Comments

0
function CryptoJSAesDecrypt(passphrase,encrypted_json_string){

var obj_json = JSON.parse(encrypted_json_string);

var encrypted = obj_json.ciphertext;
var salt = CryptoJS.enc.Hex.parse(obj_json.salt);
var iv = CryptoJS.enc.Hex.parse(obj_json.iv);   

var key = CryptoJS.PBKDF2(passphrase, salt, { hasher: CryptoJS.algo.SHA512, keySize: 64/8, iterations: 999});


var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv});

return decrypted.toString(CryptoJS.enc.Utf8);

} i want to covert php func crypto to flutter

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.