How to generate OTP Number with 6 digits

后端 未结 9 1959
小蘑菇
小蘑菇 2020-12-30 17:24

What is an OTP number in a login authentication system? Is there any specific algorithm for generating OTP numbers using java (android). Or is an OTP something like random n

9条回答
  •  独厮守ぢ
    2020-12-30 18:26

    Java 8 introduced SplittableRandom in it's java.util package. You can use it's nextInt(int origin, int bound) to get a random number between the specified bound.

    StringBuilder generatedOTP = new StringBuilder();
    SplittableRandom splittableRandom = new SplittableRandom();
    
    for (int i = 0; i < lengthOfOTP; i++) {
    
        int randomNumber = splittableRandom.nextInt(0, 9);
        generatedOTP.append(randomNumber);
    }
    return generatedOTP.toString();
    

    But I will recommend to use SecureRandom class. It provides a cryptographically strong random number and available in the package java.security.

    StringBuilder generatedOTP = new StringBuilder();
    SecureRandom secureRandom = new SecureRandom();
    
    try {
    
        secureRandom = SecureRandom.getInstance(secureRandom.getAlgorithm());
    
        for (int i = 0; i < lengthOfOTP; i++) {
            generatedOTP.append(secureRandom.nextInt(9));
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    
    return generatedOTP.toString();
    

    You may get more info from Java 8- OTP Generator

提交回复
热议问题