Generating a secure random 6 digit PIN via script

richardyaxl
Tera Expert

I have previously used math.random() to generate a 6 digit numeric PIN, however I am trying to find a more secure way of doing this. I came across the GlideSecureRandomUtil API and see it is possible to generate a random 6 digit alphanumeric PIN by using the below: 

GlideSecureRandomUtil.getSecureRandomString(6)


Looking at the available methods for GlideSecureRandomUtil the only way I could think of achieving this was by generating a random number between 0-9 six times, and then concatenate them together like below, but this doesn't seem very efficient(?)

var result = '';
for (var i = 0; i < 6; i++) {
    result += GlideSecureRandomUtil.getSecureRandomIntBound(9);
}
gs.info(result);


Does anyone know if there is a more efficient alternative for generating a 6 digit numeric PIN, or have any recommendations?

 

1 ACCEPTED SOLUTION

@richardyaxl 

try this

var pin = GlideSecureRandomUtil.getSecureRandomIntBound(1000000); // 0 to 999999
pin = pin.toString().padStart(6, '0');
gs.info(pin);

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

4 REPLIES 4

Ankur Bawiskar
Tera Patron
Tera Patron

@richardyaxl 

try this

var min = 100000;
var max = 999999;
var pin = GlideSecureRandomUtil.getSecureRandomIntBound(max - min + 1) + min;
gs.info(pin);

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hey @Ankur Bawiskar,

Thanks for your response. This is a helpful as it prevents the need for multiple API calls which is what I didn't like about my solution. However, your solutions means the PIN cannot start with 0, meaning there are less possible PIN options. Ideally, I would still like it to be possible for the pin to be 012345, for example.

Thanks

Rich

@richardyaxl 

try this

var pin = GlideSecureRandomUtil.getSecureRandomIntBound(1000000); // 0 to 999999
pin = pin.toString().padStart(6, '0');
gs.info(pin);

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Thanks @Ankur Bawiskar,

That gives me exactly what I need and is much more efficient than looping through the API 6 times! I appreciate your help.