NML Says

Open Source Development 9 - Review Specs Work

Refs for Todays Session

Uncurled by Daniel Stenberg, Apr 2022

Jean-Philippe Aumasson. Serious Cryptography. No Starch Press, 2018

Model Solutions Previous Lessons

We shall illustrate the work you did in session 8. It is all compiled into a repository at Codeberg, please find it at https://codeberg.org/arosano/library8

This time you created the testsuite code, while we created the functions to be tested.

Previously, in session 6, we did the opposite, where you wrote the functions, and we wrote the testsuite.

Example 1. README.md
 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
# Open Source Experiment
## Model Solutions to Exercise OSD.8

## Copyright
Copyright © 2025 Authors as they appear in the
file [AUTHORS](AUTHORS).

## License
Copyright as stated above

The software is released under the BSD-3 License
as described in the file [LICENSE](LICENSE).

## Content
The file `lib8.py` contains a series of not 
necessarily related functions that may serve as 
useful utilities in various contexts.

For this project students supplied (most of)
the tests in the file `testsuite.py`
while we supplied the functions.

When or if the number of functions grow it may
be useful to group them into separate subject
related library files.
Example 2. AUTHORS
1
2
3
4
5
6
7
8
Copyright holder for individual functions as it
appears in the appropriate code files.

Copyright © 2025 PAUL MICKY D COSTA
Copyright © 2025 Niels Müller Larsen
Copyright © 2025 Navneet Kaur
Copyright © 2025 Tania
Copyright © 2025 Sushil Thapa
Example 3. LICENSE
 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
Copyright © 2025 Authors, please refer to the AUTHORS file.

Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the
following conditions are met:

1.  Redistributions of source code must retain the above 
    copyright notice, this list of conditions and the 
    following disclaimer.

2.  Redistributions in binary form must reproduce the 
    above copyright notice, this list of conditions and
    the following disclaimer in the documentation and/or
    other materials provided with the distribution.

3.  Neither the name of the copyright holder nor the names
    of its contributors may be used to endorse or promote
    products derived from this software without specific 
    prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
“AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
Example 4. Compilation of Our Work - lib8.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
'''
    Copyright © 2025 Niels
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
'''
import geopy.distance
import math


'''
    OSD.8.0
'''
def isOddInt(a):
    '''
        Checks if the input is an odd integer.
    '''
    if isinstance(a, int) and a % 2 != 0:
        return True
    return False

'''
    OSD.8.1
'''
def factorial(n):
    if not isinstance(n, int) or n < 1:
        return -1
    if n <= 1:
        return 1
    return n * factorial(n - 1)

'''
    OSD.8.2
'''
def max_of_3(a, b, c):
    '''
        Returns the biggest of three numbers
    '''
    return max((a, b, c))

'''
    OSD.8.3
'''
def sort_dic_key(dic):
    return dict(sorted(dic.items(), key=lambda item: item[0]))

def word_freq(s, dic={}):
    '''
        creates a word frequency dictionary from a string
    '''
    import re
    l = re.findall(r'\w+', s)
    for word in l:
        if word in dic:
            dic[word] += 1
        else:
            dic[word] = 1
    return dic

'''
    OSD.8.4
'''
def unique_words(dic):
    '''
        creates a set of words from a dictionary of word frequencies
        such as output from word_freq(s)
    '''
    if not isinstance(dic, dict):
        return set()
    return set(dic)

'''
    OSD.8.5
'''
def is_perfect(n):
    '''
        checks whether or not an integer i a perfect
        number. 
        returns a boolean
    '''
    if n < 1:
        return False
    sum = 0
    for i in range(1, n):
        if n % i == 0:
            sum = sum + i
    return sum == n


'''
    OSD.8.6
'''
def v2p(f, mode='metric'):
    '''
        Velocity to pace in h:m:s/distance
        If mode not metric imperial is assumed
    '''
    if f <= 0:
        return (0, 0)
    p0 = 3600 / f
    return divmod(p0, 60)

def p2v(p, mode='metric'):
    '''
        Pace to velocity in distance/hour
        if mode is not metric km/h (kmh)
        if imperial m/h (mph)
    '''
    if p == (0, 0):
        return 0
    p0 = p[0] * 60 + p[1]
    return 3600 / p0

'''
    OSD.8.7
'''
def password_entropy(pwd, N=63):
    '''
        Plain calculation of password entropy
        based on available characters, and
        password length.
        N = 63 => all alphanumerics upper and lower + space
    '''
    return math.log2(N ** len(pwd))

'''
    OSD.8.8
'''
def acc_interest(a, t, i):
    '''
        Accumulated amount after t terms with interest a%
    '''
    return a * (1 + i / 100) ** t

'''
    OSD.8.9
'''
def vol_sphere(r):
    '''
        Volume of sphere given radius
    '''
    if r < 0:
        return -1
    return 4 / 3 * math.pi * pow(r, 3)


'''
    OSD.8.10
    (point.py)
    class definition of a point
    x and y are ints
'''
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def distance(self, o):
        '''
            Method for calc distance between two Points
        '''
        return math.sqrt(math.pow((self.x - o.x), 2) + math.pow((self.y - o.y), 2))

'''
    OSD.8.11
    (geopoint.py)
    class definition of a point
    lat and lon are are floats
    https://stackoverflow.com/questions/19412462/getting-distance-between-two-points-based-on-latitude-longitude
'''
class GeoPoint:
    def __init__(self, lat, lon):
        self.lat = lat
        self.lon = lon
    
    def distance(self, o):
        '''
            Method for cal distance between two Points
        '''
        return geopy.distance.geodesic((self.lat, self.lon), (o.lat, o.lon)).km

'''
    OSD.8.12
'''
def acronym(s):
    '''
        Create acronym from string of words
    '''
    d = {}
    d = word_freq(s, d)
    r = ''
    for word in d:
        r += word[0].upper()
    return r.upper()

'''
    OSD.8.13
'''
def numerologize(s):
    '''
        numerologize a string (name?)
    '''
    s = s.lower()
    n = 0
    for letter in s:
        if letter != ' ':
            n += ord(letter) - 96
    return n

'''
    OSD.8.14
'''
def caesarE(s, key):
    '''
        eh?
    '''
    import re
    alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    s = s.upper()
    s = re.sub(r'[^\w]', '', s)
    ci = ''
    key = key % len(alpha)
    if key == 0:
        return s
    for ch in s:
        ci += alpha[(alpha.index(ch) + key) % len(alpha)]
    return ci

'''
    OSD.8.15
'''
def caesarD(s, key):
    '''
        eh?
    '''
    return caesarE(s, -key)

'''
    OSD.8.16
'''
def wc(s):
    '''
        Python implementation of Unix wc
    '''
    import re
    words = re.findall(r'\w+', s)
    pattern = re.compile(r'^\w.*', flags=re.MULTILINE)
    lines = re.findall(pattern, s)
    return (len(lines), len(words), len(s) + 1)
Example 5. Your work: Testsuite - testsuite.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
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
'''
    testsuite.py
    
    Copyright © 2025 Authors. Pls refer to the AUTHORS file
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
'''

import unittest
from lib8 import *

class Testing(unittest.TestCase):
    '''
    OSD.8.0
    Copyright © 2025 Niels Müller Larsen
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_isOdd1(self):
        self.assertTrue(isOddInt(1))
    def test_isOdd2(self):
        import sys
        self.assertTrue(isOddInt(sys.maxsize))
    def test_isOdd3(self):
        self.assertFalse(isOddInt(2**53))
    def test_isOdd4(self):
        self.assertTrue(isOddInt(2**63-1))


    '''
    OSD.8.1
    Copyright © 2025 PAUL MICKY D COSTA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_valid_inputs(self):
        self.assertEqual(factorial(1), 1)
        self.assertEqual(factorial(2), 2)
        self.assertEqual(factorial(3), 6)
        self.assertEqual(factorial(5), 120)
        self.assertEqual(factorial(10), 3628800)
    
    def test_zero_input(self):
        self.assertEqual(factorial(0), -1)
        
    def test_negative_input(self):
        self.assertEqual(factorial(-5), -1)
    
    def test_non_integer_input(self):
        self.assertEqual(factorial(3.5), -1)
        self.assertEqual(factorial("5"), -1)
        self.assertEqual(factorial(None), -1)
    
    def test_large_input(self):
        self.assertEqual(factorial(20), 2432902008176640000)

    '''
    OSD.8.2
    Copyright © 2025 Tania and (formatted by) NML
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_max31(self):
        self.assertEqual(max_of_3(1,2,3), 3)
    def test_max32(self):
        self.assertEqual(max_of_3(10, 5, 7), 10)
    def test_max33(self):
        self.assertEqual(max_of_3(-1, -5, -3), -1)
    def test_max34(self):
        self.assertEqual(max_of_3(7, 7, 7), 7)
    def test_max35(self):
        self.assertEqual(max_of_3(100, 1000, 10), 1000)


    '''
    OSD.8.3
    Copyright © 2025 Navneet and (formatted by) NML
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_word_freq0(self):
        dic = {}
        s = 'This is a test. This test is only a test.'
        res = {
            'this': 2,
            'is': 2,
            'a': 2,
            'test': 3,
            'only': 1,
        }
        self.assertEqual(word_freq(s.lower(), dic), res)


    '''
    OSD.8.4
    Copyright © 2025 PAUL MICKY D COSTA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_basic_dictionary(self):
        dic = {"apple": 2, "banana": 3, "orange": 1}
        expected = {"apple", "banana", "orange"}
        self.assertEqual(unique_words(dic), expected)

    def test_empty_dictionary(self):
        self.assertEqual(unique_words({}), set())

    def test_single_word(self):
        self.assertEqual(unique_words({"hello": 10}), {"hello"})

    def test_non_dict_input(self):
        self.assertEqual(unique_words(None), set())
        self.assertEqual(unique_words(["apple", "banana"]), set())
        self.assertEqual(unique_words("notadict"), set())


    '''
    OSD.8.5
    Copyright © 2025 SUSHIL THAPA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_is_perfect1(self):
        # 6 = 1 + 2 + 3
        self.assertTrue(is_perfect(6))
    def test_is_perfect2(self):
        # 28 = 1 + 2 + 4 + 7 + 14
        self.assertTrue(is_perfect(28))
    def test_is_perfect3(self):
        # 496 is a known perfect number
        self.assertTrue(is_perfect(496))
    def test_is_perfect4(self):
        # 12 is not a perfect number
        self.assertFalse(is_perfect(12))
    def test_is_perfect5(self):
        # 1 has no proper divisors
        self.assertFalse(is_perfect(1))
    def test_is_perfect6(self):
        # 0 is not a perfect number
        self.assertFalse(is_perfect(0))


    '''
    OSD.8.6
    Copyright © 2025 PAUL MICKY D COSTA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_v2p_metric(self):
        self.assertEqual(v2p(15, 'metric'), (4, 0))     # 15 km/h = 4:00 min/km
        self.assertEqual(v2p(12, 'metric'), (5, 0))     # 12 km/h = 5:00 min/km
        self.assertEqual(v2p(11, 'metric'), (5, 27.272727272727252))        # 11 km/h = 5:27 min/km
        self.assertEqual(v2p(6, 'metric'), (10, 0))     # 6 km/h = 10:00 min/km
        self.assertEqual(v2p(0, 'metric'), (0, 0))       # edge case

    def test_v2p_imperial(self):
        self.assertEqual(v2p(12, 'imperial'), (5, 0))     # 12 mph = 5:00 min/mile
        self.assertEqual(v2p(8, 'imperial'), (7, 30))     # 8 mph = 7:30 min/mile
        self.assertEqual(v2p(4, 'imperial'), (15, 0))     # 4 mph = 15:00 min/mile
        self.assertEqual(v2p(0, 'imperial'), (0, 0))       # edge case

    def test_p2v_metric(self):
        self.assertAlmostEqual(p2v((5, 0), 'metric'), 12.0)
        self.assertAlmostEqual(p2v((5, 27.273), 'metric'), 11.0, 1)
        self.assertAlmostEqual(p2v((10, 0), 'metric'), 6.0)
        self.assertAlmostEqual(p2v((0, 0), 'metric'), 0.0)

    def test_p2v_imperial(self):
        self.assertAlmostEqual(p2v((5, 0), 'imperial'), 12.0)
        self.assertAlmostEqual(p2v((7, 30), 'imperial'), 8.0)
        self.assertAlmostEqual(p2v((15, 0), 'imperial'), 4.0)
        self.assertAlmostEqual(p2v((0, 0), 'imperial'), 0.0)
    
    # one test of second param removed by NML


    '''
    OSD.8.7
    Copyright © 2025 Tania and (formatted by) NML
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_entropy1(self):
        self.assertEqual(password_entropy('password'), 47.818239387999334)
    def test_entropy2(self):
        self.assertEqual(password_entropy('Password123'), 65.75007915849908)
    def test_entropy3(self):
        self.assertEqual(password_entropy('P@ssw0rd!'), 53.79551931149925)
    def test_entropy4(self):
        self.assertEqual(password_entropy(''), 0.0)
    def test_entropy5(self):
        self.assertEqual(password_entropy('  '), 11.954559846999834)
    def test_entropy6(self):
        self.assertEqual(password_entropy('123456'), 35.8636795409995)
    def test_entropy7(self):
        self.assertEqual(password_entropy('A'), 5.977279923499917)
    def test_entropy8(self):
        self.assertEqual(password_entropy('!@#$%^'), 35.8636795409995)
    def test_entropy9(self):
        self.assertTrue(password_entropy('abracadabraABR') > 80)    # l = 14
    def test_entropyA(self):
        self.assertFalse(password_entropy('abracadabraABRACA', N = 26) > 80)    # l = 17


    '''
    OSD.8.8
    Copyright © 2025 Navneet and (formatted by) NML
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_interest1(self):
        a = 1000
        t = 3
        i = 5
        self.assertEqual(acc_interest(a, t, i), 1157.6250000000002)
    
    
    '''
    OSD.8.9
    Copyright © 2025 PAUL MICKY D COSTA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_standard_radii(self):
        import math
        self.assertAlmostEqual(vol_sphere(1), (4/3) * math.pi * 1**3)
        self.assertAlmostEqual(vol_sphere(2), (4/3) * math.pi * 8)
        self.assertAlmostEqual(vol_sphere(3), (4/3) * math.pi * 27)

    def test_zero_radius(self):
        self.assertEqual(vol_sphere(0), 0.0)

    def test_negative_radius(self):
        self.assertEqual(vol_sphere(-5), -1)

    def test_large_radius(self):
        self.assertAlmostEqual(vol_sphere(10), (4/3) * math.pi * 1000)


    '''
    OSD.8.10
    Copyright © 2025 SUSHIL THAPA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''

    def test_distance1(self):
        p1 = Point(0, 0)
        p2 = Point(3, 4)
        self.assertEqual(p1.distance(p2), 5)

    def test_distance2(self):
        p1 = Point(1, 1)
        p2 = Point(1, 1)
        self.assertEqual(p1.distance(p2), 0)

    def test_distance3(self):
        p1 = Point(-1, -1)
        p2 = Point(2, 3)
        self.assertAlmostEqual(p1.distance(p2), 5.0)

    def test_distance4(self):
        p1 = Point(5, 0)
        p2 = Point(0, 12)
        self.assertEqual(p1.distance(p2), 13)

    def test_distance5(self):
        p1 = Point(-3, 4)
        p2 = Point(3, -4)
        self.assertAlmostEqual(p1.distance(p2), 10.0)


    '''
    OSD.8.11
    Copyright © 2025 NML.
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_geopoint0(self):
        g= GeoPoint(56.15674, 10.21076)      # Aarhus
        o = GeoPoint(55.67594, 12.56553)        # Copenhagen
        self.assertEqual(g.distance(o), 156.65774019967023)
    def test_geopoint1(self):
        g= GeoPoint(52.2296756, 21.0122287)
        o = GeoPoint(52.406374, 16.9251681)
        self.assertEqual(g.distance(o), 279.35290160430094)
    

    '''
    OSD.8.12
    Copyright © 2025 Tania and (formatted by) NML
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_acronym1(self):
        self.assertEqual(acronym('random access memory'), 'RAM')
    def test_acronym2(self):
        self.assertEqual(acronym('central processing unit'), 'CPU')
    def test_acronym3(self):
        self.assertEqual(acronym('graphics processing unit'), 'GPU')
    def test_acronym4(self):
        self.assertEqual(acronym('self contained underwater breathing apparatus'), 'SCUBA')
    def test_acronym5(self):
        self.assertEqual(acronym('  national  aeronautics  space  administration  '), 'NASA')
    def test_acronym6(self):
        self.assertEqual(acronym(''), '')
    def test_acronym7(self):
        self.assertEqual(acronym('hello'), 'H')


    '''
    OSD.8.13
    Copyright © 2025 Navneet and (formatted by) NML
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_numerology1(self):
        self.assertEqual(numerologize('John Doe'), 71)
    def test_numerology2(self):
        self.assertEqual(numerologize('Niels'), 59)

    

    '''
    OSD.8.14
    Copyright © 2025 PAUL MICKY D COSTA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_caesarE0(self):
        # Test case where the input is 'Jacta est alea' and the key is 3
        self.assertEqual(caesarE('Jacta est alea', 3), 'MDFWDHVWDOHD')
        
    def test_caesarE1(self):
        # Test case where the input is 'hello world' and the key is 5
        self.assertEqual(caesarE('hello world', 5), 'MJQQT1TWQI')
        
    def test_caesarE2(self):
        # Test case where the input is 'ABC' and the key is 1
        self.assertEqual(caesarE('ABC', 1), 'BCD')
        
    def test_caesarE3(self):
        # Test case where the input is 'XYZ' and the key is 4
        self.assertEqual(caesarE('XYZ', 4), '123')
        
    def test_caesarE4(self):
        # Test case with no alphabetic characters
        self.assertEqual(caesarE('123 456!@#', 3), '456789')
        
    def test_caesarE5(self):
        # Test case where the input is 'TEST' and the key is 26 (full rotation)
        self.assertEqual(caesarE('TEST', 36), 'TEST')
        
    def test_caesarE6(self):
        self.assertEqual(caesarE('PYTHON', 10), 'Z83RYX')


    '''
    OSD.8.15
    Copyright © 2025 SUSHIL THAPA
    Licensed under the BSD-3 License,
    please refer to the LICENSE document
    '''
    def test_caesarD1(self):
        self.assertEqual(caesarD('MDFWDHVWDOHD', 3), 'JACTAESTALEA')

    def test_caesarD2(self):
        self.assertEqual(caesarD('MJQQT1TWQI', 5), 'HELLOWORLD')

    def test_caesarD3(self):
        self.assertEqual(caesarD('Z83RYX', 10), 'PYTHON')

    def test_caesarD4(self):
        self.assertEqual(caesarD('CAESARCIPHER', 0), 'CAESARCIPHER')

    def test_caesarD5(self):
        self.assertEqual(caesarD('SAMETEXTSAMEKEY', 36), 'SAMETEXTSAMEKEY')

    def test_caesarD6(self):
        self.assertEqual(caesarD('BMQIBCFU', 1), 'ALPHABET')

    
    ''' 
    OSD.8.16
    Copyright © 2025 NML
    Licensed under the BSD-3 License,
    please refer to the LICENSE document 
    '''
    def test_wc0(self):
        self.assertEqual(wc('abc\ndef'), (2, 2, 8))

if __name__ == '__main__':
    unittest.main()

This Sessions Subject Matter

The material of today is meant to be read as homework. Uncurled by Daniel Stenberg, Apr 2022

Pre Exercises

A quote from Jean-Philippe Aumasson. Serious Cryptography. No Starch Press, 2018

The Vigenère Cipher

It took about 1500 years to see a meaningful improvement of the Caesar cipher in the form of the Vigenère cipher, created in the 16th century by an Italian named Giovan Battista Bellaso. The name “Vigenère” comes from the Frenchman Blaise de Vigenère, who invented a different cipher in the 16th century, but due to historical misattribution, Vigenère’s name stuck. Nevertheless, the Vigenère cipher became popular and was later used during the A merican Civil War by Confederate forces and during WWI by the Swiss Army, among others.

The Vigenère cipher is similar to the Caesar cipher, except that letters aren’t shifted by three places but rather by values defined by a key, a collection of letters that represent numbers based on their position in the alphabet. For example, if the key is DUH, letters in the plaintext are shifted using the values 3, 20, 7 because D is three letters after A, U is 20 letters after A, and H is seven letters after A. The 3, 20, 7 pattern repeats until you’ve encrypted the entire plaintext. For example, the word CRYPTO would encrypt to FLFSNV using DUH as the key: C is shifted three positions to F, R is shifted 20 positions to L, and so on. Figure 1-3 illustrates this principle when encrypting the sentence THEY DRINK THE TEA.

The Vigenère cipher is clearly more secure than the Caesar cipher, yet it’s still fairly easy to break. The first step to breaking it is to figure out the key’s length. For example, take the example in Example 40.2, wherein THEY DRINK THE TEA encrypts to WBLBXYLHRWBLWYH with the key DUH. (Spaces are usually removed to hide word boundaries.) Notice that in the ciphertext WBLBXYLHRWBLWYH, the group of three letters WBL appears twice in the ciphertext at nine-letter intervals. This suggests that the same three-letter word was encrypted using the same shift values, producing WBL each time. A cryptanalyst can then deduce that the key’s length is either nine or a value divisible by nine (that is, three). Furthermore, they may guess that this repeated three- letter word is THE and therefore determine DUH as a possible encryption key.

The second step to breaking the Vigenère cipher is to determine the actual key using a method called frequency analysis, which exploits the uneven distribution of letters in languages. For example, in English, E is the most common letter, so if you find that X is the most common letter in a ciphertext, then the most likely plaintext value at this position is E.

Despite its relative weakness, the Vigenère cipher may have been good enough to securely encrypt messages when it was used. First, because the attack just outlined needs messages of at least a few sentences, it wouldn’t work if the cipher was used to encrypt only short messages. Second, most messages needed to be secret only for short periods of time, so it didn’t matter if ciphertexts were eventually decrypted by the enemy. (The 19th- century cryptographer Auguste Kerckhoffs estimated that most encrypted wartime messages required confidentiality for only three to four hours.)

1
2
3
4
5
    Keys: 
    A  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
    D  D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
    H  H I J K L M N O P Q R S T U V W X Y Z A B C D E F G
    U  U V W X Y Z A B C D E F G H I J K L M N O P Q R S T

Figure 1-3: The Vigenére Cipher [replaced by yours truly. The Vigenére cipher is also known as poly alphabetic cipher.]

How Ciphers Work

Based on simplistic ciphers like the Caesar and Vigenère ciphers, we can try to abstract out the workings of a cipher, first by identifying its two main components: a permutation and a mode of operation. A permutation is a function that transforms an item (in cryptography, a letter or a group of bits) such that each item has a unique inverse

(for example, the Caesar cipher’s three-letter shift). A mode of operation is an algorithm that uses a permutation to process messages of arbitrary size. The mode of the Caesar cipher is trivial: it just repeats the same permutation for each letter, but as you’ve seen, the Vigenère cipher has a more complex mode, where letters at different positions undergo different permutations.

Exercises

Exercises