N
N
nikita0710032020-09-04 21:14:00
PHP
nikita071003, 2020-09-04 21:14:00

How to encode a variable, send it to the database. Then get and decode back?

Hello, I need help with php:

I am writing api. It comes with 3 variables - $a, $code, $b.
You need to encode code. I do it through OpenSSL:

define('ENCRYPTION_KEY', 'ТУТ КОД ШИФРОВАНИЯ')

$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($code, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );


$ciphertext - send to the database, along with $a $b.

I get json

{"messages_dike":[{"id_message":"15","who_sent":"SOMETHING","who_get":"SOMETHING ELSE","message_text":"ENCRYPTED TEXT","message_type" :"1","message_datetime":"2020-09-04 05:00:00"},{"id_message":"16","who_sent":"SOMETHING","who_get":"SOMETHING MORE","message_text":"ENCRYPTED TEXT","message_type":"1","message_datetime":"2020-09-04 07:00:00"}]}

message_text is the same $code. It needs to be decrypted and displayed on the page in json format, then the Android application picks it up and processes it.

I encrypted $code, sent. Requested, received back, output json. And I couldn't decode it back.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Semyon Dubina, 2020-09-04
@nikita071003

As if straight from the documentation, the second example: https://www.php.net/manual/en/function.openssl-enc...

$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
{
    echo $original_plaintext."\n";
}

Keep only the entire $ciphertext

D
DimiDr0lik, 2015-08-17
@DimiDr0lik

solved the question itself)
you need to add the rule
route add -net 192.168.2.0 netmask 255.255.255.0 gw 192.168.1.114 in router 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question