PHP Snippet 1:
//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
PHP Snippet 2:
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);
}
}
PHP Snippet 3:
<?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);
}
}
PHP Snippet 4:
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);