How to store username and password to API in wordpress option DB?

I’m currently developing a plugin and the chances are that I will more than likely release it on the public plugin repository so others can use it.

The plugin will be using an API and to use this API you need to pass a username and password. So my plugin needs to store these login credentials in the database. I don’t want to store these in plain text although the API needs them in plain text.

So my question is how do I store these sensitive bit of information? Hashing is out, so it has to be some sort of encryption.

In WordPress is there a unique key that can be used that will differ from blog to blog? What php functions should I use to encrypt and decrypt? I’m looking for functions that will more than likely work on all WP installs.


While I agree with the previous answers, to answer the question you actually asked, what comes to mind is to use one of these constants for wp-config.php:

define('AUTH_KEY',        'redacted');
define('SECURE_AUTH_KEY', 'redacted');
define('LOGGED_IN_KEY',   'redacted');
define('NONCE_KEY',       'redacted');

They are meant to be unique across wordpress installations – and are about the only options for pre-existing keys to be found in wordpress. Alternate would be to add your own similar constant that is built by hashing one of them against the admin email address or similar – and then storing that in a hidden setting option — to protect against losing your key if someone accidentally modifies the keys after your plugin is installed. The danger is, that if they were not made unique on the initial install, but the admin / site owner decides to rectify the failure after the fact, they shouldn’t accidentally break your password encryption.

As for encryption / decryption functions – a quick Google search returns the following listing with code that appears to fit the bill:

function encrypt($input_string, $key){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $h_key = hash('sha256', $key, TRUE);
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $h_key, $input_string, MCRYPT_MODE_ECB, $iv));

function decrypt($encrypted_input_string, $key){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $h_key = hash('sha256', $key, TRUE);
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $h_key, base64_decode($encrypted_input_string), MCRYPT_MODE_ECB, $iv));

Here’s some documentation of the AES encryption used here:

Leave a Comment