Skip to content

Instantly share code, notes, and snippets.

@duplaja
Last active May 22, 2019 02:43
Show Gist options
  • Save duplaja/17ed58249853ee8a19d18bf04eb07472 to your computer and use it in GitHub Desktop.
Save duplaja/17ed58249853ee8a19d18bf04eb07472 to your computer and use it in GitHub Desktop.
Encrypt / Decrypt WP Options on Save (API keys, etc)
<?php
//Registers the pre_update_option filter for elements to encrypt. Format pre_update_option_(option name)
//Only do this for ones you want encrypted... in this case, first and third options.
function yourplugin_init() {
add_filter( 'pre_update_option_your_first_option', 'yourplugin_update_option', 10, 2 );
add_filter( 'pre_update_option_your_third_option', 'yourplugin_update_option', 10, 2 );
}
add_action( 'init', 'yourplugin_init' );
//Converts option value to encrypted form, only if it has changed
function yourplugin_update_option( $new_value, $old_value ) {
if ($new_value != $old_value) {
$cypher = 'aes-256-cbc'; //Pick the cypher to use
$key = md5(SECURE_AUTH_SALT); //SECURE_AUTH_SALT can be replaced with any unique string.
$new_value = openssl_encrypt("$new_value","$cypher","$key");
}
return $new_value;
}
//A function to retrieve the decrypted value of the options, to use them in your plugin
function yourplugin_decrypt_option($option) {
$cypher = 'aes-256-cbc'; //Be sure to use the same cypher as above
$key = md5(SECURE_AUTH_SALT); //Be sure to use same $key as above
$decrypted_value = openssl_decrypt("$option","$cypher","$key");
return $decrypted_value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment