-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrc4.py
More file actions
81 lines (39 loc) · 1.29 KB
/
Copy pathrc4.py
File metadata and controls
81 lines (39 loc) · 1.29 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
81
#
# rc4.py - A python implementation of the RC4 stream cipher
#
# external modules #
from sort import swap
import copy
# helper functions #
# key-scheduling algorithm (KSA) #
def init_byte_array(byte_array, key):
my_byte_array = copy.deepcopy(byte_array)
key_length = len(key)
j = 0
for i in range(0, 256):
j = (j + my_byte_array[i] + ord(key[i % key_length])) % 256
swap(my_byte_array, i, j)
return my_byte_array
# Pseudo-Random Generation Algorithm (PRGA) #
def get_keystream(len_stream, byte_array):
key_stream = ""
i = j = 0
for k in range(0, len_stream):
i = (i + 1) % 256
j = (j + byte_array[i]) % 256
key_byte = byte_array[(byte_array[i] + byte_array[j]) % 256]
key_stream += chr(key_byte)
return key_stream
# main functions #
# encode plaintext using RC4 #
def encode(plaintext, key_text):
key = key_text[:256]
byte_array = init_byte_array(range(0, 256), key)
key_stream = get_keystream(len(plaintext), byte_array)
ciphertext = ""
for i in range(len(plaintext)):
ciphertext += chr(ord(plaintext[i]) ^ ord(key_stream[i]))
return ciphertext
# decode ciphertext using RC4 #
def decode(ciphertext, key_text):
return encode(ciphertext, key_text)