forked from akheron/diceware.py
/
diceware.py
executable file
·270 lines (219 loc) · 9.9 KB
/
diceware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python
"""Diceware passphrase generator
Diceware passphrase generator generates passphrases by reading random
data from the operating system random number generator and using it to
index the Diceware word list, supplied by user or automatically
downloaded from the Diceware web page. For more information on
Diceware, see the Diceware web page:
http://world.std.com/~reinhold/diceware.html
"""
__license__ = """
Copyright (c) 2008, 2009 Petri Lehtinen <petri@digip.org>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from math import log, ceil
from optparse import OptionParser
from ConfigParser import SafeConfigParser, NoOptionError, NoSectionError
from random import SystemRandom
import sys
import os
import os.path
import urllib
SPECIAL_CHARS = "~!#$%^&*()-=+[]\{}:;\"'<>?/0123456789"
WORD_LIST_URLS = {
"en": "http://world.std.com/~reinhold/diceware.wordlist.asc",
"fi": "http://www.iki.fi/kaip/noppaware/noppaware.txt",
"it": "http://www.taringamberini.com/download/diceware_it_IT/" +
"word_list_diceware_in_italiano.txt",
"se": "http://x42.com/diceware/diceware-sv.txt",
"tr": "http://dicewaretr.110mb.com/diceware_tr.txt",
"nl": "http://theworld.com/~reinhold/DicewareDutch.txt",
}
def generate_grid(word_list, words=5, specials=0):
longest_word_length = 0
result = []
for _ in range(words):
word_row, with_specials = generate(word_list, words, specials)
if specials:
result.append(with_specials)
else:
result.append(word_row)
# Assume word_row and with_specials contain equal length words
long_word_length = max(len(x) for x in word_row)
longest_word_length = max(long_word_length, longest_word_length)
return result, longest_word_length
def generate(word_list, words=5, specials=0):
rnd = SystemRandom()
words = [ rnd.choice(word_list) for _ in range(words) ]
# Insert at most options.special special characters. This is not
# exactly the procedure described in the Diceware web page, because
# this handles the case where there are more than 6 words in the
# passphrase and more than 6 characters in the word.
if specials:
split_words = [ map(None, x) for x in words ]
for _ in range(specials):
# i is the index of the word in which the special character
# replacement takes place.
i = rnd.randrange(len(split_words))
# j is the index of the character to be replaced with a special
# character.
j = rnd.randrange(len(split_words[i]))
# k is the index of the special character
k = rnd.randrange(len(SPECIAL_CHARS))
# Split to individual characters, replace the k'th char, unsplit
split_words[i][j] = SPECIAL_CHARS[k]
with_specials = [ "".join(x) for x in split_words ]
else:
with_specials = words
return words, with_specials
def select_word(placeholder):
return generate(open('uwords.' + placeholder, 'r').readlines(), words=1, specials=0)[0][0][:-1]
def read_word_list(fobj):
# Read the word list skipping lines which do not start with 5 digits
# and a white space character and removing the 5 digits
word_list = [ line[6:].strip() for line in fobj
if line[0:5].isdigit() and line[5].isspace() ]
# A valid Diceware word list has exactly 6**5 = 7776 words
if len(word_list) != 7776:
raise ValueError("invalid word list format")
return word_list
def get_word_list(cache_dir, lang="en"):
assert lang in WORD_LIST_URLS.keys()
# Read the cached word list
word_list_path = os.path.join(cache_dir, lang)
try:
fobj = open(word_list_path)
except IOError:
# The word list does not exist => cache it
word_list_url = WORD_LIST_URLS[lang]
urllib.urlretrieve(word_list_url, word_list_path)
fobj = open(word_list_path)
return read_word_list(fobj)
def main():
def ensure_dir(path):
"""Ensure that path is a directory creating it if necessary.
If path already exists and is not a directory, print an error
message and quit with sys.exit().
Parameters:
path String specifying the path to ensure
Return value:
path
"""
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
print("error: '%s' is not a directory" % path)
sys.exit(1)
return path
def config_default(config, section, option, default):
"""Set default values for options that do not have a value."""
try:
config.get(section, option)
except NoSectionError:
config.add_section(section)
config.set(section, option, default)
except NoOptionError:
config.set(section, option, default)
config_dir = ensure_dir(os.path.expanduser("~/.diceware.py"))
cache_dir = ensure_dir(os.path.join(config_dir, "cache"))
# Parse config file
config_file = os.path.join(config_dir, "config")
config = SafeConfigParser()
config.read(config_file)
config_default(config, "defaults", "lang", "en")
config_default(config, "defaults", "words", "5")
config_default(config, "defaults", "special", "0")
config_default(config, "defaults", "file", "")
config_default(config, "defaults", "separator", " ")
# Sanity checks for config options
if config.get("defaults", "lang") not in WORD_LIST_URLS.keys():
print("error: '%s' is not a valid value for option 'lang'"
% config.get("defaults", "lang"))
sys.exit(1)
try:
config.getint("defaults", "words")
config.getint("defaults", "special")
except ValueError:
print("error: 'words' and 'special' options must have integer values")
sys.exit(1)
# Parse command line arguments
parser = OptionParser()
parser.add_option("-g", "--grid", dest="grid", action="store_true",
help="Instead of a single line, generate NxN grid of "+
"words. This makes eavesdropping harder")
parser.add_option("-n", "--words", dest="words", type="int", metavar="N",
help="generate N words (default: %default)",
default=config.getint("defaults", "words"))
# todo: blend this template option with regular style here
parser.add_option("-t", "--template", dest="template",
default=["adj", "noun", "adv", "verb", "noun", "adv", "verb"])
parser.add_option("-s", "--special", dest="special", type="int", metavar="M",
help="insert M special characters (default: %default)",
default=config.getint("defaults", "special"))
parser.add_option("-f", "--file", dest="file", metavar="FILE",
help="override the `lang' option and read the word list " +
"from FILE", default=config.get("defaults", "file"))
parser.add_option("-p", "--separator", dest="separator", type="string", metavar="P",
help="specify the separator between words (default: %default)",
default=config.get("defaults", "separator"))
linguas = sorted(WORD_LIST_URLS.keys())
parser.add_option("-l", "--lang", dest="lang", metavar="LANG",
type="choice", choices=linguas,
help="use the word list for LANG (" + ", ".join(linguas) +
") (default: %default)", default=config.get("defaults", "lang"))
options, args = parser.parse_args()
if args or options.words < 1 or options.special < 0:
parser.print_help()
sys.exit(0)
parser.destroy()
# todo change this hack
if options.template:
print options.template
words = []
for placeholder in options.template:
words.append(select_word(placeholder))
print ' '.join(words)
sys.exit(0)
# --file has higher precedence than --lang
if options.file:
try:
fobj = open(options.file)
except IOError:
print("error: unable to open word list file '%s'" % options.file)
sys.exit(1)
try:
word_list = read_word_list(fobj)
except ValueError, e:
print("error: %s" % e)
sys.exit(1)
else:
word_list = get_word_list(cache_dir, options.lang)
if not options.grid:
words, with_specials = generate(word_list, options.words,
options.special)
print("passphrase : %s" % options.separator.join(words))
if options.special > 0:
print("with specials: %s" % options.separator.join(with_specials))
else:
words, length = generate_grid(word_list, options.words,
options.special)
for word_row in words:
print " ".join([word.ljust(length) for word in word_row])
if __name__ == "__main__":
main()