define('AES_256_CBC', 'aes-256-cbc');

// both stored in a file on server
$encryption_key = openssl_random_pseudo_bytes(32); 
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC)); 

$user_id = 1123;
$exp     = time() + (365 * 24 * 60 * 60);

$data = [
    "user_id" => $user_id,
    "exp"     => $exp,
$json = json_encode($data);

$token = openssl_encrypt($json, AES_256_CBC, $encryption_key, 0, $iv);
$base = base64_encode($token);
// at this point send the token to the client to use for further auth
$tokenDecoded = base64_decode($base);
$clear = openssl_decrypt($tokenDecoded, AES_256_CBC, $encryption_key, 0, $iv);
$sessionData = json_decode($clear);


Everything occurs over an SSL HTTPS connection with signed certificate.

Is my implementation safe?


1 Answer 1


It is not just the safety of your code that you should be worried about. You need a holistic approach; your question suggests to me that you have not looked at the bigger picture. Read this article and you will see you need to approach your question differently. For one, it depends on your server's configuration.

Depending on how important the security requirements are for you, I'd suggest using a third party service; either one which takes the problem off your hands entirely, or if that's not an option, have a consultant guide you to making a setup that will stay secure even over time while code changes and cracks can slip through unnoticed. There are some services that can try to find holes in your system, but they are only of limited use.

If you need a better answer than this, I think you're going to have to give a lot more info on the context of your code; where it's used, how it's used, etc.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.