Signup/Sign In
LAST UPDATED: MAY 7, 2024

One Time Password Generation using Javascript

Web Development #web-development#javascript

    With the rise of technologies like Internet Of Things (IoT), Cloud and Big Data we have seen applications in the recent past which are making our lives better with each passing day. With so much data being generated, security has become the pillar stone for almost every technology/application. And hence, one should focus on security from the time of inception of any application idea. One Time Password or OTP is one of the security mechanisms used in modern applications.

    Most of the web applications and even mobile applications are using one time passwords as the first step of verifying authenticity of a user because there are many issues with static passwords. Static passwords are the passwords that we associate with our user-id or email-id while registering for any website or mobile app. There are many problems with static passwords, some of them are listed below

    Problems with static passwords:

    1. Most of the users use the same password for different websites, hence if a person knows your password for any account then it is easy to crack open your different accounts.

    2. Keyloggers are able to capture your static passwords easily.

    3. Static passwords can be easily cracked using password attacks like Brute force, Dictionary attacks, and pre-calculated dictionary attacks.

    Reasons to use One Time Passwords:

    1. One Time Passwords provide better security than static passwords because OTPs have expiry time which makes it harder for any hacker or attacker to crack the password within the expiry time of the OTP.

    2. Keyloggers (software or hardware which can be used to capture strokes on the keyboard of a device) help to capture static passwords typed by the user. Yes, it can also be used to capture the user's OTP at that point in time, but that OTP cannot be used for the next time to log into the account.

    OTP generation for applications

    Most of the two-step authentication or two-step verification methods use One-Time Passwords.

    The main role of a One-Time Password (sometimes analogously used as One Time Pin) is to authenticate a user for a single session or transaction. It is used almost in every banking transaction. This technique is a very simple yet powerful way of verifying users.

    So let us start with the fundamentals of One Time Password (OTP) generation.

    Generally, the client and server(generates the OTP) use time-synchronization algorithms so that the user is validated whenever OTP is generated within a given time frame. In this article, we will learn how to generate One Time Passwords only.

    In general, One Time passwords can be classified into two types:

    1. Numeric OTPs: All the characters in the OTP are numbers only.

    2. Alphanumerical OTPs: The characters in the OTP are a mix of both numbers and alphabets.

    The length of the OTP varies from application to application and is completely dependent on one's own requirements. If you want more secure OTPs, then we suggest choosing longer-length OTPs. At present, most of the applications generate One Time Passwords of length 4 or 6.

    In this article, you will learn to generate OTP in JavaScript.

    How to Generate One Time Password using Javascript

    Let's see how to code this in JavaScript.

    One Time Password Generation(Only Digits)

    Here we have the code for generating OTP:

    function generateOTP()
    {
    
        var digits = '0123456789';
    
        var otpLength = 4;
    
        var otp = '';
    
        for(let i=1; i<=otpLength; i++)
    
        {
    
            var index = Math.floor(Math.random()*(digits.length));
    
            otp = otp + digits[index];
    
        }
    
        return otp;
    
    }

    Above is the code for generating the OTP, now let's try to understand what we have done.

    Understanding the generateOTP() method

    1. The first step is to store all the digits(0 to 9) in a variable named digits and this string is later used as an array to access its characters.

    2. Then we defined the length of the OTP using the variable otpLength, this value should be greater than or equal to 4.

    3. We are using an empty string otp which will store each and every random number generated, and hence form the OTP.

    4. The for the loop is then defined in a way that it iterates a number of times equal to the otpLength.

    5. In each iteration, a random number is generated using the Math.random() method, which will return a value between 0 and 1. This value is then multiplied by the length of the digits array.

      i.e value between (0-1)*(length of digits array)

      For example: 0.2708388088367647*10 = 2.7083880883676468

      Take one more example, 0.9410922840442396*10 = 9.410922840442398

      The result is always a floating value.


    6. So to obtain an integer value we round the result using the Math.round() method.

    7. The whole equation is as follows:

      Math.round(Math.random*digits.length);

      For example: Math.round(0.44569 * 10)

      4 is the value generated.


    8. The value that we obtain in step 7 is stored in the variable index. Now we use this index to point the value at that index in the string(array) digits.

      For example: if the value of index = 4

      Then we access the digits string in the following manner: digits[index]

      And you see the output by printing the value in console using the following statement: console.log(digits[4])

      The value at index 4 in digits is 4
      Digits Array
      In the picture above we have the digits string represented as an array.

    9. In the above array representation, we can observe how the characters are accessed from the string digits and are concatenated to the otp variable thus forming the OTP.

    10. Finally using the return statement we pass the generated otp to the function which called the generateOTP function.

    OUTPUT of the Program:

    I wrote a loop to generate OTP 5 Times and as you can see below they were different every time.

    Numerical OTP Output using Javascript

    One Time Password Generation (Alphanumeric OTP)

    Now let's update our code to make it generate alphanumeric OTP.

    function generateOTP()
    
    {
    
        var digits = '0123456789abcdefghijklmnopqrstuvwxyz';
    
        var otpLength = 6;
    
        var otp = '';
    
        for(let i=1; i<=otpLength; i++)
    
        {
    
            var index = Math.floor(Math.random()*(digits.length));
    
            otp = otp + digits[index];
    
        }
    
        return otp;
    
    }

    Similar to the previous program, the functionality is same but the only difference is that our digits string consists of alphabets from a-z along with numbers from 0-9.

    Hence the digits.length will produce a value of 36(ie. 10 numbers and 26 alphabets). Then the value stored in variable index will be between 0 and 36.

    In addition to the variable digits we also changed the value of otpLength to 6, to produce a 6 digit OTP.

    Array2 reference image for OTP with alphabets

    OUTPUT of the Program:

    All the OTP’s are of length 6 and are unique.

    Output for Alphanumerical OTP generation

    TIP to Generate OTP with Special Characters

    To implement a different kind of OTP with special characters along with numbers and alphabets just change the variable digits with the characters you want like placing alphabets from A-Z (upper case) or placing some special symbols. (There are possibilities of errors when special characters are used)

    var digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+';

    OUTPUT of the Program:

    With the digits string changed, as shown above, the following will be output:

    Output 3 image for Alphanumeric with Capitals and Special characters

    Time-Based One Time Passwords

    The OTPs which are valid for a specific amount of time are called Time Based One Time Passwords (TOTP). There are many applications available for two-step verification, you need not create your own authentication system.

    Google Authenticate is one good example for Time Based OTPs. You can use the API (Application Programming Interface) of Google to implement this. But it uses more complex algorithms like HMAC-SHA1 and some Time based algorithms.

    LastPass is a similar software that also provides the facility to store like a vault and is available for Chrome and some other browsers.

    There are many two-factor authentication applications like Microsoft Authenticator, Authy, and Yubico Authenticator. While most of these are software applications, Yubico is a hardware-based solution for two-factor authentication, where you need to buy a YubiKey(a USB device) which verifies an account with a one-tap(button provided on the device) approach, although this is very easy but is supported by very fewer accounts like Google, Github, etc.

    One interesting thing is that almost every application these days use one-time passwords to verify the user rather than using static passwords. But you can try different authenticators too and comment below or let us know if there are any new Authenticators worth using ;)

    HAPPY CODING!

    Conclusion

    Using JavaScript to generate one-time passwords (OTPs) is a secure and effective way to authenticate users. Libraries such as OTP.js and Speakeasy make implementing OTPs easy. Although OTPs are not completely secure, they provide an extra layer of security to protect against common threats.

    Frequently Asked Questions(FAQs)

    Let's see some frequently asked questions.

    1. What is One Time Password (OTP) generation using JavaScript?

    OTP generation using JavaScript is a process of creating a unique, one-time password that expires after a single use, using JavaScript programming language.

    2. How does OTP generation using JavaScript improve website security?

    OTPs add an extra layer of security to website login processes, making it harder for attackers to gain access to user accounts.

    3. Are there any JavaScript libraries available for OTP generation?

    Yes, libraries such as OTP.js and Speakeasy offer developers a range of tools for generating OTPs and integrating them into their systems.

    4. Are OTPs completely secure?

    While OTPs provide a high level of security, they are not entirely foolproof. Attackers may still be able to intercept OTPs, but implementing OTPs can significantly reduce the risk of unauthorized access to sensitive information.

    You may also like:

    Software Engineer| AI | ML | Geek
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS