Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Create A Random Nonce String Using JavaScript

TwitterFacebookRedditLinkedInHacker News

Have you ever needed to come up with a random string of characters say for a password? Maybe you’re looking for a random string of characters for an oauth 1.0 nonce. Maybe you’re in a job interview and you’re asked to generate a random alpha numeric string.

Whatever the case, we’re going to look at generating a random string of characters of any given length using JavaScript.

If you’ve been keeping up with my open source work, you’ve probably seen a nonce function I’ve made for use with oauth 1.0a providers.

A nonce via Wikipedia:

An arbitrary number used only once in a cryptographic communication.

Here is one way to create such a function:

var randomString = function(length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for(var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

This code was actually taken from a popular Stack Overflow example.

So in case you’re not familiar how the code works. We first define a string of all the allowed characters in our final randomized string. We then loop until a given length which will represent the string size. In this loop we will look at the allowed character string as a kind of array (character by character) and randomly choose an index of the array. This then allows us a random string.

Conclusion

Knowing how to create a random string is good for oauth nonce’s, strong passwords, and interview questions for software engineering phone screenings. Good to know and easy to do.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.