Blog

Improve security with OTPs: Guide to one-time passwords

Amy Elliott Amy Elliott
· 12 min read · Tips and resources · October 11th, 2024
If you’re looking for a way to make your customers’ experience and your app or website more secure, one-time passwords (OTPs) are the ideal solution.

With so much of what we do now residing online, it’s no surprise that the rate of security breaches has exploded. But, there are solutions that businesses can implement to protect themselves and their customers—in this article, we’re talking OTPs. 

One-time passwords are a simple yet highly effective way to prevent hackers from gaining access to online accounts. They work by providing a unique password every time the user logs in. 

Keep reading to learn more about OTPs and how they work, plus how you can easily set up and start sending OTPs with MailerSend. Let’s get to it!

What are OTP messages?

A one-time password (sometimes referred to as a one-time passcode) is an algorithm-generated password used to authenticate a single transaction or login session. 

OTPs can be used for the entire authentication process, for example, using an OTP on its own to log in along with the user’s username, email address or phone number. Or, it can be a part of a multi-layer authentication process, such as two-factor authentication (2FA) or multi-factor authentication (MFA). This involves the user logging in with static credentials and then using an OTP as an additional layer of authentication. 

Here’s an example of an OTP from restaurant reservation app, OpenTable. The user can enter either their cell phone number or email address and receive a one-time password to login, rather than use the same password every time.

SMS OTP:

An example of an SMS OTP from OpenTable.

Email OTP:

An example of an email OTP from OpenTable.

OTPs offer additional security because:

a) They provide a unique password every single time the user completes a transaction or logs in, therefore the password cannot be discovered and used again.

b) OTPs are stronger and more secure passwords that are made up of random characters compared to user-generated passwords which are often weaker and more predictable.

Types of OTPs

There are three types of OTPs, each of which uses a different method to generate the password. The OTPs can be generated by a security token in the form of a device (hard token) or mobile phone app (soft token), or be delivered via SMS or email.

Time-based one-time passwords (TOTPs)

TOTPs generate new passwords based on the current time which are then usually delivered via an authenticator app (like Google Authenticator, Microsoft Authenticator or Authy) or via a hardware device. 

An example would be the TOTPs used for 2-factor authentication for apps like Facebook or Slack.

An example of a TOTP with an authentication app.

They use two pieces of information to generate the OTP. The first is a static secret key or seed which is known by the user’s token and the authentication server that validates the OTP. The second is the moving factor—in the case of TOTPs, a time-based counter. To calculate the time counter, a Unix timestamp is used along with the pre-set time limit (or timestep) of an OTP (typically 30 or 60 seconds). 

To generate the OTP, the secret key and timestep are input into a cryptographic hash function. The OTP must then be used within the assigned timestep before it becomes invalid.

Graph showing how TOTP works.

Hash-based one-time passwords (HOTPs)

These are also known as HMAC-based one-time passwords, as they use the hash-based message authentication code (HMAC) open-source standard.

A popular example is the Yubico YubiKey, a physical key that individuals can use via USB-C or by tapping against an NFC-enabled device for secure access to accounts.

An example of a physical key that uses hash-based OTPs. Image source: Yubico.

Like TOTPs, HOTPs use a secret key or seed as well as a moving factor. The moving factor differs here though, as it is based on an event-activated counter rather than time-based. The counter is stored in the token and on the server. The counter on the token counts the number of OTPs that are generated when the button on the token is pressed. The counter on the server counts the number of OTPs once each one is validated. This means that HOTPs are not time-limited. 

To generate the hash-based OTP, the secret key and counter are inserted into a one-way cryptographic hash-function that generates the OTP. Unlike TOTPs, it will remain valid until the user requests another OTP that is then validated.

Graph showing how HOTP works.

Transmission-based OTP

This type of OTP implementation is the most common, and one of the easiest ways to set up OTP. It involves generating unique, temporary passwords that are then sent to the user via push notification, text message or email. 

Here’s an example from the food delivery app, Deliveroo.

An example of a transmission-based OTP SMS from Deliveroo.

Transmission-based OTP is easier to implement for developers as there is no need for two separate devices to create and validate the passwords. Password generation and authentication is done by the same server. The most common way to deliver passwords is by SMS.

Note:

Hard vs. soft tokens

Hard tokens are physical devices that generate OTPs such as USB drives, fobs, smart cards and bluetooth devices. An example of a popular OTP hardware provider is Yubico. Soft tokens refer to software that generates OTPs, such as authentication apps like Google Authenticator.

Real-world OTP use cases

Any organization that conducts business or activities online can make its users and internal accounts more secure with OTPs. If you have a system that requires users, customers, or employees to log in, you can use OTPs. Here are a few example use cases. 

Banking 

Security is of the utmost importance in banking and financial services—there’s a lot at stake in the event that an account is compromised. Using OTPs is an excellent way to ensure customers’ account credentials cannot be accessed. In addition to logging in to accounts, OTPs can be used to verify large transactions, loan and credit card applications, account closures, and more. 

E-commerce

For e-commerce stores, one-time passwords don’t just make accounts more secure, they enhance the user experience. Users don’t need to remember or store endless passwords for different e-commerce websites—they can simply enter their email address or phone number and receive a unique, secure password.

SaaS

Software applications can contain huge amounts of sensitive data. Data that—if it gets into the wrong hands—can cause significant ramifications for organizations and their users. OTPs offer a simple solution that can improve SaaS security, removing the potential for human error and preventing brute-force attacks on user accounts.

Healthcare 

Similarly, healthcare providers are guardians of a lot of sensitive information in the form of patient records. Implementing OTPs is one way to protect patients’ data and avoid HIPAA violations

How your business can benefit from OTPs

You’ve probably noticed the widespread use of OTPs from your own online experience. That’s because OTPs are a reliable way to increase security. Let’s take a look at some of the benefits.

1. Prevent replay attacks

A replay attack involves a cybercriminal eavesdropping on a secure network, intercepting a data transmission and then delaying or repeating it. By using this method, hackers can intercept users’ passwords and then use them. OTPs can prevent this from happening as, by the time the cybercriminal attempts to use the password, it is no longer valid. Either because the time limit for the OTP has expired or it has already been used by the end-user and is therefore no longer valid for use. 

2. Improve users’ security practices

Since many users are lax about the strength and security of their passwords, implementing OTPs as an alternative removes the potential for hackers to exploit them. What’s more, using OTPs as part of a multi-factor authentication process helps to override the weakness of bad passwords by adding another layer of security that hackers can’t usually intercept. 

3. Convenient for the end-user

OTPs are an easy and reliable way to protect your user's data and accounts from attack. Additionally, using OTPs makes it easier to manage account access—there’s no need to use bad (albeit memorable) passwords, try to remember stronger passwords, or keep them saved anywhere. Even better, OTPs are completely free for the end-user. 

4. Quick, automated sending

Delivering new, randomly generated OTPs is super quick and painless—there’s no need for users to sit around waiting to log in or complete their purchase. Generating new OTPs via device or app is instant, and with the correct implementation and infrastructure, delivering OTPs via email or SMS is just as fast and seamless. 

5. Compliance with privacy laws

Organizations handling the personal data of customers, users, and employees are required to take adequate measures to ensure an appropriate level of security. Implementing OTPs adds an additional layer of protection that can help them to comply with the relevant privacy laws, such as the GDPR.

Check out our guide on SMS compliance to learn more. 

6. Keep IT admins happy

Password management requires a lot of time and effort to implement and maintain good practices. With OTPs, admins needn’t worry about security for password storage, policies, password rules and timelines, and so on. They can dedicate their time elsewhere while OTP automates everything.

The risks of using OTPs

As with anything online, attackers have also found ways to exploit certain mobile network vulnerabilities to gain access to things such as OTPS. This doesn’t mean you should avoid them! Rather, just be aware of the types of cyber threats revolving around OTPs and take measures to prevent them.

SMS

  • Sim swapping: Mobile service providers are very easily able to port phone numbers to different sims. Attackers exploit this ability by contacting the phone number owner and using social engineering to gain information about them. They will then contact the user’s mobile service provider and use the information they gained to try and convince the provider that they have lost their phone and need their number to be ported to a different device. These types of attacks rely on users falling victim to the scam.

  • SS7 flaw: SS7 (Signaling System No.7) is an outdated, although still in use, protocol that’s been around since the 70’s. It’s the leading protocol for connecting network communication worldwide—it’s even used by intelligence agencies for surveillance purposes. Attackers use these same surveillance methods to hack the network and eavesdrop on people’s mobile phones. In fact, they can fool the network into believing that the hacker device is the device belonging to the subscriber, allowing them to intercept phone calls and text messages without the real owner knowing. 

  • Push-bombing attacks: This type of attack targets users using multi-factor authentication. Attackers will obtain the user’s account credentials and then attempt to login in many times, bombarding the user with authentication requests. The goal is to overwhelm the user so that they eventually confirm their identity and give the attacker unauthorized access.

Email

  • Phishing and spoofing attacks: A more recent method of phishing attack targets users in an attempt to use social engineering to gain access to their OTPs. A well-known example of this is the Coinbase phishing attack, where hackers sent users spoofed emails with links to fake Coinbase pages that prompted the user to login and enter information, including their OTPs. 

  • Man-in-the-middle attacks: MITM attacks are more effective when email encryption and authentication are not used. They involve the attacker intercepting the data exchange between two parties, and stealing information, such as account credentials. 

How to set up OTPs with MailerSend

With MailerSend, you can easily send OTPs via SMS and email thanks to our developer-friendly APIs. Let’s take a look at how to set up both.

First, in order to have the one-time password, you'll need to create a function to generate a random number and add a validity timeframe to the function. You'll also need to create the function to validate the OTP when the user enters it.

Once you’re done, you can choose between sending the OTP via email or text:

Set up OTP emails

Send an email using one of your templates—remember the sending instructions are available under the template settings!

Be sure to include a variable containing your random number like {{otp}}. You can then use the following code to send an HTML email:

{
   "from":{
      "email":"hello@{{sendingdomain}}",
      "name":"Awesome Company"
   },
   "to":[
      {
         "email":"jane@mailersend.com"
      }
   ],
   "subject":"Your {{company}} verification code",
   "html":"<b>Hi {{name}}!</b>
   	 <br>
   	 <br>To help us make sure it's really you, here's the verification code you'll need to log in:
   	 <br>
   	 <b>{{otp}}</b>.
<br>
   	 <br>
   	 If this wasn't you logging in, and you use a password to log in, please reset your password. To further secure your account, please set up two-step authentication.
   	 <br>
   	 This code will expire in <b>1 hour</b>. Once the code expires, you will need to request a new verification code by going through the login procedure again",
   "personalization":[
      {
         "email":"agathe+1@mailersend.com",
         "data":{
            "company":"MailerSend",
            "name":"Jane",
            "otp":"1234567890"
         }
      }
   ]
}

Set up OTP SMS

You can follow the same method to send an SMS, using the following code:

{
   "from":"+18332947701",
   "to":[
      "+18332403627"
   ],
   "text":"Hey {{name}}! Your {{company}} verification code is {{otp}}. ",
   "personalization":[
      {
         "phone_number":"+18332403627",
         "data":{
            "name":"Jane",
            "otp":"1234567890"
         }
      }
   ]
}

Make sure you have a field on your login page that appears when the user enters their email address so that they can enter the one-time password.

Developer resources for sending emails and SMS messages

Guides for sending emails:

Guides for sending SMS:

Official API documentation:

OTP for a secure, reliable user experience

OTPs are more than just another type of transactional message you can send your recipients. It’s a way to improve security for your business and users, and provide a better, more professional customer experience. Whether you’ve experienced a breach or not, implementing some form of OTP, either for login, transaction verification or MFA, is a must for businesses that prioritize security.

Will you be using MailerSend to send OTP emails or text messages to your users? Tell us about your use case in the comments!

Start using OTPs now!

Sign up to MailerSend’s transactional messaging service to start sending OTP SMS and emails. Get 3,000 emails free or upgrade to get SMS, more emails and advanced features.

Amy Elliott
I’m Amy, Content Writer at MailerSend. As a child, I dreamt about writing a book and practiced by tearing pages from an A4 notepad and binding them with sugar paper. The book is pending but in the meantime, I love taking a deep dive into technical topics and sharing insights on email metrics and deliverability.