mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Add typehints ciphers and bool alg (#3264)
* updating DIRECTORY.md * updating DIRECTORY.md * Fixed accidental commit of file I have't touched * fixup! Format Python code with psf/black push * updating DIRECTORY.md * updating DIRECTORY.md * Fixed some suggested coding style issues * Update rsa_key_generator.py * Update rsa_key_generator.py Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: John Law <johnlaw.po@gmail.com>
This commit is contained in:
parent
5b024f4dd5
commit
9d745b6156
|
@ -1,4 +1,4 @@
|
||||||
def compare_string(string1, string2):
|
def compare_string(string1: str, string2: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> compare_string('0010','0110')
|
>>> compare_string('0010','0110')
|
||||||
'0_10'
|
'0_10'
|
||||||
|
@ -19,7 +19,7 @@ def compare_string(string1, string2):
|
||||||
return "".join(l1)
|
return "".join(l1)
|
||||||
|
|
||||||
|
|
||||||
def check(binary):
|
def check(binary: [str]) -> [str]:
|
||||||
"""
|
"""
|
||||||
>>> check(['0.00.01.5'])
|
>>> check(['0.00.01.5'])
|
||||||
['0.00.01.5']
|
['0.00.01.5']
|
||||||
|
@ -43,7 +43,7 @@ def check(binary):
|
||||||
binary = list(set(temp))
|
binary = list(set(temp))
|
||||||
|
|
||||||
|
|
||||||
def decimal_to_binary(no_of_variable, minterms):
|
def decimal_to_binary(no_of_variable: int, minterms: [float]) -> [str]:
|
||||||
"""
|
"""
|
||||||
>>> decimal_to_binary(3,[1.5])
|
>>> decimal_to_binary(3,[1.5])
|
||||||
['0.00.01.5']
|
['0.00.01.5']
|
||||||
|
@ -59,7 +59,7 @@ def decimal_to_binary(no_of_variable, minterms):
|
||||||
return temp
|
return temp
|
||||||
|
|
||||||
|
|
||||||
def is_for_table(string1, string2, count):
|
def is_for_table(string1: str, string2: str, count: int) -> bool:
|
||||||
"""
|
"""
|
||||||
>>> is_for_table('__1','011',2)
|
>>> is_for_table('__1','011',2)
|
||||||
True
|
True
|
||||||
|
@ -79,7 +79,7 @@ def is_for_table(string1, string2, count):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def selection(chart, prime_implicants):
|
def selection(chart: [[int]], prime_implicants: [str]) -> [str]:
|
||||||
"""
|
"""
|
||||||
>>> selection([[1]],['0.00.01.5'])
|
>>> selection([[1]],['0.00.01.5'])
|
||||||
['0.00.01.5']
|
['0.00.01.5']
|
||||||
|
@ -126,7 +126,7 @@ def selection(chart, prime_implicants):
|
||||||
chart[j][i] = 0
|
chart[j][i] = 0
|
||||||
|
|
||||||
|
|
||||||
def prime_implicant_chart(prime_implicants, binary):
|
def prime_implicant_chart(prime_implicants: [str], binary: [str]) -> [[int]]:
|
||||||
"""
|
"""
|
||||||
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
|
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
|
||||||
[[1]]
|
[[1]]
|
||||||
|
|
|
@ -29,7 +29,7 @@ def main():
|
||||||
print(f"\n{mode.title()}ed text: \n{translated}")
|
print(f"\n{mode.title()}ed text: \n{translated}")
|
||||||
|
|
||||||
|
|
||||||
def check_keys(keyA, keyB, mode):
|
def check_keys(keyA: int, keyB: int, mode: str) -> None:
|
||||||
if mode == "encrypt":
|
if mode == "encrypt":
|
||||||
if keyA == 1:
|
if keyA == 1:
|
||||||
sys.exit(
|
sys.exit(
|
||||||
|
@ -90,7 +90,7 @@ def decrypt_message(key: int, message: str) -> str:
|
||||||
return plainText
|
return plainText
|
||||||
|
|
||||||
|
|
||||||
def get_random_key():
|
def get_random_key() -> int:
|
||||||
while True:
|
while True:
|
||||||
keyA = random.randint(2, len(SYMBOLS))
|
keyA = random.randint(2, len(SYMBOLS))
|
||||||
keyB = random.randint(2, len(SYMBOLS))
|
keyB = random.randint(2, len(SYMBOLS))
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
def encode_base64(text):
|
def encode_base64(text: str) -> str:
|
||||||
r"""
|
r"""
|
||||||
>>> encode_base64('WELCOME to base64 encoding 😁')
|
>>> encode_base64('WELCOME to base64 encoding 😁')
|
||||||
'V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ=='
|
'V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ=='
|
||||||
|
@ -33,7 +33,7 @@ def encode_base64(text):
|
||||||
return r[0 : len(r) - len(p)] + p
|
return r[0 : len(r) - len(p)] + p
|
||||||
|
|
||||||
|
|
||||||
def decode_base64(text):
|
def decode_base64(text: str) -> str:
|
||||||
r"""
|
r"""
|
||||||
>>> decode_base64('V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ==')
|
>>> decode_base64('V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ==')
|
||||||
'WELCOME to base64 encoding 😁'
|
'WELCOME to base64 encoding 😁'
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
def decrypt(message):
|
def decrypt(message: str) -> None:
|
||||||
"""
|
"""
|
||||||
>>> decrypt('TMDETUX PMDVU')
|
>>> decrypt('TMDETUX PMDVU')
|
||||||
Decryption using Key #0: TMDETUX PMDVU
|
Decryption using Key #0: TMDETUX PMDVU
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
def gcd(a, b):
|
def gcd(a: int, b: int) -> int:
|
||||||
while a != 0:
|
while a != 0:
|
||||||
a, b = b % a, a
|
a, b = b % a, a
|
||||||
return b
|
return b
|
||||||
|
|
||||||
|
|
||||||
def findModInverse(a, m):
|
def findModInverse(a: int, m: int) -> int:
|
||||||
if gcd(a, m) != 1:
|
if gcd(a, m) != 1:
|
||||||
return None
|
return None
|
||||||
u1, u2, u3 = 1, 0, a
|
u1, u2, u3 = 1, 0, a
|
||||||
|
|
|
@ -1,12 +1,14 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
|
||||||
def decrypt_caesar_with_chi_squared(
|
def decrypt_caesar_with_chi_squared(
|
||||||
ciphertext: str,
|
ciphertext: str,
|
||||||
cipher_alphabet=None,
|
cipher_alphabet: str = None,
|
||||||
frequencies_dict=None,
|
frequencies_dict: str = None,
|
||||||
case_sensetive: bool = False,
|
case_sensetive: bool = False,
|
||||||
) -> tuple:
|
) -> Tuple[int, float, str]:
|
||||||
"""
|
"""
|
||||||
Basic Usage
|
Basic Usage
|
||||||
===========
|
===========
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def miller_rabin(n, allow_probable=False):
|
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
|
||||||
"""Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.
|
"""Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.
|
||||||
|
|
||||||
Uses numerical analysis results to return whether or not the passed number
|
Uses numerical analysis results to return whether or not the passed number
|
||||||
|
@ -87,7 +87,7 @@ def miller_rabin(n, allow_probable=False):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def test_miller_rabin():
|
def test_miller_rabin() -> None:
|
||||||
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
|
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
|
||||||
and a prime in each range.
|
and a prime in each range.
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
def find_primitive(n):
|
def find_primitive(n: int) -> int:
|
||||||
for r in range(1, n):
|
for r in range(1, n):
|
||||||
li = []
|
li = []
|
||||||
for x in range(n - 1):
|
for x in range(n - 1):
|
||||||
|
|
|
@ -19,7 +19,7 @@ def main():
|
||||||
# so I used 4.80 Algorithm in
|
# so I used 4.80 Algorithm in
|
||||||
# Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
|
# Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
|
||||||
# and it seems to run nicely!
|
# and it seems to run nicely!
|
||||||
def primitiveRoot(p_val):
|
def primitiveRoot(p_val: int) -> int:
|
||||||
print("Generating primitive root of p")
|
print("Generating primitive root of p")
|
||||||
while True:
|
while True:
|
||||||
g = random.randrange(3, p_val)
|
g = random.randrange(3, p_val)
|
||||||
|
@ -30,7 +30,7 @@ def primitiveRoot(p_val):
|
||||||
return g
|
return g
|
||||||
|
|
||||||
|
|
||||||
def generateKey(keySize):
|
def generateKey(keySize: int) -> ((int, int, int, int), (int, int)):
|
||||||
print("Generating prime p...")
|
print("Generating prime p...")
|
||||||
p = rabinMiller.generateLargePrime(keySize) # select large prime number.
|
p = rabinMiller.generateLargePrime(keySize) # select large prime number.
|
||||||
e_1 = primitiveRoot(p) # one primitive root on modulo p.
|
e_1 = primitiveRoot(p) # one primitive root on modulo p.
|
||||||
|
@ -43,7 +43,7 @@ def generateKey(keySize):
|
||||||
return publicKey, privateKey
|
return publicKey, privateKey
|
||||||
|
|
||||||
|
|
||||||
def makeKeyFiles(name, keySize):
|
def makeKeyFiles(name: str, keySize: int):
|
||||||
if os.path.exists("%s_pubkey.txt" % name) or os.path.exists(
|
if os.path.exists("%s_pubkey.txt" % name) or os.path.exists(
|
||||||
"%s_privkey.txt" % name
|
"%s_privkey.txt" % name
|
||||||
):
|
):
|
||||||
|
|
|
@ -64,7 +64,7 @@ class HillCipher:
|
||||||
|
|
||||||
to_int = numpy.vectorize(lambda x: round(x))
|
to_int = numpy.vectorize(lambda x: round(x))
|
||||||
|
|
||||||
def __init__(self, encrypt_key):
|
def __init__(self, encrypt_key: int):
|
||||||
"""
|
"""
|
||||||
encrypt_key is an NxN numpy array
|
encrypt_key is an NxN numpy array
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
def mixed_keyword(key="college", pt="UNIVERSITY"):
|
def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
For key:hello
|
For key:hello
|
||||||
|
|
|
@ -57,7 +57,7 @@ MORSE_CODE_DICT = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def encrypt(message):
|
def encrypt(message: str) -> str:
|
||||||
cipher = ""
|
cipher = ""
|
||||||
for letter in message:
|
for letter in message:
|
||||||
if letter != " ":
|
if letter != " ":
|
||||||
|
@ -69,7 +69,7 @@ def encrypt(message):
|
||||||
return cipher[:-1]
|
return cipher[:-1]
|
||||||
|
|
||||||
|
|
||||||
def decrypt(message):
|
def decrypt(message: str) -> str:
|
||||||
decipher = ""
|
decipher = ""
|
||||||
letters = message.split(" ")
|
letters = message.split(" ")
|
||||||
for letter in letters:
|
for letter in letters:
|
||||||
|
|
|
@ -2,7 +2,7 @@ import random
|
||||||
|
|
||||||
|
|
||||||
class Onepad:
|
class Onepad:
|
||||||
def encrypt(self, text):
|
def encrypt(self, text: str) -> ([str], [int]):
|
||||||
"""Function to encrypt text using pseudo-random numbers"""
|
"""Function to encrypt text using pseudo-random numbers"""
|
||||||
plain = [ord(i) for i in text]
|
plain = [ord(i) for i in text]
|
||||||
key = []
|
key = []
|
||||||
|
@ -14,7 +14,7 @@ class Onepad:
|
||||||
key.append(k)
|
key.append(k)
|
||||||
return cipher, key
|
return cipher, key
|
||||||
|
|
||||||
def decrypt(self, cipher, key):
|
def decrypt(self, cipher: [str], key: [int]) -> str:
|
||||||
"""Function to decrypt text using pseudo-random numbers."""
|
"""Function to decrypt text using pseudo-random numbers."""
|
||||||
plain = []
|
plain = []
|
||||||
for i in range(len(key)):
|
for i in range(len(key)):
|
||||||
|
|
|
@ -11,7 +11,7 @@ def chunker(seq, size):
|
||||||
yield chunk
|
yield chunk
|
||||||
|
|
||||||
|
|
||||||
def prepare_input(dirty):
|
def prepare_input(dirty: str) -> str:
|
||||||
"""
|
"""
|
||||||
Prepare the plaintext by up-casing it
|
Prepare the plaintext by up-casing it
|
||||||
and separating repeated letters with X's
|
and separating repeated letters with X's
|
||||||
|
@ -37,7 +37,7 @@ def prepare_input(dirty):
|
||||||
return clean
|
return clean
|
||||||
|
|
||||||
|
|
||||||
def generate_table(key):
|
def generate_table(key: str) -> [str]:
|
||||||
|
|
||||||
# I and J are used interchangeably to allow
|
# I and J are used interchangeably to allow
|
||||||
# us to use a 5x5 table (25 letters)
|
# us to use a 5x5 table (25 letters)
|
||||||
|
@ -59,7 +59,7 @@ def generate_table(key):
|
||||||
return table
|
return table
|
||||||
|
|
||||||
|
|
||||||
def encode(plaintext, key):
|
def encode(plaintext: str, key: str) -> str:
|
||||||
table = generate_table(key)
|
table = generate_table(key)
|
||||||
plaintext = prepare_input(plaintext)
|
plaintext = prepare_input(plaintext)
|
||||||
ciphertext = ""
|
ciphertext = ""
|
||||||
|
@ -82,7 +82,7 @@ def encode(plaintext, key):
|
||||||
return ciphertext
|
return ciphertext
|
||||||
|
|
||||||
|
|
||||||
def decode(ciphertext, key):
|
def decode(ciphertext: str, key: str) -> str:
|
||||||
table = generate_table(key)
|
table = generate_table(key)
|
||||||
plaintext = ""
|
plaintext = ""
|
||||||
|
|
||||||
|
|
|
@ -28,7 +28,7 @@ alphabet = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def generate_table(key):
|
def generate_table(key: str) -> [(str, str)]:
|
||||||
"""
|
"""
|
||||||
>>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE
|
>>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE
|
||||||
[('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
|
[('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
|
||||||
|
@ -38,7 +38,7 @@ def generate_table(key):
|
||||||
return [alphabet[char] for char in key.upper()]
|
return [alphabet[char] for char in key.upper()]
|
||||||
|
|
||||||
|
|
||||||
def encrypt(key, words):
|
def encrypt(key: str, words: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> encrypt('marvin', 'jessica')
|
>>> encrypt('marvin', 'jessica')
|
||||||
'QRACRWU'
|
'QRACRWU'
|
||||||
|
@ -52,7 +52,7 @@ def encrypt(key, words):
|
||||||
return cipher
|
return cipher
|
||||||
|
|
||||||
|
|
||||||
def decrypt(key, words):
|
def decrypt(key: str, words: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> decrypt('marvin', 'QRACRWU')
|
>>> decrypt('marvin', 'QRACRWU')
|
||||||
'JESSICA'
|
'JESSICA'
|
||||||
|
@ -60,7 +60,7 @@ def decrypt(key, words):
|
||||||
return encrypt(key, words)
|
return encrypt(key, words)
|
||||||
|
|
||||||
|
|
||||||
def get_position(table, char):
|
def get_position(table: [(str, str)], char: str) -> (int, int) or (None, None):
|
||||||
"""
|
"""
|
||||||
>>> table = [
|
>>> table = [
|
||||||
... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
|
... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
|
||||||
|
@ -76,7 +76,7 @@ def get_position(table, char):
|
||||||
return (None, None) if row == -1 else (row, table[row].index(char))
|
return (None, None) if row == -1 else (row, table[row].index(char))
|
||||||
|
|
||||||
|
|
||||||
def get_opponent(table, char):
|
def get_opponent(table: [(str, str)], char: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> table = [
|
>>> table = [
|
||||||
... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
|
... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
|
||||||
def rabinMiller(num):
|
def rabinMiller(num: int) -> bool:
|
||||||
s = num - 1
|
s = num - 1
|
||||||
t = 0
|
t = 0
|
||||||
|
|
||||||
|
@ -25,7 +25,7 @@ def rabinMiller(num):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def isPrime(num):
|
def isPrime(num: int) -> bool:
|
||||||
if num < 2:
|
if num < 2:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
@ -210,7 +210,7 @@ def isPrime(num):
|
||||||
return rabinMiller(num)
|
return rabinMiller(num)
|
||||||
|
|
||||||
|
|
||||||
def generateLargePrime(keysize=1024):
|
def generateLargePrime(keysize: int = 1024) -> int:
|
||||||
while True:
|
while True:
|
||||||
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
|
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
|
||||||
if isPrime(num):
|
if isPrime(num):
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
def dencrypt(s: str, n: int = 13):
|
def dencrypt(s: str, n: int = 13) -> str:
|
||||||
"""
|
"""
|
||||||
https://en.wikipedia.org/wiki/ROT13
|
https://en.wikipedia.org/wiki/ROT13
|
||||||
|
|
||||||
|
|
|
@ -40,7 +40,7 @@ def main():
|
||||||
print(decryptedText)
|
print(decryptedText)
|
||||||
|
|
||||||
|
|
||||||
def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE):
|
def getBlocksFromText(message: int, blockSize: int = DEFAULT_BLOCK_SIZE) -> [int]:
|
||||||
messageBytes = message.encode("ascii")
|
messageBytes = message.encode("ascii")
|
||||||
|
|
||||||
blockInts = []
|
blockInts = []
|
||||||
|
@ -52,7 +52,9 @@ def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE):
|
||||||
return blockInts
|
return blockInts
|
||||||
|
|
||||||
|
|
||||||
def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE):
|
def getTextFromBlocks(
|
||||||
|
blockInts: [int], messageLength: int, blockSize: int = DEFAULT_BLOCK_SIZE
|
||||||
|
) -> str:
|
||||||
message = []
|
message = []
|
||||||
for blockInt in blockInts:
|
for blockInt in blockInts:
|
||||||
blockMessage = []
|
blockMessage = []
|
||||||
|
@ -65,7 +67,9 @@ def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE):
|
||||||
return "".join(message)
|
return "".join(message)
|
||||||
|
|
||||||
|
|
||||||
def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE):
|
def encryptMessage(
|
||||||
|
message: str, key: (int, int), blockSize: int = DEFAULT_BLOCK_SIZE
|
||||||
|
) -> [int]:
|
||||||
encryptedBlocks = []
|
encryptedBlocks = []
|
||||||
n, e = key
|
n, e = key
|
||||||
|
|
||||||
|
@ -74,7 +78,12 @@ def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE):
|
||||||
return encryptedBlocks
|
return encryptedBlocks
|
||||||
|
|
||||||
|
|
||||||
def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_SIZE):
|
def decryptMessage(
|
||||||
|
encryptedBlocks: [int],
|
||||||
|
messageLength: int,
|
||||||
|
key: (int, int),
|
||||||
|
blockSize: int = DEFAULT_BLOCK_SIZE,
|
||||||
|
) -> str:
|
||||||
decryptedBlocks = []
|
decryptedBlocks = []
|
||||||
n, d = key
|
n, d = key
|
||||||
for block in encryptedBlocks:
|
for block in encryptedBlocks:
|
||||||
|
@ -82,7 +91,7 @@ def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_
|
||||||
return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)
|
return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)
|
||||||
|
|
||||||
|
|
||||||
def readKeyFile(keyFilename):
|
def readKeyFile(keyFilename: str) -> (int, int, int):
|
||||||
with open(keyFilename) as fo:
|
with open(keyFilename) as fo:
|
||||||
content = fo.read()
|
content = fo.read()
|
||||||
keySize, n, EorD = content.split(",")
|
keySize, n, EorD = content.split(",")
|
||||||
|
@ -90,8 +99,11 @@ def readKeyFile(keyFilename):
|
||||||
|
|
||||||
|
|
||||||
def encryptAndWriteToFile(
|
def encryptAndWriteToFile(
|
||||||
messageFilename, keyFilename, message, blockSize=DEFAULT_BLOCK_SIZE
|
messageFilename: str,
|
||||||
):
|
keyFilename: str,
|
||||||
|
message: str,
|
||||||
|
blockSize: int = DEFAULT_BLOCK_SIZE,
|
||||||
|
) -> str:
|
||||||
keySize, n, e = readKeyFile(keyFilename)
|
keySize, n, e = readKeyFile(keyFilename)
|
||||||
if keySize < blockSize * 8:
|
if keySize < blockSize * 8:
|
||||||
sys.exit(
|
sys.exit(
|
||||||
|
@ -112,7 +124,7 @@ def encryptAndWriteToFile(
|
||||||
return encryptedContent
|
return encryptedContent
|
||||||
|
|
||||||
|
|
||||||
def readFromFileAndDecrypt(messageFilename, keyFilename):
|
def readFromFileAndDecrypt(messageFilename: str, keyFilename: str) -> str:
|
||||||
keySize, n, d = readKeyFile(keyFilename)
|
keySize, n, d = readKeyFile(keyFilename)
|
||||||
with open(messageFilename) as fo:
|
with open(messageFilename) as fo:
|
||||||
content = fo.read()
|
content = fo.read()
|
||||||
|
|
|
@ -13,7 +13,7 @@ import math
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
|
||||||
def rsafactor(d: int, e: int, N: int) -> list[int]:
|
def rsafactor(d: int, e: int, N: int) -> [int]:
|
||||||
"""
|
"""
|
||||||
This function returns the factors of N, where p*q=N
|
This function returns the factors of N, where p*q=N
|
||||||
Return: [p, q]
|
Return: [p, q]
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
import sys
|
import sys
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
from . import cryptomath_module as cryptoMath
|
from . import cryptomath_module as cryptoMath
|
||||||
from . import rabin_miller as rabinMiller
|
from . import rabin_miller as rabinMiller
|
||||||
|
@ -12,7 +13,7 @@ def main():
|
||||||
print("Key files generation successful.")
|
print("Key files generation successful.")
|
||||||
|
|
||||||
|
|
||||||
def generateKey(keySize):
|
def generateKey(keySize: int) -> Tuple[Tuple[int, int], Tuple[int, int]]:
|
||||||
print("Generating prime p...")
|
print("Generating prime p...")
|
||||||
p = rabinMiller.generateLargePrime(keySize)
|
p = rabinMiller.generateLargePrime(keySize)
|
||||||
print("Generating prime q...")
|
print("Generating prime q...")
|
||||||
|
@ -33,7 +34,7 @@ def generateKey(keySize):
|
||||||
return (publicKey, privateKey)
|
return (publicKey, privateKey)
|
||||||
|
|
||||||
|
|
||||||
def makeKeyFiles(name, keySize):
|
def makeKeyFiles(name: int, keySize: int) -> None:
|
||||||
if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists(
|
if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists(
|
||||||
"%s_privkey.txt" % (name)
|
"%s_privkey.txt" % (name)
|
||||||
):
|
):
|
||||||
|
|
|
@ -21,7 +21,7 @@ def main():
|
||||||
print("\n{}ion: \n{}".format(mode.title(), translated))
|
print("\n{}ion: \n{}".format(mode.title(), translated))
|
||||||
|
|
||||||
|
|
||||||
def checkValidKey(key):
|
def checkValidKey(key: str) -> None:
|
||||||
keyList = list(key)
|
keyList = list(key)
|
||||||
lettersList = list(LETTERS)
|
lettersList = list(LETTERS)
|
||||||
keyList.sort()
|
keyList.sort()
|
||||||
|
@ -31,7 +31,7 @@ def checkValidKey(key):
|
||||||
sys.exit("Error in the key or symbol set.")
|
sys.exit("Error in the key or symbol set.")
|
||||||
|
|
||||||
|
|
||||||
def encryptMessage(key, message):
|
def encryptMessage(key: str, message: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
|
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
|
||||||
'Ilcrism Olcvs'
|
'Ilcrism Olcvs'
|
||||||
|
@ -39,7 +39,7 @@ def encryptMessage(key, message):
|
||||||
return translateMessage(key, message, "encrypt")
|
return translateMessage(key, message, "encrypt")
|
||||||
|
|
||||||
|
|
||||||
def decryptMessage(key, message):
|
def decryptMessage(key: str, message: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
|
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
|
||||||
'Harshil Darji'
|
'Harshil Darji'
|
||||||
|
@ -47,7 +47,7 @@ def decryptMessage(key, message):
|
||||||
return translateMessage(key, message, "decrypt")
|
return translateMessage(key, message, "decrypt")
|
||||||
|
|
||||||
|
|
||||||
def translateMessage(key, message, mode):
|
def translateMessage(key: str, message: str, mode: str) -> str:
|
||||||
translated = ""
|
translated = ""
|
||||||
charsA = LETTERS
|
charsA = LETTERS
|
||||||
charsB = key
|
charsB = key
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# https://en.wikipedia.org/wiki/Trifid_cipher
|
# https://en.wikipedia.org/wiki/Trifid_cipher
|
||||||
|
|
||||||
|
|
||||||
def __encryptPart(messagePart, character2Number):
|
def __encryptPart(messagePart: str, character2Number: dict) -> str:
|
||||||
one, two, three = "", "", ""
|
one, two, three = "", "", ""
|
||||||
tmp = []
|
tmp = []
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ def __encryptPart(messagePart, character2Number):
|
||||||
return one + two + three
|
return one + two + three
|
||||||
|
|
||||||
|
|
||||||
def __decryptPart(messagePart, character2Number):
|
def __decryptPart(messagePart: str, character2Number: dict) -> (str, str, str):
|
||||||
tmp, thisPart = "", ""
|
tmp, thisPart = "", ""
|
||||||
result = []
|
result = []
|
||||||
|
|
||||||
|
@ -32,7 +32,7 @@ def __decryptPart(messagePart, character2Number):
|
||||||
return result[0], result[1], result[2]
|
return result[0], result[1], result[2]
|
||||||
|
|
||||||
|
|
||||||
def __prepare(message, alphabet):
|
def __prepare(message: str, alphabet: str) -> (str, str, dict, dict):
|
||||||
# Validate message and alphabet, set to upper and remove spaces
|
# Validate message and alphabet, set to upper and remove spaces
|
||||||
alphabet = alphabet.replace(" ", "").upper()
|
alphabet = alphabet.replace(" ", "").upper()
|
||||||
message = message.replace(" ", "").upper()
|
message = message.replace(" ", "").upper()
|
||||||
|
@ -83,7 +83,9 @@ def __prepare(message, alphabet):
|
||||||
return message, alphabet, character2Number, number2Character
|
return message, alphabet, character2Number, number2Character
|
||||||
|
|
||||||
|
|
||||||
def encryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
|
def encryptMessage(
|
||||||
|
message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5
|
||||||
|
) -> str:
|
||||||
message, alphabet, character2Number, number2Character = __prepare(message, alphabet)
|
message, alphabet, character2Number, number2Character = __prepare(message, alphabet)
|
||||||
encrypted, encrypted_numeric = "", ""
|
encrypted, encrypted_numeric = "", ""
|
||||||
|
|
||||||
|
@ -96,7 +98,9 @@ def encryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
|
||||||
return encrypted
|
return encrypted
|
||||||
|
|
||||||
|
|
||||||
def decryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
|
def decryptMessage(
|
||||||
|
message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5
|
||||||
|
) -> str:
|
||||||
message, alphabet, character2Number, number2Character = __prepare(message, alphabet)
|
message, alphabet, character2Number, number2Character = __prepare(message, alphabet)
|
||||||
decrypted_numeric = []
|
decrypted_numeric = []
|
||||||
decrypted = ""
|
decrypted = ""
|
||||||
|
|
|
@ -22,7 +22,7 @@ def main():
|
||||||
print("Output:\n%s" % (text + "|"))
|
print("Output:\n%s" % (text + "|"))
|
||||||
|
|
||||||
|
|
||||||
def encryptMessage(key, message):
|
def encryptMessage(key: int, message: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> encryptMessage(6, 'Harshil Darji')
|
>>> encryptMessage(6, 'Harshil Darji')
|
||||||
'Hlia rDsahrij'
|
'Hlia rDsahrij'
|
||||||
|
@ -36,7 +36,7 @@ def encryptMessage(key, message):
|
||||||
return "".join(cipherText)
|
return "".join(cipherText)
|
||||||
|
|
||||||
|
|
||||||
def decryptMessage(key, message):
|
def decryptMessage(key: int, message: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> decryptMessage(6, 'Hlia rDsahrij')
|
>>> decryptMessage(6, 'Hlia rDsahrij')
|
||||||
'Harshil Darji'
|
'Harshil Darji'
|
||||||
|
|
|
@ -17,7 +17,7 @@ def main():
|
||||||
print(translated)
|
print(translated)
|
||||||
|
|
||||||
|
|
||||||
def encryptMessage(key, message):
|
def encryptMessage(key: str, message: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.')
|
>>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.')
|
||||||
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
|
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
|
||||||
|
@ -25,7 +25,7 @@ def encryptMessage(key, message):
|
||||||
return translateMessage(key, message, "encrypt")
|
return translateMessage(key, message, "encrypt")
|
||||||
|
|
||||||
|
|
||||||
def decryptMessage(key, message):
|
def decryptMessage(key: str, message: str) -> str:
|
||||||
"""
|
"""
|
||||||
>>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
|
>>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
|
||||||
'This is Harshil Darji from Dharmaj.'
|
'This is Harshil Darji from Dharmaj.'
|
||||||
|
@ -33,7 +33,7 @@ def decryptMessage(key, message):
|
||||||
return translateMessage(key, message, "decrypt")
|
return translateMessage(key, message, "decrypt")
|
||||||
|
|
||||||
|
|
||||||
def translateMessage(key, message, mode):
|
def translateMessage(key: str, message: str, mode: str) -> str:
|
||||||
translated = []
|
translated = []
|
||||||
keyIndex = 0
|
keyIndex = 0
|
||||||
key = key.upper()
|
key = key.upper()
|
||||||
|
|
|
@ -19,7 +19,7 @@
|
||||||
|
|
||||||
|
|
||||||
class XORCipher:
|
class XORCipher:
|
||||||
def __init__(self, key=0):
|
def __init__(self, key: int = 0):
|
||||||
"""
|
"""
|
||||||
simple constructor that receives a key or uses
|
simple constructor that receives a key or uses
|
||||||
default key = 0
|
default key = 0
|
||||||
|
@ -28,7 +28,7 @@ class XORCipher:
|
||||||
# private field
|
# private field
|
||||||
self.__key = key
|
self.__key = key
|
||||||
|
|
||||||
def encrypt(self, content, key):
|
def encrypt(self, content: str, key: int) -> [str]:
|
||||||
"""
|
"""
|
||||||
input: 'content' of type string and 'key' of type int
|
input: 'content' of type string and 'key' of type int
|
||||||
output: encrypted string 'content' as a list of chars
|
output: encrypted string 'content' as a list of chars
|
||||||
|
@ -53,7 +53,7 @@ class XORCipher:
|
||||||
|
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
def decrypt(self, content, key):
|
def decrypt(self, content: str, key: int) -> [str]:
|
||||||
"""
|
"""
|
||||||
input: 'content' of type list and 'key' of type int
|
input: 'content' of type list and 'key' of type int
|
||||||
output: decrypted string 'content' as a list of chars
|
output: decrypted string 'content' as a list of chars
|
||||||
|
@ -78,7 +78,7 @@ class XORCipher:
|
||||||
|
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
def encrypt_string(self, content, key=0):
|
def encrypt_string(self, content: str, key: int = 0) -> str:
|
||||||
"""
|
"""
|
||||||
input: 'content' of type string and 'key' of type int
|
input: 'content' of type string and 'key' of type int
|
||||||
output: encrypted string 'content'
|
output: encrypted string 'content'
|
||||||
|
@ -103,7 +103,7 @@ class XORCipher:
|
||||||
|
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
def decrypt_string(self, content, key=0):
|
def decrypt_string(self, content: str, key: int = 0) -> str:
|
||||||
"""
|
"""
|
||||||
input: 'content' of type string and 'key' of type int
|
input: 'content' of type string and 'key' of type int
|
||||||
output: decrypted string 'content'
|
output: decrypted string 'content'
|
||||||
|
@ -128,7 +128,7 @@ class XORCipher:
|
||||||
|
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
def encrypt_file(self, file, key=0):
|
def encrypt_file(self, file: str, key: int = 0) -> bool:
|
||||||
"""
|
"""
|
||||||
input: filename (str) and a key (int)
|
input: filename (str) and a key (int)
|
||||||
output: returns true if encrypt process was
|
output: returns true if encrypt process was
|
||||||
|
@ -153,7 +153,7 @@ class XORCipher:
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def decrypt_file(self, file, key):
|
def decrypt_file(self, file: str, key: int) -> bool:
|
||||||
"""
|
"""
|
||||||
input: filename (str) and a key (int)
|
input: filename (str) and a key (int)
|
||||||
output: returns true if decrypt process was
|
output: returns true if decrypt process was
|
||||||
|
|
Loading…
Reference in New Issue
Block a user