Skip to content

Commit e6f0387

Browse files
Create passwords.md
1 parent 40256a5 commit e6f0387

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

recipes/python/passwords.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Passwords
2+
3+
Here `secrets.choice` is used for cryptographically strong random generation.
4+
5+
## One-liner for the shell
6+
7+
```sh
8+
$ python -c "import secrets, string; print(''.join(secrets.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(20)))"
9+
```
10+
11+
## Python script
12+
13+
```python
14+
#!/usr/bin/env python3
15+
16+
import secrets
17+
import string
18+
19+
DEFAULT_LENGTH = 20
20+
CHAR_SET = string.ascii_letters + string.digits + string.punctuation
21+
22+
def create_password(length=DEFAULT_LENGTH, char_set=CHAR_SET):
23+
"""
24+
Generate a secure, random password of a specified length and set of characters.
25+
"""
26+
return ''.join(secrets.choice(char_set) for i in range(length))
27+
28+
29+
if __name__ == "__main__":
30+
generated_password = create_password()
31+
print(generated_password)
32+
```

0 commit comments

Comments
 (0)