-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRC4.py
55 lines (39 loc) · 1.02 KB
/
RC4.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
def KSA(key):
keylength = len(key)
S = range(256)
j = 0
for i in range(256):
j = (j + S[i] + key[i % keylength]) % 256
S[i], S[j] = S[j], S[i] # swap
return S
def PRGA(S):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i] # swap
K = S[(S[i] + S[j]) % 256]
yield K
def RC4(key):
S = KSA(key)
return PRGA(S)
if __name__ == '__main__':
# test vectors are from http://en.wikipedia.org/wiki/RC4
# ciphertext should be BBF316E8D940AF0AD3
key = 'Key'
plaintext = 'Plaintext'
# ciphertext should be 1021BF0420
#key = 'Wiki'
#plaintext = 'pedia'
# ciphertext should be 45A01F645FC35B383552544B9BF5
#key = 'Secret'
#plaintext = 'Attack at dawn'
def convert_key(s):
return [ord(c) for c in s]
key = convert_key(key)
keystream = RC4(key)
import sys
for c in plaintext:
sys.stdout.write("%02X" % (ord(c) ^ keystream.next()))
print