How to generate passwords in Python 2 and Python 3? Safely?

Here on Stackoverflow there is at least one message related to this topic: Generate password in python

You may find that this topic has found some critics even in PEP. It is mentioned here: https://www.python.org/dev/peps/pep-0506/

So, how to generate random passwords correctly and safely in Python 2 and Python 3?

+4
source share
1 answer

Python 2

, random Python 2 . : " ".

random , "", ( ), . , . , : https://jazzy.id.au/2010/09/22/cracking_random_number_generators_part_3.html

Python 2 os.urandom SystemRandom, , .

, , . os.urandom Linux /dev/urandom. /dev/urandom, /dev/random. , , /dev/random.

Python 2 :

import os

def gen_password(length=8, charset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()"):
    random_bytes = os.urandom(length)
    len_charset = len(charset)
    indices = [int(len_charset * (ord(byte) / 256.0)) for byte in random_bytes]
    return "".join([charset[index] for index in indices])

Python 3

Python 3.6 secrets. PEP-0506 '. - " ", "-" . API .

Python 3.

import secrets

def gen_password(length=8, charset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()"):
    return "".join([secrets.choice(charset) for _ in range(0, length)])
+5

Source: https://habr.com/ru/post/1668458/


All Articles