Skip to content

Add rc4 cipher#12687

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base:master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,6 +113,7 @@
* [Porta Cipher](ciphers/porta_cipher.py)
* [Rabin Miller](ciphers/rabin_miller.py)
* [Rail Fence Cipher](ciphers/rail_fence_cipher.py)
* [Rc4](ciphers/rc4.py)
* [Rot13](ciphers/rot13.py)
* [Rsa Cipher](ciphers/rsa_cipher.py)
* [Rsa Factorization](ciphers/rsa_factorization.py)
Expand Down
118 changes: 118 additions & 0 deletions ciphers/rc4.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
"""
Implementation of RC4 (Rivest Cipher 4) stream cipher algorithm.
Reference:
- https://en.wikipedia.org/wiki/RC4
"""


defksa(key: bytes) ->list[int]:
"""
Key Scheduling Algorithm (KSA) for RC4.
Args:
key: The secret key as bytes.
Returns:
A permutation (list) of 256 integers (S-box).
Example:
>>> ksa(b'Key')[:5]
[0, 1, 2, 3, 4]
"""
key_length=len(key)
s_box=list(range(256))
j=0

foriinrange(256):
j= (j+s_box[i] +key[i%key_length]) %256
s_box[i], s_box[j] =s_box[j], s_box[i]

returns_box


defprga(s_box: list[int], message_length: int) ->list[int]:
"""
Pseudo-Random Generation Algorithm (PRGA) for RC4.
Args:
s_box: The S-box after KSA.
message_length: Number of bytes to generate.
Returns:
A keystream as a list of integers.
Example:
>>> prga(list(range(256)), 5)
[0, 1, 2, 3, 4]
"""
i=0
j=0
keystream= []

for_inrange(message_length):
i= (i+1) %256
j= (j+s_box[i]) %256
s_box[i], s_box[j] =s_box[j], s_box[i]
k=s_box[(s_box[i] +s_box[j]) %256]
keystream.append(k)

returnkeystream


defrc4(key: bytes, data: bytes) ->bytes:
"""
Encrypt or decrypt data using RC4 stream cipher.
Args:
key: The secret key as bytes.
data: The plaintext or ciphertext as bytes.
Returns:
Encrypted or decrypted output as bytes.
Example:
>>> ciphertext = rc4(b'Key', b'Plaintext')
>>> rc4(b'Key', ciphertext)
b'Plaintext'
"""
s_box=ksa(key)
keystream=prga(s_box, len(data))
output=bytes(
[
data_byte^keystream_byte
fordata_byte, keystream_byteinzip(data, keystream)
]
)
returnoutput


if__name__=="__main__":
importargparse

parser=argparse.ArgumentParser(
description="Encrypt or decrypt data using RC4 cipher."
)
parser.add_argument(
"mode", choices=["encrypt", "decrypt"], help="Mode: encrypt or decrypt"
)
parser.add_argument("key", type=str, help="Encryption/Decryption key")
parser.add_argument("input", type=str, help="Input text")

args=parser.parse_args()

key_bytes=args.key.encode("ascii")
input_bytes=args.input.encode("ascii")

result_bytes=rc4(key_bytes, input_bytes)

ifargs.mode=="encrypt":
print(result_bytes.hex())
else: # decrypt mode
try:
# if user passed hex data, decode it
input_bytes=bytes.fromhex(args.input)
result_bytes=rc4(key_bytes, input_bytes)
print(result_bytes.decode("ascii"))
exceptValueError:
print("Error: Input must be valid hex string when decrypting.")
Loading
close