How to generate OTP Number with 6 digits

后端 未结 9 1972
小蘑菇
小蘑菇 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:14

    I have the same difficulty to find simple rule about it.

    There are a lot of content explaining about OTP like "Time Synchronized" etc..., however I was looking for a simple solution while keeping the system's security.

    In my case I keep the 2FA (Two Factor Authentication), that already gives a lot of security.

    A relevant info about JAVA for random generator (see: SecureRandom) Important if you want a unique number generation, avoiding repeats.

    Examples:

    https://www.securecoding.cert.org/confluence/display/java/MSC02-J.+Generate+strong+random+numbers

    Details about it: http://resources.infosecinstitute.com/random-number-generation-java/

    Based on examples above I implemented the following snippet:

    public class SimpleOTPGenerator {
    
    
        protected SimpleOTPGenerator() {
        }
    
        public static String random(int size) {
    
            StringBuilder generatedToken = new StringBuilder();
            try {
                SecureRandom number = SecureRandom.getInstance("SHA1PRNG");
                // Generate 20 integers 0..20
                for (int i = 0; i < size; i++) {
                    generatedToken.append(number.nextInt(9));
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
    
            return generatedToken.toString();
        }
    }
    

提交回复
热议问题