@@ -29,23 +29,53 @@ def generate_charset(seed: int = 0):
29
29
return '' .join (charset )
30
30
31
31
32
- def encode (text : str , charset : str , shift_pattern : list [int ]) -> str :
32
+ def get_random_charsets (charset : str , shift_pattern : list [int ]) -> list :
33
+ random_charsets = []
34
+ for i in shift_pattern :
35
+ rng = random .Random (i ) # Local RNG instance
36
+ new_charset = list (charset )
37
+ rng .shuffle (new_charset )
38
+ random_charsets .append (new_charset )
39
+ return random_charsets
40
+
41
+
42
+ def _code (text : str , charset : str , shift_pattern : list [int ], encode : bool ):
33
43
result = ""
44
+
45
+ # generate a list of charsets
46
+ random_charsets = get_random_charsets (charset , shift_pattern )
47
+
48
+ # Encode the text using the shift pattern
34
49
pattern_length = len (shift_pattern )
35
50
for i , char in enumerate (text ):
36
51
if char in charset :
37
- shift = shift_pattern [i % pattern_length ]
38
- index = charset .index (char )
39
- result += charset [(index + shift ) % len (charset )]
52
+ i_shift = i % pattern_length
53
+ shift = shift_pattern [i_shift ]
54
+
55
+ random_charset : str = random_charsets [i_shift ]
56
+
57
+ index = random_charset .index (char )
58
+
59
+ # Calculate the new index based on encoding or decoding
60
+ offset : int
61
+ if encode :
62
+ offset = (index + shift ) % len (random_charset )
63
+ else :
64
+ offset = (index - shift ) % len (random_charset )
65
+
66
+ # Append the character from the random charset
67
+ result += random_charset [offset ]
40
68
else :
41
69
result += char
42
70
return result
43
71
44
72
73
+ def encode (text : str , charset : str , shift_pattern : list [int ]) -> str :
74
+ return _code (text , charset , shift_pattern , encode = True )
75
+
76
+
45
77
def decode (text : str , charset : str , shift_pattern : list [int ]) -> str :
46
- # Negate each shift to reverse the encoding
47
- reversed_pattern = [- s for s in shift_pattern ]
48
- return encode (text , charset , reversed_pattern )
78
+ return _code (text , charset , shift_pattern , encode = False )
49
79
50
80
51
81
class EncoderDecoderUI ():
0 commit comments