Generating OTP in Java

Java Programming Java 8Object Oriented Programming

Generate OTP is now a requirement on most of the website now-a-days. In case of additional authentication, system generates a OTP password adhering to OTP policy of the company. Following example generates a unique OTP adhering to following conditions −

  • It should contain at least one number.
  • Length should be 4 characters.

Example

import java.util.Random;

public class Tester {
   public static void main(String[] args) {

      System.out.println(generateOTP(4));
   }

   private static char[] generateOTP(int length) {
      String numbers = "1234567890";
      Random random = new Random();
      char[] otp = new char[length];

      for(int i = 0; i< length ; i++) {
         otp[i] = numbers.charAt(random.nextInt(numbers.length()));
      }
      return otp;
   }
}

Output

6674
raja
Published on 14-Aug-2018 07:58:48
Advertisements