I want to build python algorithm that generates 6 digits pin code. I had many ideas like : based on time, on id .... etc, but non sounded secure once the algorithm is exposed. Now I am trying to generate that using random.randint(a, b)
, however I want to know how it really works and python documentation don't provide much about it. So can you please provide more about this or any other suggestions to generate 6 digits pin code.

- 25
- 1
- 6
-
Do you mean how it randomly picks the numbers or how to use the function? – Mark Skelton Feb 22 '16 at 11:12
-
You can find out yourself how it works, by looking into the [source code](https://github.com/python/cpython/blob/3.5/Lib/random.py#L214-L218). – Artjom B. Feb 22 '16 at 11:51
4 Answers
This method will return you by default a 6 number sized string and if you pass in a value as many numbers as you passed in.
import string
import random
def id_generator(size=6, chars=string.digits):
return ''.join(random.choice(chars) for x in range(size))
print(id_generator())
123123
print(id_generator(10))
1234512345

- 696
- 8
- 25
-
I tried to call the functions many times, it gives a number for some and "None" on the other – Yazan Housheih Feb 22 '16 at 11:40
-
The easiest way to securely implement this is to use the operating system's random number generator(random.SystemRandom() or os.urandom(n)) to generate your digits. The official documentation has a nice big warning against using the default generator.
The one caveat is that SystemRandom() apparently doesn't work on all systems, though from what I can tell no one's quite sure what systems don't support it.
other than that, random.SystemRandom().randint() should work just fine.

- 1
- 1

- 11
- 4
You can try this as a very simple solution:
#!/usr/bin/env python
from random import choice
from string import digits
code = list()
for i in range(6):
code.append(choice(digits))
print ''.join(code)
Output something like:
455799

- 5,872
- 8
- 55
- 89
You can always use the direct approach, although this is more like Fortran than Python. You can also repurpose this as a key generator.
import random
def pin_code(n)
pin = []
for i in range(n):
pin.append(random.randint(0,9))
print(*pin, sep='')

- 1
- 1
-
1This isn't really helping, as OP question is mainly about security concerns of using `random.randint`. – Diane M May 12 '19 at 02:52