One particular web service that I am writing interfaces with an API. Each API call requires the user's username and password to be sent, no state is maintained.
Ideally, when using my web service the user will enter his API username and password once, and my web service will store that information until the session ends. I understand that I should not store the API password using PHP sessions nor in a database due to security concerns. Therefore, how can I securely store and access the password for the duration of the session?
Would it be secure to encrypt the password, store the encrypted password in a cookie and the encryption key in a session?
Note that I originally asked the question (without the proposed solution) on SO: https://stackoverflow.com/questions/15084025/storing-third-party-passwords-for-reuse-across-pages Had I drank coffee first, I would have known to post here instead of there. The SO post can be deleted, but not by me.
The answer given there is the one I am now using in production, so if there are flaws in the approach (store encrypted password in PHP session, encryption key in cookie) then I would very much like to know.
$encryptionKey = sha1(microtime(true).mt_rand(PHP_INT_MAX / 10, PHP_INT_MAX)); $encryptedPassword = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryptionKey, $password, MCRYPT_MODE_CFB); setcookie('atwood', $encryptionKey, 0); $_SESSION['encryptedPassword'] = $encryptedPassword; $password = mcrypt_decrypt(MCRYPT_BLOWFISH, $_COOKIE['atwood'], $_SESSION['encryptedPassword'], MCRYPT_MODE_CFB);