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
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();
}
}
public static void main(String []args){
java.util.Random r=new java.util.Random();
int otp = r.nextInt(1000000); // no. of zeros depends on the OTP digit
System.out.println(otp);
}
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