Score:1

How to generate a random string in Python for a mission-critical application

kr flag

I'm trying to figure something out, but it is difficult for me. I need to generate a fully random string in Python. My current function is attached below. I just want to know whether this is secure and good for the project that I'm working on, a cryptocurrency type of website.

import random
import string

def get_random_string(length):
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    print(result_str)
Paul Uszak avatar
cn flag
How long a string, and how many? Randomness is a function of sample size. So for ONE key, just make it up: https://crypto.stackexchange.com/a/74833/23115
Score:3
ng flag

the Random module uses a cryptographically insecure PRG (Mersenne Twister). You want the Secrets module (documentation here), which uses urandom on Linux, or CryptGenRandom() on Windows. In fact, I believe the following code should work (but have not verified it):

from secrets import choice
import string

def get_random_string(length):
    result_str = ''.join(choice(string.ascii_letters) for i in range(length))
    print(result_str)

If you are implementing things where misimplementation may cost you money in any way, I would suggest learning about practical cryptography before proceeding (as it is very easy to make small mistakes that can be a big pain). There are a variety of books people like, for example Cryptography Engineering.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.