mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-05 02:40:16 +00:00
0601b56173
* Contributes to #9943 Added doctest to largest_of_very_large_numbers.py Added doctest to word_patterns.py Added doctest to onepad_cipher.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Contributes to #9943 Added doctest to maths/largest_of_very_large_numbers.py Added doctest to strings/word_patterns.py Added doctest to ciphers/onepad_cipher.py * Add tests without modifying code #10740 Added test to maths/largest_of_very_large_numbers Added test to strings/word_patterns.py Added test to ciphers/onepad_cipher.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
65 lines
1.8 KiB
Python
65 lines
1.8 KiB
Python
import random
|
|
|
|
|
|
class Onepad:
|
|
@staticmethod
|
|
def encrypt(text: str) -> tuple[list[int], list[int]]:
|
|
"""
|
|
Function to encrypt text using pseudo-random numbers
|
|
>>> Onepad().encrypt("")
|
|
([], [])
|
|
>>> Onepad().encrypt([])
|
|
([], [])
|
|
>>> random.seed(1)
|
|
>>> Onepad().encrypt(" ")
|
|
([6969], [69])
|
|
>>> random.seed(1)
|
|
>>> Onepad().encrypt("Hello")
|
|
([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61])
|
|
>>> Onepad().encrypt(1)
|
|
Traceback (most recent call last):
|
|
...
|
|
TypeError: 'int' object is not iterable
|
|
>>> Onepad().encrypt(1.1)
|
|
Traceback (most recent call last):
|
|
...
|
|
TypeError: 'float' object is not iterable
|
|
"""
|
|
plain = [ord(i) for i in text]
|
|
key = []
|
|
cipher = []
|
|
for i in plain:
|
|
k = random.randint(1, 300)
|
|
c = (i + k) * k
|
|
cipher.append(c)
|
|
key.append(k)
|
|
return cipher, key
|
|
|
|
@staticmethod
|
|
def decrypt(cipher: list[int], key: list[int]) -> str:
|
|
"""
|
|
Function to decrypt text using pseudo-random numbers.
|
|
>>> Onepad().decrypt([], [])
|
|
''
|
|
>>> Onepad().decrypt([35], [])
|
|
''
|
|
>>> Onepad().decrypt([], [35])
|
|
Traceback (most recent call last):
|
|
...
|
|
IndexError: list index out of range
|
|
>>> random.seed(1)
|
|
>>> Onepad().decrypt([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61])
|
|
'Hello'
|
|
"""
|
|
plain = []
|
|
for i in range(len(key)):
|
|
p = int((cipher[i] - (key[i]) ** 2) / key[i])
|
|
plain.append(chr(p))
|
|
return "".join(plain)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
c, k = Onepad().encrypt("Hello")
|
|
print(c, k)
|
|
print(Onepad().decrypt(c, k))
|