def get_prg(plaintext_size, k):
j = 0
S = list(range(32))
for i in range(32):
j = (j + S[i] + ord(k[i % len(k)])) % 32
S[i], S[j] = S[j], S[i]
return S
def fake_rc4(plaintext, keystream):
i = 0
j = 0
i = (i + 1) % 32
j = (j + keystream[i]) % 32
keystream[i], keystream[j] = keystream[j], keystream[i]
t = (keystream[i] + keystream[j]) % 32
return t
i need at the end to return a cipher text.
at the fake_rc4
I return the index of the keystream.
How at the other func do I encode the text using xor on the plain text?
I use mod 32 and not 256 because of an exercise.
this is the exercise:
Write the stream cipher fake-RC4: implement a function encrypt that given a plaintext and a 32-bytes key
k
, returns a ciphertext encrypted with a weak variant of RC4 which we describe here.First, implement the fake-RC4 pseudo-random generator (PRG):
It starts with
i = j = 0
, and to generate the next byte in the keystream it:
- Increments
i
by 1 (modulo 32),- Increments
j
by thei
th character of the key (modulo 32),- Swaps the
i
th character of the key with itsj
th character,- Adds the
i
th character of the key and itsj
th character, modulo32
, and returns the key's character at that index.So for example, if the
i
th character of the key was'a'
(whose ASCII value is97
), and itsj
th character was'3'
(whose ASCII value is51
), their sum would be148
. Modulo the length of the key, the result will be148 % 32 = 20
, so the pseudo random generator would return the20
th character of the key as the next byte.Once you have the pseudo-random generator working, the rest is easy:
- Iterate over the plaintext
- XOR every character with the next byte of the pseudo-random generator's keystream
- Return the result as the ciphertext!