|
| 1 | +from typing import List |
| 2 | + |
| 3 | +class RC4: |
| 4 | + def __init__(self, key: bytes): |
| 5 | + self.key=key |
| 6 | + self.s=self._ksa(key) |
| 7 | + |
| 8 | + def _ksa(self, key: bytes) -> List[int]: |
| 9 | + """Key Scheduling Algorithm (KSA)""" |
| 10 | + key_length=len(key) |
| 11 | + s=list(range(256)) |
| 12 | + j=0 |
| 13 | + for i in range(256): |
| 14 | + j=(j+s[i]+key[i%key_length])%256 |
| 15 | + s[i],s[j]=s[j],s[i] |
| 16 | + return s |
| 17 | + |
| 18 | + def _prga(self) -> int: |
| 19 | + """Pseudo-Random Generation Algorithm (PRGA)""" |
| 20 | + i=0 |
| 21 | + j=0 |
| 22 | + while True: |
| 23 | + i=(i+1)%256 |
| 24 | + j=(j+self.s[i])%256 |
| 25 | + self.s[i],self.s[j]=self.s[j],self.s[i] |
| 26 | + yield self.s[(self.s[i]+self.s[j])%256] |
| 27 | + |
| 28 | + def _reset_state(self): |
| 29 | + """Reset state for each encryption/decryption.""" |
| 30 | + self.s=self._ksa(self.key) |
| 31 | + |
| 32 | + def encrypt(self,plaintext:bytes)->bytes: |
| 33 | + """Encrypt plaintext using RC4""" |
| 34 | + self._reset_state() |
| 35 | + prga=self._prga() |
| 36 | + return bytes([p^next(prga) for p in plaintext]) |
| 37 | + |
| 38 | + def decrypt(self,ciphertext:bytes)->bytes: |
| 39 | + """Decrypt ciphertext using RC4 (Same as encryption)""" |
| 40 | + return self.encrypt(ciphertext) |
| 41 | + |
| 42 | + |
| 43 | +if __name__ == "__main__": |
| 44 | + key=b"SecretKey" |
| 45 | + rc4=RC4(key) |
| 46 | + |
| 47 | + plaintext=b"Hello, RC4 Cipher!" |
| 48 | + print("Original:",plaintext) |
| 49 | + |
| 50 | + ciphertext=rc4.encrypt(plaintext) |
| 51 | + print("Encrypted:",ciphertext) |
| 52 | + |
| 53 | + decrypted_text=rc4.decrypt(ciphertext) |
| 54 | + print("Decrypted:",decrypted_text) |
| 55 | + |
| 56 | + assert plaintext==decrypted_text, "Decryption failed" |
| 57 | + print("Encryption and decryption successful.") |
0 commit comments