-1

Generate 8 digit OTP in java with first digit as zero. I have tried with Math() function in Java but it gives random numbers first digit without zero. Suggest me an easiest way to achieve the same

Yogeshivu N
  • 5
  • 1
  • 7
  • 1
    generate a 7 digit one and add a zero as first digit (there is no `Math()` function in standard Java) – user85421 Feb 19 '20 at 10:58
  • Its difficult to maintain the length if you are adding zero as first letter. Using format, you can do this. – chetan R M Feb 19 '20 at 11:03
  • @Martijn Pieters i had a request for 8 digit OTP with 0 as the first digit. even though it is marked as duplicate – Yogeshivu N Mar 11 '20 at 07:00
  • @YogeshivuN you marked an answer as accepted that did nothing but point to the other question. *You and your colleague together made this a duplicate*. – Martijn Pieters Mar 11 '20 at 07:49

2 Answers2

3

You should be using SecureRandom. Refer https://stackoverflow.com/a/11052736/1776132

String.format("%08d", new SecureRandom().nextInt(10_000_000))
Smile
  • 3,832
  • 3
  • 25
  • 39
2
static final LENGHT = 8;

Random randomizer = new Random();
StringBuilder builder = new StringBuilder();
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();

EDIT

As Smile mentioned, using SecureRandom would be better choice.

static final LENGHT = 8;

SecureRandom randomizer = new SecureRandom();
StringBuilder builder = new StringBuilder();
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();

If you want first digit as zero always;

static final LENGHT = 7;

SecureRandom randomizer = new SecureRandom();
StringBuilder builder = new StringBuilder("0");
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();
Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30