my password generator

Passwords are everywhere, we use them for logging into all sorts of services, and typically we use a very small number of passwords, sometimes with small variations. In this article I explain why and how you should be using a password generator.

are my passwords strong?

Using similar passwords everywhere is bad practise – it means if an attacker gets a password for one service you use, they will likely be able to gain access to your other accounts elsewhere.

The reason you don’t use lots of different passwords is because it’s difficult for us humans to remember them all, especially when we’re told to use special characters, numbers, and mixed case letters, and avoid using words, patterns, or repetition.

Because this is what goes into making an OK password, but there is a better way.

so what is a strong password?

To create a strong password the only real option is to use a secure password generator. These use a cryptographically-secure random number generator to create the strongest passwords possible with the available limitations, such as length, characters available, etc.

What secure passwords look like:
64 character alphanumeric password:
a40vr2IStSnuSJWYwscjSgX5zKNyxKjn4v0q6mxkCbY7I2wm9FvbZumD2fMEtKL
64 character alphanumeric password with symbols:
aY5v[kHDRo:tET"zIarFn4£4[ZP|%YIH{hR6"xRU[6£n,baS8[tf&d520ZhE:2

So you get the idea. Even short passwords (16 characters or less) are much more secure than any password you can actually think of, even mashing your face on the keyboard will result in reproducible patterns. If an attacker mashes their own face into a keyboard for hours and hours, not only is this hilarious for everyone watching, but chances are that they will have generated several passwords that are similar to yours. They can then add these “mashed face” passwords to a database to use in the future, to save themselves the face-pain if nothing else. (This is what password databases are for – they contain billions of passwords to use in cracking systems. I’m not covering rainbow-tables here, but please feel free to read up on it in your spare time.)

why are my normal passwords not strong?

Basically it comes down to the ease at which they can be computationally guessed, given whether the attacker has a hash, hint, or other personal data that you may have used to create your password, such as patterns you’ve used to create passwords on other sites.

If an attacker has one of your passwords, are your other passwords sufficiently different to prevent the attacker guessing the other ones?

If you use `las4nco7h3jpjse;facebook` as your facebook password, what combinations do you think the attacker might try to use to access your gmail account?
Perhaps `las4nco7h3jpjse;gmail` and `las4nco7h3jpjse;google` would be their first two attempts?

It only takes one of your accounts’ passwords to be compromised using this pattern for all of your other account passwords to become guessable.

how do i generate a strong random password?

I use a password generator that I wrote myself, which is clean and simple. It is based on principles of generating numbers with high entropy using a secure random number generator function built into Javascript, and available on most (if not all) browsers.
This extension works on Chrome and Firefox at the time of writing, and it doesn’t work in Internet Explorer.
(I would appreciate it if people would tell me via comments if it works in other obscure browsers.)

Drag the following button into your bookmarks bar to use this password generator, the code is also shown a bit further down the page.

Password Generator

Clicking on it in your toolbar should result in a window like this:

password generator

Click the buttons to generate passwords according to the length and complexity required.

but how am i supposed to remember all these passwords?

You aren’t.

There are several browser extensions and third-party applications that enable the secure storage of passwords, such as KeyPass, Keeper, and even as a core part of the Google Chrome browser.

Many of these secure password stores are available as extensions to your existing Firefox, Chrome or IE browsers, and on mobile devices, so you can generate and submit a new password on one device, and it will be available on your other devices automatically.

but what if someone gets my password manager password?

Using a password manager does mean you typically need to remember at least one relatively secure master password, but these services do typically offer two-factor authentication, which forces anyone who attempts to log in to your password storage to also have access to your phone or mobile device, so it can send you a text message to confirm the person who owns the password storage is also in control of the registered phone number for the account.

Google, Facebook, Twitter and others support two-factor authentication, and you should be using it whenever possible.

the geeky bit

The bookmarklet is a block of Javascript code that executes on the current page you are browsing, but doesn’t send any data to any server at all. This means the password generated only ever exists in the browser window. You have the option in the tool to generate various password sizes, with or without special characters. It is also relatively easy to change the code if you want additional buttons.

From a security perspective there are a couple of other features this password generator makes use of:

  1. By default it obscures most of the password from view, so if your screen is being watched (either by shoulder-surfing or by a more nefarious screen watching software utility) then the password is still moderately protected. There is a ‘show password’ button so you can check the password looks as you might expect, but this defeats the security feature.
  2. If you have a keylogger installed on the computer, the copy-paste action of the password text is not likely to be captured by the keylogger, which it would be if you had to type it in manually. Copy-pasting passwords also reduces the likelihood that you will get the password wrong, and makes you feel more comfortable using absurd-looking long passwords with lots of special characters.
  3. The bookmarklet relies on no third party code, so there are no connections made to any other resource to generate or store your password, or to facilitate any component of this utility.

Here’s the code for the password generator with a bit of wrapping and white-space to make it more readable.

javascript:(function() {
    var x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        y=x+'!"£$%^&*()_+-={}[]:@~;#?,./|\',
        w=window.open('','',
            'height=110,width=600,top=100,left=100,location=no,menubar=no,'+
            'resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no'
        ),
        d=w.document,
        b=d.body,
        a='appendChild',
        C='createElement',
        B=d[C]('button'),
        e=d[C]('input'),
        ctn='createTextNode',
        f=function(c,ct){
            var bb = d[C]('button');
            bb[a](d[ctn]('x'+ct));
            bb.onclick=function(){
                var f=new Uint8Array(ct),
                    i=f.length-1,
                    o='';
                w.crypto.getRandomValues(f);
                while(i)o+=c[f[i--]%c.length];
                e.value=o;
                e.select();
            };
            b[a](bb);
        },
        m=function(R,t){
            b[a](d[R](t));
        };
    b.style.fontFamily='Tahoma';
    b.style.background='#cfc';
    e.style.width=20;
    b.onclick=function(){e.select();};
    B[a](d[ctn]('password hidden for security - click to show'));
    B.onclick=function(){
        e.style.width=550;
        B.style.display='none';
    };
    m(ctn,'Press Ctrl-C to copy your new password ');
    m(C,'br');
    b[a](e);
    b[a](B);
    m(C,'br');
    f(x,16);
    f(x,32);
    f(x,64);
    m(ctn,' a-zA-Z0-9');
    m(C,'br');
    f(y,16);
    f(y,32);
    f(y,64);
    m(ctn,' with symbols');
}());

The code is minified somewhat, as URLs are limited to 4096 bytes – this code is way below that anyway, but it makes it look more exciting if nothing else.

what is the difference between random and secure-random?

I’m glad you asked.

Generating random numbers with normal ‘random’ functions aren’t considered secure because although the output of these functions appears random, and the randomness usually stands up to basic statistical analysis, standard random number generators are only random enough to be used for non-security related scenarios. Normal random number generators should only be used where the numbers generated aren’t predictable or reproducible.

The last few digits of the current system time in microseconds might be used as a simple generator, but these numbers are selected at intervals from the same source, with little external influence, so reproducing or predicting the next number in the series would be a lot easier than if the numbers were produced by a more secure system. So `current microseconds mod 6` is great for generating dice rolls, but not so great for generating passwords.

To generate random numbers in Javascript that are strong, we use `window.crypto.getRandomValues()`. This is a built-in security component of modern web browsers. If we just need a normal ‘random’ number, we use `Math.random()` instead, which is quicker, but not secure.

further reading

php passing pointer parameters performance

A little adds up to a lot, and in the world of code, a tiny change in code performance can have a big impact on application performance overall.

So, pointers aren’t a “thing” in PHP. This article is about the use of PHP References, and I used the word ‘pointer’ in the title because it is alliterative. So there 🙂


how to test performance of small blocks

So there are plenty of theories on how to test code performance, but this simple script below can trivially compare 2 blocks of code. Both blocks must be executed an equal number of times, with as little risk of other system interference as possible. This means you don’t run one block of code 1000 times and then run another block 1000 times to compare them – this risks external influences affecting one of the execution cycles much more heavily than the other, tainting your results. So you run one, then the other, then repeat, capturing times for each execution as it happens.

function funcA() {
    //do some code
};
function funcB() {
    //do some other code
};
//setup (only run once):
function changeDataA() {}
function changeDataB() {}

$loops = 5000;
$timeA = 0.0;
$timeB = 0.0;

ob_start();
for($i=0; $i<$loops; ++$i) {
    $start = microtime(1);
    funcA();
    $timeA += microtime(1) - $start;

    $start = microtime(1);
    funcB();
    $timeB += microtime(1) - $start;
}
ob_end_clean();

$timeA = round(1000000 * ($timeA / $loops), 3);
$timeB = round(1000000 * ($timeB / $loops), 3);

echo "
TimeA averaged $timeA microseconds
TimeB averaged $timeB microseconds
";

So I’ll be using this code to show how performance differs when writing your code slightly different ways. Sometimes the difference is very small, and you are welcome to reproduce these tests and come to your own conclusions, this blog contains only my professional opinions.

Sometimes the code set up cost should also be taken into account – if the code in question is called a small number of times in a single execution of your code then the set up cost of a block of code will have a bigger impact on performance. I will include the code I used to perform these tests below so you can see where I have included set up cost in the calculation.


passing variables by reference

Passing variables by reference is when you use the `&` prefixed to an argument in a function, so any changes made to that variable in the function will also affect the variable that was passed into the function.
These parameters are called references, passing ‘By Reference’ being the opposite of passing ‘By Value’ which is when you pass a variable without the ‘&’ prefix.

Example:

function funcA() {
    $str = str_shuffle("0123456789");
    $str = changeData1($str);
    strlen($str);
};
function funcB() {
    $str = str_shuffle("0123456789");
    changeData2($str);
    strlen($str);
};
//setup (only run once):
function changeData1($data) {
    return $data . " World";
}
function changeData2(&$data) {
    $data .= " World";
}

results in the following execution times:

TimeA averaged 2.774 microseconds
TimeB averaged 2.748 microseconds

So not a lot of difference there, but you can already see the `funcB()` function is very slightly faster.

But… Consider what happens you are working with larger data blobs. All of a sudden you are calling a function `changeData1()` with large amounts of data that PHP has to allocate memory for, copy it, alter it, then remove the original (and later garbage-collect it). This can happen when modifying the contents of a file, for example:

function funcA() {
    $str = str_shuffle("0123456789");
    $str = str_repeat($str, 100000);
    $str = changeData1($str);
    strlen($str);
};
function funcB() {
    $str = str_shuffle("0123456789");
    $str = str_repeat($str, 100000);
    changeData2($str);
    strlen($str);
};
//setup (only run once):
function changeData1($data) {
    return $data . " World";
}
function changeData2(&$data) {
    $data .= " World";
}

Outputs:

TimeA averaged 542.497 microseconds
TimeB averaged 294.44 microseconds

It was ~45% faster to use a reference here.
So when working with large strings, it is a lot more performant to alter the existing string, than to copy the passed string and return it.


On a large array:

function funcA() {
    $str = str_shuffle("0123456789");
    $str = str_repeat($str, 10000);
    $str = explode('0', $str);
    $str = changeData1($str);
    count($str);
};
function funcB() {
    $str = str_shuffle("0123456789");
    $str = str_repeat($str, 10000);
    $str = explode('0', $str);
    changeData2($str);
    count($str);
};
//setup (only run once):
function changeData1($data) {
    $data[] = " World";
    return $data;
}
function changeData2(&$data) {
    $data[] = " World";
}

outputs:

TimeA averaged 2980.23 microseconds
TimeB averaged 2028.161 microseconds

So we took ~32% off the processing time here by passing our variable by reference.


we can also use the reference operator `&` in a regular `foreach` loop.

Here’s an example:

function funcA() {
    $str = str_shuffle("0123456789");
    $str = str_repeat($str, 1000);
    $str = explode('0', $str);
    foreach($str as $k => $v) {
        $str[$k] .= 'a'; //<-- we have to look up the key every iteration!
    }
    count($str);
};
function funcB() {
    $str = str_shuffle("0123456789");
    $str = str_repeat($str, 1000);
    $str = explode('0', $str);
    foreach($str as &$v) { //<-- & used here, and no key required any more
        $v .= 'a'; //<-- modify the value in the array using the reference 
    }
    count($str);
};

And our survey says:

TimeA averaged 296.358 microseconds
TimeB averaged 160.289 microseconds

Sooooo…. We nearly improve the performance of this code by ~54%, just by using a reference instead of modifying the array values by key.


using a reference to reduce calls to nested variables

Why write this code:

$myBigArray['firstVar']['secondVar']['thirdVar'][] = "FOO";
$myBigArray['firstVar']['secondVar']['thirdVar'][] = "BAR";
$myBigArray['firstVar']['secondVar']['thirdVar'][] = "Hello";
$myBigArray['firstVar']['secondVar']['thirdVar'][] = "World";

when you can do this instead:

$thirdVar =& $myBigArray['firstVar']['secondVar']['thirdVar'];
$thirdVar[] = "FOO";
$thirdVar[] = "BAR";
$thirdVar[] = "Hello";
$thirdVar[] = "World";

Much better 🙂


use `unset` when you want to redefine the reference

When working with references, it can be pretty easy to accidentally modify data you didn’t intend to, consider this:

$bar = "bar";
$foo =& $bar;
$foo = null;

This code sets `$bar` to null. The reference `$foo` is still pointed at `$bar`.
If you want to stop `$foo` pointing at `$bar` you have to point it at something else,
eg. $foo =& $somethingElse
or you need to call unset($foo).


Common methods in PHP already use references for performance reasons, such as:

for sorting the elements in the given array
function sort (array &$array, $sort_flags = null) {} (and other array sorting functions)

for randomly re-ordering elements in the given array
function shuffle (array &$array) {}

for iterating over the given array, modifying values as it loops over items in the given array
function array_walk (array &$array, $funcname, $userdata = null) {}

for getting the current element in the given array
function current (array &$array) {}

for adding a variable to the end of the given array
function array_push (array &$array, $var, $_ = null) {}

So all of these methods modify the given array in-situ, rather than returning a modified copy of it.
If you think about it, this makes a lot of sense, because if you want to retain the original array before you modify it, then it’s just one line of code to copy the array; but if these functions always returned a copy of the given array, you would have to write your own function to modify the original array in-situ if you wanted the performance gain.


Other core functions in PHP use references for passing data back to the calling code, for example:

$count = null;
str_replace("_", "-", "ab_cd_12_34", $count);
echo "count: $count"; //says "count: 3"

The signature for this function is:

function str_replace ($search, $replace, $subject, &$count = null) {}

This can be very handy when you want to change an existing function to return more than one variable, but don’t want to change all the existing usages of the function in your code. Just tack on an optional reference parameter to the function signature and use that to return your extra data. And maybe design your system better next time 😀


you don’t need to use references to objects

When passing objects around, copies of them are NOT created by default. So you don’t need to use references in this case, the original object will still be modified by your function. See example:

class Foo {
    public $foo;
}
$a = new Foo;
function updateMe($a) { //foo = "bar";
}
updateMe($a);
echo "Foo: ". $a->foo; // says "Foo: bar"

If you use a reference on the parameter here it doesn’t give you any warning, because the parameter may accept primitive types as well as objects, which would otherwise be passed `ByVal` instead of `ByRef`.


ye olden days of references in php

For those who are interested, in PHP’s history, parameters to be passed by reference use to have to be specified in the calling code, instead of the function signature, like so:

$a = "hello";
function modifyMe($a) { //<-- reference not used here
    $a .= " world!";
}
modifyMe(&$a); //<-- reference used here

But if you try to do this today, you get a Fatal error….

PHP Fatal error:  Call-time pass-by-reference has been removed;
If you would like to pass argument by reference, modify the declaration of modifyMe().

Further Reading

PHP Manual: References
Stephen Morley: PHP references tutorial

code smell – objects vs arrays

“Code Smell” is a term that I have heard used in the past, and regularly use myself to describe code that may work fine, but just doesn’t seem as good or clean as it could be. Maybe there’s some repeated code, or unnecessary over-use of strings. Basically the code smells bad.

Use objects instead of associative arrays for working with collections of values.

Here’s why…

In Javascript, it is now commonplace to see a single object passed to a method as a collection of parameters.
This is for code flexibility, so you can call the method with as many or as few values in the object as you like, and you can build the list of values to be passed to a method over a larger area of code. It also means you can simply forward the parameters object to another method, perhaps modifying some of the parameters between calls.

So the community has accepted this is convenient way to pass parameters around – I’m not saying this should be done everywhere, in fact this should only be done when it smells right to do so… Currently one commonly used option is to use associative arrays to accomplish this. Here are some unexpected drawbacks:

  • `$arr[‘foo’]` can’t be described using `/** @var */` (or PHPStorm doesn’t support it).
  • `$arr[‘SomeVariebleName’]` won’t show the typo when you meant `$arr[‘SomeVariableName’]`
  • `$arr[‘bar’]` might be not set, and you’d have to use `isset()` or similar function to determine if it has been set.
  • `$arr[‘foo’]` is slower than `$arr->foo`. Not by a lot, but it is.
  • finding all the places in your code that `$arr[‘foo’]` is used when your array keeps getting passed around, is hard work.
  • you have no dedicated place to put functions for interacting with this array of parameters.

To fix some of these issues you might convert your array to an object using a cast:

$arr = ['foo'=>'a', 'bar'=>'b']; 
$object = json_decode(json_encode($arr), FALSE);
//or 
$object = (object) $arr;

However, you still have no dedicated space to describe the object – `$arr->foo` still has no built-in PHPDoc, no default value, and if you are likely to use the same object in multiple classes, you end up reproducing blocks of code, which also smells bad.

Here are some solutions…

class HelloWorldParams
{
    /** @var int */
    public $foo = 1;

    /** @var string */
    public $bar = 'foo';

    /** @var string */
    public $ran = 'bar';
}

$f = new HelloWorldParams();
$f->foo = 1;
$f->bar = 'Hello';
$f->ran = 'World!';

So here we’ve completely replaced using the array with using a custom object, in the same way that we would use a STRUCT in C. No methods, just a class that contains a bunch of properties. Using this object makes reading the code easier, tracing code easier, and refactoring code easier. And all it takes is a tiny little class that can be re-used elsewhere in your project.

What about when we have an array and we need to convert it?

Good question. We can add a constructor method to our class to make this easier:

class HelloWorldParams
{
    /** @var int */
    public $foo = 1;
    
    /** @var string */
    public $bar = 'foo';
    
    /** @var string */
    public $ran = 'bar';
    
    /**
     * HelloWorldParams constructor.
     *
     * @param mixed[] $arr
     */
    public function __construct(array $arr=[])
    {
        foreach($arr as $k => $v) {
            $this->$k = $v
        }
    }
}

$arr = [
    'foo' => 1,
    'bar' => 'Hello',
    'ran' => 'World!'
];
$f = new HelloWorldParams($arr);

This technique demonstrates replacing an associative array with an object, to improve performance, maintainability, readability and to reduce code duplication. That is all.

Some folks might say

you should always have setters and getters to access object properties

but these people are wrong. KISS!!

There is a time and a place for getters and setters (or accessors and mutators if you’re in academia) and this is not it. You can add them if you like, but IMHO you’re just adding unnecessary code. Remember that you’ve already improved your code with this simple step above, there’s no need to go overboard.

This is a simple class, and if you want to add complex functionality like input validation (which is one of the main reasons for using setters), then you’re better off using a validation class that validates the input data, and a hydrator class that populates the object, which is beyond the scope of this blog entry.


It is possible to reduce the code a little using PHPDoc instead of explicit properties – I advise against this as it reduces code clarity, but I’ll describe what I mean here anyway, so I can show you a slightly more unusual PHPDoc use-case:

/**
 * @property int $foo
 * @property string $bar
 * @property string $ran
 */
class HelloWorldParams{}
$f = new HelloWorldParams();

So this happens in PHPStorm:

PHPStorm recognises @property values

So the only practical difference between this and the previous code above, is that we can’t use default values for the properties unless we add them as real properties of the class. Also, parsing annotations in this class won’t work as effectively as it would for the previous example, because we are describing properties within the class docblock, instead of using dedicated docblocks for each property.

(A docblock is a `/** … */` , not to be confused with a multi-line comment `/* … */`.)


All the examples above allow you to add any property to the class, so by default it doesn’t prevent you from setting a property to the object that it doesn’t expect to have.
PHPStorm will warn you that you’re using an unexpected field, but it will still let you set the property:

PHPStorm Field not found
PHPStorm field declared dynamically

So here’s one way to prevent custom dynamic fields being set in your object, that still retains most of the above functionality:

class HelloWorldParams
{
    public $foo;
    public $bar;
    public $ran;
    /**
     * @param string $name
     * @param mixed $value
     */
    public function __set($name, $value)
    {
        if(!property_exists($this, $name)) {
            throw new InvalidArgumentException(
                "Property '$name' not present for object " . __CLASS__
            );
        }
    }
}
$f = new HelloWorldParams();
$f->abcd = "bar";

We’re using the `__set()` magic method to throw an exception if we try to set a value to a property that doesn’t exist. Simple.