2018-09-28 04:17:28 +00:00
|
|
|
import random
|
|
|
|
|
2018-07-02 08:07:25 +00:00
|
|
|
|
2018-04-13 15:49:38 +00:00
|
|
|
class Onepad:
|
2021-04-04 05:22:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def encrypt(text: str) -> tuple[list[int], list[int]]:
|
2023-10-22 05:42:26 +00:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
"""
|
2018-07-02 08:07:25 +00:00
|
|
|
plain = [ord(i) for i in text]
|
2018-04-13 15:49:38 +00:00
|
|
|
key = []
|
|
|
|
cipher = []
|
|
|
|
for i in plain:
|
|
|
|
k = random.randint(1, 300)
|
2019-10-05 05:14:13 +00:00
|
|
|
c = (i + k) * k
|
2018-04-13 15:49:38 +00:00
|
|
|
cipher.append(c)
|
|
|
|
key.append(k)
|
|
|
|
return cipher, key
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2021-04-04 05:22:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def decrypt(cipher: list[int], key: list[int]) -> str:
|
2023-10-22 05:42:26 +00:00
|
|
|
"""
|
|
|
|
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'
|
|
|
|
"""
|
2018-04-13 15:49:38 +00:00
|
|
|
plain = []
|
|
|
|
for i in range(len(key)):
|
2019-10-05 05:14:13 +00:00
|
|
|
p = int((cipher[i] - (key[i]) ** 2) / key[i])
|
2018-04-13 15:49:38 +00:00
|
|
|
plain.append(chr(p))
|
2022-10-15 17:29:42 +00:00
|
|
|
return "".join(plain)
|
2018-07-02 08:07:25 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
c, k = Onepad().encrypt("Hello")
|
2018-07-02 08:07:25 +00:00
|
|
|
print(c, k)
|
|
|
|
print(Onepad().decrypt(c, k))
|