WordPress Plugin: How to NOT Store API Key/Password in Plain Text

no-plain-text-api-key

Sometime we need to save API key, or password, for external services in our WordPress plugin. It’s problematic, since we have to use that key to make API connection, but we don’t want to save it in plain text (because it’s just plain dumb). So we need a way to encrypt this key and save it to database, and decrypt it to use.

This encrypted key need to be unique.

To make this encryption process possible, WordPress have salt/secret key (added in wp-config.php) that we can use.

Code Sample

Here’s a simple code sample to use:

/**
 * Encrypt Text
 * @link https://shellcreeper.com/?p=2082
 */
function my_encrypt( $plain_text ){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $h_key = hash('sha256', wp_salt(), TRUE);
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $h_key, $plain_text, MCRYPT_MODE_ECB, $iv));
}

/**
 * Decrypt Text
 * @link https://shellcreeper.com/?p=2082
 */
function my_decrypt( $encrypted_text ){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $h_key = hash('sha256', wp_salt(), TRUE);
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $h_key, base64_decode( $encrypted_text ), MCRYPT_MODE_ECB, $iv));
}

( source )

oAuth ?

yes, if it’s available, use oAuth.