This repository was archived by the owner on Mar 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrc4.py
More file actions
80 lines (67 loc) · 2.32 KB
/
rc4.py
File metadata and controls
80 lines (67 loc) · 2.32 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
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
#!/usr/bin/env python3.6
import sys
def generateSbox(keystream):
k = list(keystream) #keystream als list, ein zeichen pro index
L = len(k)
s = [i for i in range(256)]
j = 0
for i in range(256):
j = (j + s[i] + ord(k[i%L])) % 256 #ord() konvertiert ascii symbol in integer
s[i], s[j] = s[j], s[i] #vertausche s[i] mit s[j]
return s
def encrypt(keystream, plaintext):
print("Keystream: "+keystream+"\nPlaintext: "+plaintext)
s = generateSbox(keystream)
klar = bytearray()
klar.extend(map(ord, plaintext))
schl = list()
i = 0
j = 0
for n in range(0, len(klar)):
i = i + 1 % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
zufallszahl = s[(s[i] + s[j]) % 256]
schl.append(zufallszahl ^ klar[n]) # ^ = XOR
return schl
def decrypt(keystream, ciphertext):
print("Keystream: "+keystream+"\nCiphertext: "+ciphertext)
s = generateSbox(keystream)
chi = bytearray.fromhex(ciphertext)
schl = list()
i = 0
j = 0
for n in range(0, len(chi)):
i = i + 1 % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
zufallszahl = s[(s[i] + s[j]) % 256]
schl.append(zufallszahl ^ chi[n]) # ^ = XOR
return schl
if __name__== "__main__":
print ("--- RC4 Encryptor ---")
if(len(sys.argv) < 2):
print("Usage: python rc4.py [enc|dec] keystream [plaintext|ciphertext]")
sys.exit(1)
if(sys.argv[1] == "enc"):
encrypted = encrypt(sys.argv[2], sys.argv[3])
encryptedStr = ''
for i in range(0, len(encrypted)):
encryptedStr += chr(encrypted[i])
print("Encrypted Bytesequence:")
print(''.join(format(x,'02x') for x in encrypted))
sys.exit(0)
elif(sys.argv[1] == "dec"):
decrypted = decrypt(sys.argv[2], sys.argv[3])
decryptedStr = ''
for i in range(0, len(decrypted)):
decryptedStr += chr(decrypted[i])
decryptedStr = ''.join(format(x,'02x') for x in decrypted)
print("Decrypted Bytesequence:")
print(decryptedStr)
print("Decrypted Bytesequence as ASCII:")
print(bytes.fromhex(decryptedStr).decode('utf-8'))
sys.exit(0)
else:
print("Usage: python rc4.py [enc|dec] keystream [plaintext|ciphertext]")
sys.exit(2)