I have a string and I want to store this string securely in a database.
So, what came up to my mind is to encrypt this string using a user password as the encryption key.
And when the user needs to use this string we decrypt it using that key.
Is there some algorithm that helps to store these strings in a database securely, preventing anyone accessing it even the team?
You want to use some type of shared secret encryption algorithm like AES. Both openssl and mcrypt should support this. I would recommend openssl as mcrypt is EOL.
The following example comes directly from php.net. You probably don't need the hmac as you want to retrieve the original data.
<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
//$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv./*$hmac.*/$ciphertext_raw );
//decrypt later....
$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";
}
*/