使用质数生成随机密码

3

我正在进行一项大学项目,起初是要在两个给定输入之间打印出所有的质数。后来有人告诉我它必须与我所学的网络管理课程相关,因此我想在我的脚本末尾添加一个密码生成器(用于网络安全)。

我已经编写了所有的代码,但我有一个问题,它不能使用我打印出的质数列表中的随机质数。它只使用最后一个打印的数字,我理解原因,但是否有任何方法可以使其使用随机质数,或者我需要将数字存储在其他地方?

#A program to count the prime numbers from a given start to a given end


#importing math function
import math
import os, random, string
#Input the number to start counting from
Starting_number = input("Enter the starting number: ")




#Input the number to end the count on.
Ending_number = input("Enter the number you want to count up to: ")

#if Starting_number is less than 0 it will print out a suitable message.
if Starting_number < 0:
    print 'Invalid entry, please enter a positiv number. \nWill count from ',Starting_number, 'to 0 and begin prime number count to',Ending_number, '.'

#If Ending_number is less than or equals to 0 then it will print out a suitable message.
if Ending_number <= 0:
    print 'Invalid entry on last input \nPlease enter two positive numbers for the count to work.'

#Starting loop as long as the current count is between Starting_number and Ending_number
for num in range(Starting_number, Ending_number):

    #
    if all(num%i !=0 for i in range(2,num)):

        print num





if num >= 1 and num <= 100:
    length = 4
    chars = string.ascii_letters + string.digits + '!@#$%^&*()'
    random.seed = (os.urandom(1024))

    print ''.join(random.choice(chars) for i in range(length))


if num >= 101 and num <= 200:
    length = (Ending_number / Starting_number) * 5 + 11
    if length >= num:
        length = num / 100
    chars = string.ascii_letters + string.digits + '!@#$%^&*()'
    random.seed = (os.urandom(1024))

    print ''.join(random.choice(chars) for i in range(length))

1
避免在Python2中使用input。它不会将数字作为输入。它会执行Python代码。如果您尝试在提示输入起始数字时输入[1,2,3],则会看到意外的错误。此外,用户可能会插入诸如__import__("os").system("kill my machine command")之类的内容,这可能会导致非常糟糕的后果。要请求整数,请使用int(raw_input(...))。对于浮点数,请使用float(raw_input(...))。在Python3中,名为input的函数实际上是raw_input,因此您仍然需要添加int(..)调用。 - Bakuriu
2个回答

2
当您检测到质数时,请将它们添加到列表中。不仅如此,而是...
print num

将其添加到列表中,如下所示:
primes.append(num)

然后,您可以从“primes”列表中选择一个随机项:
from random import choice
print choice(primes)

1
我真的很想把这个作为评论添加,但我没有足够的积分来添加评论。对于密码生成器,您不希望它成为质数。你应该随机选择一个数字。如果您有一个32位数字,则如果数字在完整的32位空间中是随机的,则具有更多的熵。如果您仅限于质数,那么您已经大大减少了空间。虽然与您所问的内容没有直接关联,但这可能是有用的信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接