-1

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.

4 Answers4

5

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

rwx
  • 696
  • 8
  • 25
1

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.

Community
  • 1
  • 1
0

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
MLSC
  • 5,872
  • 8
  • 55
  • 89
-1

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