春江暮客

春江暮客的个人学习分享网站

Python Random Strong Password Generator

2018-12-18 Miscellaneous
Python Random Strong Password Generator

For security, it is better to use different strong passwords on different websites. The annoying part is that creating a new strong password manually every time is inconvenient, so a small generator script is much easier.

One important detail, though: if the password is meant for a real security use case, it is better to rely on stronger randomness sources than ordinary pseudo-random helpers.

random

Python code as follows

import secrets
import string

def get_strong_pass(length=16):
    alphabet = string.ascii_letters + string.digits + "_#-"
    return "".join(secrets.choice(alphabet) for _ in range(length))

print(get_strong_pass())

Compared with random.choice(), secrets.choice() is the more appropriate option for passwords, tokens, and other security-related strings.

Next, you can call this function inside Django if needed. Below is also a browser-side JavaScript version, but it should use a stronger randomness source as well.

JavaScript code


<script>
function createPassword(min,max) {
        // Arrays used for generating random passwords
        var num = ["0","1","2","3","4","5","6","7","8","9"];
        var english = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
        var ENGLISH = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
        var special = ["-","_","#"];
        var config = num.concat(english).concat(ENGLISH).concat(special);

        // Ensure at least one from each group exists
        var arr = [];
        arr.push(getOne(num));
        arr.push(getOne(english));
        arr.push(getOne(ENGLISH));
        arr.push(getOne(special));

        // Get the desired password length
        var len = min + Math.floor(Math.random()*(max-min+1));

        for(var i=4; i<len; i++){
            // Pick a random character from the config array
            arr.push(config[Math.floor(Math.random()*config.length)]);
        }

        // Shuffle the array
        var newArr = [];
        for(var j=0; j<len; j++){
            var randomIndex = getSecureInt(arr.length);
            newArr.push(arr.splice(randomIndex,1)[0]);
        }

        // Randomly pick one value from an array
        function getOne(arr) {
            return arr[getSecureInt(arr.length)];
        }

        function getSecureInt(max) {
            var randomArray = new Uint32Array(1);
            window.crypto.getRandomValues(randomArray);
            return randomArray[0] % max;
        }

        return newArr.join("");
    }
document.write(createPassword(15,15));
</script>

Strong password is here

For a demo page, this is already enough. For long-term real-world use, it is still better to generate passwords locally and store them in a proper password manager.

友情链接

其它