[英]python - random string generator _help_
這是一個愚蠢的問題...說實話,我目前還沒有任何線索,並且是python的新手...
我目前正在用python腳本破壞頭以生成隨機密碼。 我發現從一個良好的開端這里例如通過“奧米德拉哈”
編輯: 在revist上,此示例對於似乎具有執行相同任務的更簡單方法的某些事情而言,已遠遠不復雜...
import random
import hashlib
import time
"""
This script is adapted from an example found here:https://stackoverflow.com/questions/18319101/whats-the-best-way-to-generate-random-strings-of-a-specific-length-in-python ; originally provided by user 'Omid Raha'
"""
SECRET_KEY = 'ffdsat9asdf5o5u9HKHvurtiasdf1tg1V36jyasdfSv8Ppin9O'
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
'%*/-_@'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
print (get_random_string)
只需返回:
<function get_random_string at 0x1034f7848>
我不知道這意味着什么...或者我是否正確執行了腳本。
編輯:
謝謝你的閱讀
跌跌撞撞...發現了這一點:
from OpenSSL import rand
p = rand.seed("lolNOmoreBADpasswds12")
print(p)
那:
import os, random, string
length = 12
chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random.seed = (os.urandom(1024))
print ''.join(random.choice(chars) for i in range(length))
和另一個:
from OpenSSL import rand
p = rand.bytes("12")
print(p)
玩這樣的事情,那個,和其他的... :)
編輯: 以上所有方法都很爛
鑒於: xkcd岩石
假設您有一個包含所有要包含的單詞字符串的文件,那么可以考慮將其視為最佳的前進路徑(對於令人難以忘懷的隨機密碼生成器) :
import random, string, os
word_file = "./wordlist"
words = open(word_file).read().splitlines()
part1 = random.choice(words)
part2 = random.choice(words)
part3 = random.choice(words)
part4 = random.choice(words)
phrase = part1.capitalize()+part2+part3.capitalize()+part4
print phrase
我知道的最簡單的隨機字符串生成器:
import random, string;
all_chars = string.ascii_lowercase
def randstr(length):
result = str()
for i in range(length):
result += random.choice(all_chars)
return(result)
print(randstr(15))
如果要更改可能的字符數,只需更改all_chars變量:
例如:
如果需要數字和字符:
all_chars = string.ascii_lowercase + string.digits
對於數字以及大小寫字符:
all_chars = string.ascii_letters + string.digits
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.