Apply function to update_option Variable
I found some instructions on encrypting an options field for a plugin here, using:
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));
And here, recommending WP's Portable PHP Password hashing framework:
require_once( '/path/to/wp-includes/class-phpass.php' );
$wp_hasher = new PasswordHash( 8, TRUE );
$password = 'swordfish';
$hashed_password = $wp_hasher-HashPassword( $password );
But I'm having trouble because I want to display the decrypted password (if set) in the form field, but am not sure how to then encrypt it before sending to the DB.
The current code is as follows:
// Register and define the settings
add_action('admin_init', 'my_plugin_admin_init');
function my_plugin_admin_init(){
register_setting(
'my_plugin_options',
'my_plugin_options',
'my_plugin_validate_options'
);
add_settings_section(
'my_plugin_main',
'The Credentials',
'my_plugin_section_text',
'my_plugin'
);
// Display and fill the form field
function my_plugin_password() {
$options = get_option( 'my_plugin_options',__('Option Not Set') );
if (isset($options['my_plugin_password'])) {
$my_plugin_password = decrypt($options, $options['my_plugin_password'], SECURE_AUTH_SALT);
$my_plugin_password_enc = encrypt($my_plugin_password, SECURE_AUTH_SALT);
} else {
$my_plugin_password = _e('YOUR PASSWORD');
$my_plugin_password_enc = '';
}
// echo the field
echo "input id='my_plugin_password' name='my_plugin_options[my_plugin_password]' type='text' value='$my_plugin_password_enc' /";
}
add_settings_field(
'my_password',
'Enter Password: ',
'my_password',
'my_plugin',
'my_plugin_main'
);
And I think what's happening now is that an unencrypted password is being decrypted into something like this: @H!��f46vQa��,�v��3�1��(Ȥ��
The "encrypted" one just ends up looking like the input string followed by a string of A
s.
Do I need to add an update_option
call somewhere, maybe?
Also wondering if it's more secure to do the encrypting and decrypting with JavaScript so only encrypted strings leave the client. But I'm not sure how that would work when a user logged in from another client.
Topic encryption plugin-development Wordpress
Category Web