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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
|
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# This software is hereby released into public domain. Use it wisely.
#
# ElsieFour (LC4) and its enhancement LS47
# version 2.7: 2018-02-13
#
# - Python script for LS47 originally written by Mirek Kratochvil (2017)
# See https://github.com/exaexa/ls47
# - Python 3 port by Bernhard Esslinger / AK (Feb 2018)
# See www.mysterytwisterc3.org
# - New options by CrypTool project (www.cryptool.org) (Feb 2018) in order to
# support both ciphers LC4 and LS47, both ways to deal with nonces, keyword
# usage for both LC4 and LS47, reading from file and commandline, and
# extended test outputs.
#
# Sample calls:
# - Using cipher LC4, enforced with option -6:
# python lc4-ls47.py -6 -ws thisismysecretkey -es its_my_fathers_son_but_not_my_brother -v -nl 6
# python lc4-ls47.py -6 -ws thisismysecretkey -ds q6xojffkncfyz#f5czs49#3mbsco#2iscvbnm#bymaf -v -nl 6
# - Using cipher LS47, enforced with option -7:
# python lc4-ls47.py -7 -ws s3cret_p4ssw0rd/31337 -ds y'zbvvs+d2,ky4sy?w(_wkz*7'90v:./s)kcz?mj+gyu8-'h(y,i+v,z+1ws -v -nl 10
# python lc4-ls47.py -7 -ws s3cret_p4ssw0rd/31337 -ds y'zbvvs+d2,ky4sy?w(_wkz*7'90v:./s)kcz?mj+gyu8-'h(y,i+v,z+1ws -v -ns 8y(l._4ct'
#
from __future__ import print_function
import sys
import os
import random
import argparse
version = "v2.7 (2018-02-13)"
letters6 = "#_23456789abcdefghijklmnopqrstuvwxyz"
letters7 = "_abcdefghijklmnopqrstuvwxyz.0123456789,-+*/:?!'()"
def missing_letters(s,t):
return ''.join(sorted(set(c for c in s if c not in t)))
def check_key(key):
illegal = missing_letters(key,letters)
missing = missing_letters(letters,key)
duplicates = ''.join(sorted(c for c in letters if key.count(c)>1))
errors = []
if illegal: errors.append( "Key contains illegal letters: '%s'" % illegal )
if missing: errors.append( "Key misses some letters: '%s'" % missing )
if duplicates: errors.append( "Key contains duplicate letters: '%s'" % duplicates )
if errors:
errors.append( "The key must be a permutation of the alphabet: %s" % letters )
raise ValueError("\n".join(errors))
def check_nonce(nonce):
illegal = missing_letters(nonce,letters)
if illegal:
raise ValueError("Nonce contains illegal letters: '%s'" % illegal)
def check_plaintext(s):
illegal = missing_letters(s,letters)
if illegal:
raise ValueError("Plaintext contains illegal letters: '%s'" % illegal)
def check_ciphertext(s):
illegal = missing_letters(s,letters)
if illegal:
raise ValueError("Ciphertext contains illegal letters: '%s'" % illegal)
def find_ix(letter):
m = [l[1] for l in tiles if l[0] == letter]
if len(m) != 1:
raise ValueError("Letter '%c' not in the alphabet!" % letter)
return m[0]
def find_pos(key, letter):
p = key.find(letter)
if not (0 <= p < size * size):
raise ValueError("Letter '%c' not in key?!" % letter)
return (p // size, p % size)
def add_pos(a, b):
return ((a[0] + b[0]) % size, (a[1] + b[1]) % size)
def sub_pos(a, b):
return ((a[0] - b[0]) % size, (a[1] - b[1]) % size)
def find_at_pos(key, coord):
return key[coord[1] + coord[0] * size]
def rotate_right(key, row, n):
mid = key[size * row:size * (row + 1)]
return key[:size * row] + mid[-n:] + mid[:-n] + key[size * (row + 1):]
def rotate_down(key, col, n):
lines = [key[i * size:(i + 1) * size] for i in range(size)]
lefts = [l[:col] for l in lines]
mids = [l[col] for l in lines]
rights = [l[col + 1:] for l in lines]
mids = mids[-n:] + mids[:-n]
return ''.join(lefts[i] + mids[i] + rights[i] for i in range(size))
def rotate_marker_right(m, row, n):
if m[0] != row:
return (m[0], m[1])
else:
return (m[0], (m[1] + n) % size)
def rotate_marker_down(m, col, n):
if m[1] != col:
return (m[0], m[1])
else:
return ((m[0] + n) % size, m[1])
def derive_key(password):
i = 0
k = letters
for c in password:
(row, col) = find_ix(c)
k = rotate_down(rotate_right(k, i, col), i, row)
i = (i + 1) % size
return k
def encrypt(plaintext):
global key, mp
ciphertext = ''
for p in plaintext:
pp = find_pos(key, p)
mix = find_ix(find_at_pos(key, mp))
cp = add_pos(pp, mix)
c = find_at_pos(key, cp)
ciphertext += c
key = rotate_right(key, pp[0], 1)
if marker_mode==1: mp = rotate_marker_right(mp, pp[0], 1)
cp = find_pos(key, c)
key = rotate_down(key, cp[1], 1)
if marker_mode==1: mp = rotate_marker_down(mp, cp[1], 1)
mp = add_pos(mp, find_ix(c))
return ciphertext
def decrypt(ciphertext):
global key, mp
plaintext = ''
for c in ciphertext:
cp = find_pos(key, c)
mix = find_ix(find_at_pos(key, mp))
pp = sub_pos(cp, mix)
p = find_at_pos(key, pp)
plaintext += p
key = rotate_right(key, pp[0], 1)
if marker_mode==1: mp = rotate_marker_right(mp, pp[0], 1)
cp = find_pos(key, c)
key = rotate_down(key, cp[1], 1)
if marker_mode==1: mp = rotate_marker_down(mp, cp[1], 1)
mp = add_pos(mp, find_ix(c))
return plaintext
def create_random_nonce(size):
return ''.join(random.choice(letters) for i in range(size))
def encrypt_with_nonce(plaintext):
global nonce, nonce_enc
ciphertext = encrypt(nonce + plaintext)
nonce_enc = ciphertext[:nonce_size]
if nonce_mode==1:
return nonce + ciphertext[nonce_size:]
else:
return ciphertext
def decrypt_with_nonce(ciphertext):
global nonce, nonce_enc
if nonce_mode==1:
nonce = ciphertext[:nonce_size]
nonce_enc = encrypt(nonce)
return decrypt(ciphertext[nonce_size:])
else:
plaintext = decrypt(ciphertext)
nonce = plaintext[:nonce_size]
nonce_enc = ciphertext[:nonce_size]
return plaintext[nonce_size:]
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def printinfo(enc=False):
eprint('CIPHER : ' + ("LC4" if size==6 else "LS47"))
eprint('ALPHABET : ' + letters)
if args.keywordstring:
eprint('KEYWORD : ' + args.keywordstring)
eprint('KEY : ' + initialkey) # key variable modified during process?
eprint('NONCE : ' + nonce)
eprint('NONCE ENC : ' + nonce_enc)
eprint('NONCEMODE : ' + ("Kaminsky" if nonce_mode==1 else "Kratochvil"))
eprint('MARKER : ' + ("Kaminsky" if marker_mode==1 else "Kratochvil"))
if enc:
eprint('PLAINTEXT : ' + plaintext)
eprint('CIPHERTEXT: ' + ciphertext)
else:
eprint('CIPHERTEXT: ' + ciphertext)
eprint('PLAINTEXT : ' + plaintext)
def test1(size):
global letters, nonce_mode, marker_mode, tiles, noncelen, nonce, nonce_size, nonce_enc, signature
global ciphertext, plaintext, key, initialkey, mp
if size == 7:
CIPHERNAME = "LS47"
letters = letters7;
nonce_mode = 2
marker_mode = 2
noncelen=10; nonce = create_random_nonce(noncelen)
# nonce = 'dr0+:_pij2' # just a sample for testing fixed nonce
else:
CIPHERNAME = "LC4"
letters = letters6;
nonce_mode = 1
marker_mode = 1
noncelen=6; nonce = create_random_nonce(noncelen)
# nonce = 'pjpm5i' # just a sample for testing fixed nonce
tiles = list(zip(letters, [(x // size, x % size) for x in range(size * size)]))
check_nonce(nonce)
nonce_size = len(nonce)
nonce_enc = ""
print('\n' + CIPHERNAME)
if size == 7:
keyword = 's3cret_p4ssw0rd/31337'; args.keywordstring=keyword
key = derive_key(keyword)
else:
key = letters
initialkey = key
check_key(key)
mp = (0, 0)
if size == 7:
plaintext = 'conflagrate_the_rose_bush_at_six!'
signature = 'peace-vector-3'
else:
plaintext = 'its_my_fathers_son_but_not_my_brother'
signature = '#its_me' # signature = ''
check_plaintext(plaintext)
ciphertext = encrypt_with_nonce(plaintext)
key = initialkey; mp = (0, 0) # initialization again
check_ciphertext(ciphertext)
decryptedtext = decrypt_with_nonce(ciphertext)
print('decrypted text: ' + decryptedtext)
printinfo(True)
args.keywordstring=''
if __name__ == '__main__':
parser = argparse.ArgumentParser()
mgroup = parser.add_mutually_exclusive_group()
parser.add_argument("-v", "--verbose", help="output additional information on stderr", action="count", default=0)
mgroup.add_argument("-6", "--lc4", help="use ElsieFour cipher (6x6 table) (default)", action="store_true")
mgroup.add_argument("-7", "--ls47", help="use LS47 cipher (7x7 table)", action="store_true")
mgroup2 = parser.add_mutually_exclusive_group()
mgroup2.add_argument("-ks", "--keystring", metavar="STRING", help="use STRING as key")
mgroup2.add_argument("-kf", "--keyfile", metavar="FILE", help="read key from FILE")
mgroup2.add_argument("-ws", "--keywordstring", metavar="STRING", help="generate key from keyword STRING", default=None)
mgroup2.add_argument("-wf", "--keywordfile", metavar="FILE", help="read keyword from FILE to generate key", default=None)
mgroup3 = parser.add_mutually_exclusive_group()
mgroup3.add_argument("-nl", "--noncelen", metavar="LENGTH", help="use random nonce of length LENGTH", type=int, default=0)
mgroup3.add_argument("-ns", "--noncestring", metavar="STRING", help="use STRING as nonce")
mgroup4 = parser.add_mutually_exclusive_group()
mgroup4.add_argument("-es", "--encryptstring", metavar="STRING", help="encrypt STRING")
mgroup4.add_argument("-ef", "--encryptfile", metavar="FILE", help="read plaintext from FILE and encrypt it")
mgroup4.add_argument("-ds", "--decryptstring", metavar="STRING", help="decrypt STRING")
mgroup4.add_argument("-df", "--decryptfile", metavar="FILE", help="read ciphertext from FILE and decrypt it")
mgroup4.add_argument("-t", "--test", help="encrypt and decrypt a string with a random nonce and a given key (once with LC4 and once with LS47)", action="store_true")
mgroup5 = parser.add_mutually_exclusive_group()
mgroup5.add_argument("-n0", "--nKaminsky", help="use nonce in Kaminsky mode (default for LC4)", action="store_true")
mgroup5.add_argument("-n1", "--nKratochvil", help="use nonce in Kratochvil mode (default for LS47)", action="store_true")
mgroup6 = parser.add_mutually_exclusive_group()
mgroup6.add_argument("-m0", "--mKaminsky", help="use marker in Kaminsky mode (default for LC4)", action="store_true")
mgroup6.add_argument("-m1", "--mKratochvil", help="use marker in Kratochvil mode (default for LS47)", action="store_true")
parser.add_argument("-s", "--signature", help="append SIGNATURE to plaintext when encrypting")
args = parser.parse_args()
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
if args.verbose and len(sys.argv)==2:
print('Version: ' + version)
# parser.print_help()
sys.exit(1)
# set cipher
if args.ls47:
size = 7
letters = letters7
else:
size = 6
letters = letters6
tiles = list(zip(letters, [(x // size, x % size) for x in range(size * size)]))
# set nonce
if args.noncestring:
nonce = args.noncestring
elif args.noncelen:
nonce = create_random_nonce(args.noncelen)
else:
nonce = ""
check_nonce(nonce)
nonce_size = len(nonce)
nonce_enc = ""
# set nonce mode
nonce_mode = 1 if size==6 else 2
if args.nKaminsky: nonce_mode = 1
if args.nKratochvil: nonce_mode = 2
# set marker mode
marker_mode = 1 if size==6 else 2
if args.nKaminsky: marker_mode = 1
if args.nKratochvil: marker_mode = 2
# set key
key = letters
if args.keywordfile: args.keywordstring = open(args.keywordfile, 'r').read().rstrip('\r\n')
if args.keywordstring: key = derive_key(args.keywordstring);
if args.keyfile: args.keystring = open(args.keyfile, 'r').read().rstrip('\r\n')
if args.keystring: key = args.keystring;
initialkey = key
check_key(key)
mp = (0, 0)
# encrypt / decrypt / test
if args.encryptfile:
args.encryptstring = open(args.encryptfile, 'r').read().rstrip('\r\n')
if args.decryptfile:
args.decryptstring = open(args.decryptfile, 'r').read().rstrip('\r\n')
if args.encryptstring:
plaintext = args.encryptstring
if args.signature: plaintext += args.signature
check_plaintext(plaintext)
ciphertext = encrypt_with_nonce(plaintext)
if args.verbose: printinfo(True)
print(ciphertext)
elif args.decryptstring:
ciphertext = args.decryptstring
check_ciphertext(ciphertext)
plaintext = decrypt_with_nonce(ciphertext)
if args.verbose: printinfo()
if args.signature and args.verbose:
eprint("Warning: the given signature is ignored during decryption")
print(plaintext)
elif args.test:
print('\nVersion: ' + version)
print('Test: No nonce provided (only its length), so each call will produce a different ciphertext.')
size = 7; test1(size)
size = 6; test1(size)
sys.exit(1)
else:
# if args.verbose: print('Version : ' + version)
print('ALPHABET : ' + letters)
print('KEY : ' + initialkey)
print('NONCE : ' + nonce)
|