Why do generated passwords start/end with spaces?

If wp_generate_password() was called with the third parameter $extra_special_chars = true a space might be part of the password:

function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
    $chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    if ( $special_chars )
        $chars .= '!@#$%^&*()';
    if ( $extra_special_chars )
        $chars .= '-_ []{}<>~`+=,.;:/?|';

    $password = '';
    for ( $i = 0; $i < $length; $i++ ) {
        $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
    }

    // random_password filter was previously in random_password function which was deprecated
    return apply_filters('random_password', $password);
}

There are three other possibilities how spaces can find a way into passwords:

  1. The email client applied some broken formatting to the message.
  2. A plugin filters the password and adds the space.
  3. A plugin defined the function before WP did it (it is a pluggable function) and allowed spaces.

Search all installed plugins for password. Ask your users what email client they are using. To prevent spaces before or after WP generated passwords add a filter:

add_filter( 'random_password', 'trim' );

Note that WordPress does not send passwords with spaces to users by default. There is probably some other code involved.

Leave a Comment