Skip to content

Algo added #11869

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

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added other/RSA_Algo/__init__.py
Empty file.
139 changes: 139 additions & 0 deletions other/RSA_Algo/rsa_algo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import random
import sys
from sympy import isprime, mod_inverse
from typing import Tuple, List

Check failure on line 4 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

other/RSA_Algo/rsa_algo.py:4:1: UP035 `typing.Tuple` is deprecated, use `tuple` instead

Check failure on line 4 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

other/RSA_Algo/rsa_algo.py:4:1: UP035 `typing.List` is deprecated, use `list` instead

def generate_prime_candidate(length: int) -> int:

Check failure on line 6 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

other/RSA_Algo/rsa_algo.py:1:1: I001 Import block is un-sorted or un-formatted
"""
Generate a large prime number candidate.

Check failure on line 9 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

other/RSA_Algo/rsa_algo.py:9:1: W293 Blank line contains whitespace
>>> p = generate_prime_candidate(16)
>>> isprime(p)
True
"""
p = random.getrandbits(length)
while not isprime(p):
p = random.getrandbits(length)
return p

def generate_keys(keysize: int) -> Tuple[Tuple[int, int], Tuple[int, int]]:

Check failure on line 19 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

other/RSA_Algo/rsa_algo.py:19:36: UP006 Use `tuple` instead of `Tuple` for type annotation

Check failure on line 19 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

other/RSA_Algo/rsa_algo.py:19:42: UP006 Use `tuple` instead of `Tuple` for type annotation

Check failure on line 19 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

other/RSA_Algo/rsa_algo.py:19:59: UP006 Use `tuple` instead of `Tuple` for type annotation
"""
Generate RSA keys.

Check failure on line 22 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

other/RSA_Algo/rsa_algo.py:22:1: W293 Blank line contains whitespace
>>> public, private = generate_keys(16)
>>> len(bin(public)) - 2 # Check bit length of n
32
>>> len(bin(private)) - 2 # Check bit length of n
32
"""
try:
e = d = n = 0

p = generate_prime_candidate(keysize)
q = generate_prime_candidate(keysize)

Check failure on line 34 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

other/RSA_Algo/rsa_algo.py:34:1: W293 Blank line contains whitespace
n = p * q
phi = (p - 1) * (q - 1)

e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)

d = mod_inverse(e, phi)

return ((e, n), (d, n))
except ValueError as ex:
print(f"Value error generating keys: {ex}", file=sys.stderr)
sys.exit(1)
except TypeError as ex:
print(f"Type error generating keys: {ex}", file=sys.stderr)
sys.exit(1)
except Exception as ex:

Check failure on line 53 in other/RSA_Algo/rsa_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (BLE001)

other/RSA_Algo/rsa_algo.py:53:12: BLE001 Do not catch blind exception: `Exception`
print(f"Unexpected error generating keys: {ex}", file=sys.stderr)
sys.exit(1)

def gcd(a: int, b: int) -> int:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: a

Please provide descriptive name for the parameter: b

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: a

Please provide descriptive name for the parameter: b

"""
Compute the greatest common divisor of a and b.

>>> gcd(48, 18)
6
"""
while b != 0:
a, b = b, a % b
return a

def encrypt(pk: Tuple[int, int], plaintext: str) -> List[int]:
"""
Encrypt a message with a public key.

>>> public, private = generate_keys(16)
>>> encrypted = encrypt(public, "test")
>>> isinstance(encrypted, list)
True
"""
try:
key, n = pk
cipher = [(ord(char) ** key) % n for char in plaintext]
return cipher
except TypeError as ex:
print(f"Type error during encryption: {ex}", file=sys.stderr)
return None
except Exception as ex:
print(f"Unexpected error during encryption: {ex}", file=sys.stderr)
return None

def decrypt(pk: Tuple[int, int], ciphertext: List[int]) -> str:
"""
Decrypt a message with a private key.

>>> public, private = generate_keys(16)
>>> encrypted = encrypt(public, "test")
>>> decrypted = decrypt(private, encrypted)
>>> decrypted == "test"
True
"""
try:
key, n = pk
plain = [chr((char ** key) % n) for char in ciphertext]
return ''.join(plain)
except TypeError as ex:
print(f"Type error during decryption: {ex}", file=sys.stderr)
return None
except Exception as ex:
print(f"Unexpected error during decryption: {ex}", file=sys.stderr)
return None

if __name__ == '__main__':
import doctest
doctest.testmod()

try:
keysize = 1024
public, private = generate_keys(keysize)

message = "Hello, RSA!"
print("Original message:", message)

encrypted_msg = encrypt(public, message)
if encrypted_msg:
print("Encrypted message:", encrypted_msg)

decrypted_msg = decrypt(private, encrypted_msg)
if decrypted_msg:
print("Decrypted message:", decrypted_msg)
else:
print("Decryption failed.", file=sys.stderr)
else:
print("Encryption failed.", file=sys.stderr)
except ValueError as ex:
print(f"Value error: {ex}", file=sys.stderr)
sys.exit(1)
except TypeError as ex:
print(f"Type error: {ex}", file=sys.stderr)
sys.exit(1)
except Exception as ex:
print(f"Unexpected error: {ex}", file=sys.stderr)
sys.exit(1)
Loading