-
Notifications
You must be signed in to change notification settings - Fork 2
/
css.py
72 lines (55 loc) · 2.12 KB
/
css.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
def text_to_bits(text, encoding="utf-8", errors="surrogatepass"):
# Thanks jfs - convert-binary-to-ascii-and-vice-versa
bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def text_from_bits(bits, encoding="utf-8", errors="ignore"):
# Thanks jfs - convert-binary-to-ascii-and-vice-versa
n = int(bits, 2)
return n.to_bytes(
(n.bit_length() + 7) // 8, "big").decode(encoding, errors) or '\0'
def LFSR(text_bin, key, poly, lfsr):
# The lfsr is generated by the key and polynomial
for digit in text_bin:
xor = sum(key[num] for num in poly)
xor = 0 if xor % 2 == 0 else 1
lfsr.append(xor)
key.insert(0, xor)
del key[-1]
return lfsr
def FullAdder(text_bin, lfsr_17, lfsr_25, cin, crypt_bin):
# This is the standard full-adder truth table
for i, digit in enumerate(text_bin):
lsfr_cin_sum = lfsr_17[i] + lfsr_25[i] + cin
s = 0 if lsfr_cin_sum == 0 or lsfr_cin_sum == 2 else 1
cout = 0 if lsfr_cin_sum == 0 or lsfr_cin_sum == 1 else 1
crypt_bin.append((s + digit) % 2)
cin = cout
return crypt_bin
### Import file
with open("hell.txt", 'r') as f:
plaintext = f.read()
f.close()
### Plaintext
plaintext_bin = list(map(int, text_to_bits(plaintext)))
### Keyword
keyword = "Shane"
keyword_bin = text_to_bits(keyword)
### Keys
key_17 = list(map(int, '1' + keyword_bin[:16]))
key_25 = list(map(int, '1' + keyword_bin[16:]))
### LFSR Plaintext
lfsr_17 = LFSR(plaintext_bin, key_17, (16, 2), [])
lfsr_25 = LFSR(plaintext_bin, key_25, (24, 7, 5, 1), [])
### Full Adder Plaintext
ciphertext_bin = FullAdder(plaintext_bin, lfsr_17, lfsr_25, 0, [])
### Output Ciphertext
ciphertext = text_from_bits("".join(map(str, ciphertext_bin)))
### Full Adder Ciphertext
dectext_bin = FullAdder(ciphertext_bin, lfsr_17, lfsr_25, 0, [])
### Output Dectext
dectext = text_from_bits("".join(map(str, dectext_bin)))
### Print the results
print("The keyword: ", keyword)
print("\nThe plaintext: ", plaintext)
print("\nThe ciphertext: ", ciphertext)
print("\nThe dectext: ", dectext)