-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrc4.py
More file actions
55 lines (45 loc) · 1.16 KB
/
Copy pathrc4.py
File metadata and controls
55 lines (45 loc) · 1.16 KB
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
from binascii import hexlify
def key_init(key):
s = []
for i in range(256):
s.append(i)
j = 0
for i in range(256):
j = (j + s[i] + ord(key[i % len(key)])) % 256
s[i], s[j] = s[j], s[i]
return s
def enc(msg, key):
s = key_init(key)
i = 0
j = 0
res = []
for c in msg:
i = (i + 1) % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
oct_enc = s[(s[i]+s[j]) % 256]
res.append(chr(oct_enc ^ ord(c)))
return ''.join(res)
def dec(enc, key):
s = key_init(key)
i = 0
j = 0
res = []
for c in enc:
i = (i + 1) % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
oct_enc = s[(s[i]+s[j]) % 256]
res.append(chr(oct_enc ^ ord(c)))
return ''.join(res)
def main():
while True:
msg = input("Enter a message:")
key = input("Enter a key:")
enc_msg = enc(msg, key)
print(f"Encrypted msg:{enc_msg}")
print(f"Encrypted msg in hex:{hexlify(enc_msg.encode()).decode()}")
dec_msg = dec(enc_msg, key)
print(f"Decrypted msg:{dec_msg}")
if __name__ == "__main__":
main()