Skip to content

Instantly share code, notes, and snippets.

@chlp
Created December 4, 2018 16:21
Show Gist options
  • Save chlp/57aaadd9582c86c73ea0010e0221dc6c to your computer and use it in GitHub Desktop.
Save chlp/57aaadd9582c86c73ea0010e0221dc6c to your computer and use it in GitHub Desktop.
Example of usage OpenSSL symmetric encoding and decoding with AES-256-CBC on php and from command line
<?php
// ENCRYPTION
$method = 'AES-256-CBC';
$secret = 'my secret';
$key = 'test';
$hex_key = (bin2hex($key)); // example 74657374
$length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($length);
// $iv = hex2bin("047ed7c4aaf0069daa06b633b86aff67");
$hex_iv = bin2hex($iv); // example 047ed7c4aaf0069daa06b633b86aff67
$encrypted = openssl_encrypt($secret, $method, $key, OPENSSL_RAW_DATA, $iv);
$str_for_sending = base64_encode($encrypted) . ';' . base64_encode($iv);
var_dump($str_for_sending);
// # command line
// echo -n "my secret" | openssl enc -AES-256-CBC -nosalt -K 74657374 -iv 047ed7c4aaf0069daa06b633b86aff67 -p -base64
// key=7465737400000000000000000000000000000000000000000000000000000000
// iv =047ED7C4AAF0069DAA06B633B86AFF67
// FTeg+9M4GcrTwMFUKy75vQ==
// DECRYPTION
list($data, $iv) = explode(';', $str_for_sending);
$iv = base64_decode($iv);
$decrypted_data = openssl_decrypt($data, $method, $key, 0, $iv);
var_dump($decrypted_data);
// # command line
// echo -n "FTeg+9M4GcrTwMFUKy75vQ==" | base64 --decode | openssl enc -AES-256-CBC -d -nosalt -K 74657374 -iv 047ed7c4aaf0069daa06b633b86aff67 -p
// key=7465737400000000000000000000000000000000000000000000000000000000
// iv =047ED7C4AAF0069DAA06B633B86AFF67
// my secret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment