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:
Jenia Dysin 2020-10-16 09:11:52 +03:00 committed by GitHub
parent 5b024f4dd5
commit 9d745b6156
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 92 additions and 73 deletions

View File

@ -1,4 +1,4 @@
def compare_string(string1, string2):
def compare_string(string1: str, string2: str) -> str:
"""
>>> compare_string('0010','0110')
'0_10'
@ -19,7 +19,7 @@ def compare_string(string1, string2):
return "".join(l1)
def check(binary):
def check(binary: [str]) -> [str]:
"""
>>> check(['0.00.01.5'])
['0.00.01.5']
@ -43,7 +43,7 @@ def check(binary):
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])
['0.00.01.5']
@ -59,7 +59,7 @@ def decimal_to_binary(no_of_variable, minterms):
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)
True
@ -79,7 +79,7 @@ def is_for_table(string1, string2, count):
return False
def selection(chart, prime_implicants):
def selection(chart: [[int]], prime_implicants: [str]) -> [str]:
"""
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
@ -126,7 +126,7 @@ def selection(chart, prime_implicants):
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'])
[[1]]

View File

@ -29,7 +29,7 @@ def main():
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 keyA == 1:
sys.exit(
@ -90,7 +90,7 @@ def decrypt_message(key: int, message: str) -> str:
return plainText
def get_random_key():
def get_random_key() -> int:
while True:
keyA = random.randint(2, len(SYMBOLS))
keyB = random.randint(2, len(SYMBOLS))

View File

@ -1,4 +1,4 @@
def encode_base64(text):
def encode_base64(text: str) -> str:
r"""
>>> encode_base64('WELCOME to base64 encoding 😁')
'V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ=='
@ -33,7 +33,7 @@ def encode_base64(text):
return r[0 : len(r) - len(p)] + p
def decode_base64(text):
def decode_base64(text: str) -> str:
r"""
>>> decode_base64('V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ==')
'WELCOME to base64 encoding 😁'

View File

@ -1,4 +1,4 @@
def decrypt(message):
def decrypt(message: str) -> None:
"""
>>> decrypt('TMDETUX PMDVU')
Decryption using Key #0: TMDETUX PMDVU

View File

@ -1,10 +1,10 @@
def gcd(a, b):
def gcd(a: int, b: int) -> int:
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
def findModInverse(a: int, m: int) -> int:
if gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a

View File

@ -1,12 +1,14 @@
#!/usr/bin/env python3
from typing import Tuple
def decrypt_caesar_with_chi_squared(
ciphertext: str,
cipher_alphabet=None,
frequencies_dict=None,
cipher_alphabet: str = None,
frequencies_dict: str = None,
case_sensetive: bool = False,
) -> tuple:
) -> Tuple[int, float, str]:
"""
Basic Usage
===========

View File

@ -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.
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
def test_miller_rabin():
def test_miller_rabin() -> None:
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
and a prime in each range.
"""

View File

@ -1,4 +1,4 @@
def find_primitive(n):
def find_primitive(n: int) -> int:
for r in range(1, n):
li = []
for x in range(n - 1):

View File

@ -19,7 +19,7 @@ def main():
# so I used 4.80 Algorithm in
# Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
# and it seems to run nicely!
def primitiveRoot(p_val):
def primitiveRoot(p_val: int) -> int:
print("Generating primitive root of p")
while True:
g = random.randrange(3, p_val)
@ -30,7 +30,7 @@ def primitiveRoot(p_val):
return g
def generateKey(keySize):
def generateKey(keySize: int) -> ((int, int, int, int), (int, int)):
print("Generating prime p...")
p = rabinMiller.generateLargePrime(keySize) # select large prime number.
e_1 = primitiveRoot(p) # one primitive root on modulo p.
@ -43,7 +43,7 @@ def generateKey(keySize):
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(
"%s_privkey.txt" % name
):

View File

@ -64,7 +64,7 @@ class HillCipher:
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
"""

View File

@ -1,4 +1,4 @@
def mixed_keyword(key="college", pt="UNIVERSITY"):
def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
"""
For key:hello

View File

@ -57,7 +57,7 @@ MORSE_CODE_DICT = {
}
def encrypt(message):
def encrypt(message: str) -> str:
cipher = ""
for letter in message:
if letter != " ":
@ -69,7 +69,7 @@ def encrypt(message):
return cipher[:-1]
def decrypt(message):
def decrypt(message: str) -> str:
decipher = ""
letters = message.split(" ")
for letter in letters:

View File

@ -2,7 +2,7 @@ import random
class Onepad:
def encrypt(self, text):
def encrypt(self, text: str) -> ([str], [int]):
"""Function to encrypt text using pseudo-random numbers"""
plain = [ord(i) for i in text]
key = []
@ -14,7 +14,7 @@ class Onepad:
key.append(k)
return cipher, key
def decrypt(self, cipher, key):
def decrypt(self, cipher: [str], key: [int]) -> str:
"""Function to decrypt text using pseudo-random numbers."""
plain = []
for i in range(len(key)):

View File

@ -11,7 +11,7 @@ def chunker(seq, size):
yield chunk
def prepare_input(dirty):
def prepare_input(dirty: str) -> str:
"""
Prepare the plaintext by up-casing it
and separating repeated letters with X's
@ -37,7 +37,7 @@ def prepare_input(dirty):
return clean
def generate_table(key):
def generate_table(key: str) -> [str]:
# I and J are used interchangeably to allow
# us to use a 5x5 table (25 letters)
@ -59,7 +59,7 @@ def generate_table(key):
return table
def encode(plaintext, key):
def encode(plaintext: str, key: str) -> str:
table = generate_table(key)
plaintext = prepare_input(plaintext)
ciphertext = ""
@ -82,7 +82,7 @@ def encode(plaintext, key):
return ciphertext
def decode(ciphertext, key):
def decode(ciphertext: str, key: str) -> str:
table = generate_table(key)
plaintext = ""

View File

@ -28,7 +28,7 @@ alphabet = {
}
def generate_table(key):
def generate_table(key: str) -> [(str, str)]:
"""
>>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE
[('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
@ -38,7 +38,7 @@ def generate_table(key):
return [alphabet[char] for char in key.upper()]
def encrypt(key, words):
def encrypt(key: str, words: str) -> str:
"""
>>> encrypt('marvin', 'jessica')
'QRACRWU'
@ -52,7 +52,7 @@ def encrypt(key, words):
return cipher
def decrypt(key, words):
def decrypt(key: str, words: str) -> str:
"""
>>> decrypt('marvin', 'QRACRWU')
'JESSICA'
@ -60,7 +60,7 @@ def decrypt(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 = [
... ('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))
def get_opponent(table, char):
def get_opponent(table: [(str, str)], char: str) -> str:
"""
>>> table = [
... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),

View File

@ -3,7 +3,7 @@
import random
def rabinMiller(num):
def rabinMiller(num: int) -> bool:
s = num - 1
t = 0
@ -25,7 +25,7 @@ def rabinMiller(num):
return True
def isPrime(num):
def isPrime(num: int) -> bool:
if num < 2:
return False
@ -210,7 +210,7 @@ def isPrime(num):
return rabinMiller(num)
def generateLargePrime(keysize=1024):
def generateLargePrime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if isPrime(num):

View File

@ -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

View File

@ -40,7 +40,7 @@ def main():
print(decryptedText)
def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE):
def getBlocksFromText(message: int, blockSize: int = DEFAULT_BLOCK_SIZE) -> [int]:
messageBytes = message.encode("ascii")
blockInts = []
@ -52,7 +52,9 @@ def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE):
return blockInts
def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE):
def getTextFromBlocks(
blockInts: [int], messageLength: int, blockSize: int = DEFAULT_BLOCK_SIZE
) -> str:
message = []
for blockInt in blockInts:
blockMessage = []
@ -65,7 +67,9 @@ def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE):
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 = []
n, e = key
@ -74,7 +78,12 @@ def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE):
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 = []
n, d = key
for block in encryptedBlocks:
@ -82,7 +91,7 @@ def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_
return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)
def readKeyFile(keyFilename):
def readKeyFile(keyFilename: str) -> (int, int, int):
with open(keyFilename) as fo:
content = fo.read()
keySize, n, EorD = content.split(",")
@ -90,8 +99,11 @@ def readKeyFile(keyFilename):
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)
if keySize < blockSize * 8:
sys.exit(
@ -112,7 +124,7 @@ def encryptAndWriteToFile(
return encryptedContent
def readFromFileAndDecrypt(messageFilename, keyFilename):
def readFromFileAndDecrypt(messageFilename: str, keyFilename: str) -> str:
keySize, n, d = readKeyFile(keyFilename)
with open(messageFilename) as fo:
content = fo.read()

View File

@ -13,7 +13,7 @@ import math
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
Return: [p, q]

View File

@ -1,6 +1,7 @@
import os
import random
import sys
from typing import Tuple
from . import cryptomath_module as cryptoMath
from . import rabin_miller as rabinMiller
@ -12,7 +13,7 @@ def main():
print("Key files generation successful.")
def generateKey(keySize):
def generateKey(keySize: int) -> Tuple[Tuple[int, int], Tuple[int, int]]:
print("Generating prime p...")
p = rabinMiller.generateLargePrime(keySize)
print("Generating prime q...")
@ -33,7 +34,7 @@ def generateKey(keySize):
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(
"%s_privkey.txt" % (name)
):

View File

@ -21,7 +21,7 @@ def main():
print("\n{}ion: \n{}".format(mode.title(), translated))
def checkValidKey(key):
def checkValidKey(key: str) -> None:
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
@ -31,7 +31,7 @@ def checkValidKey(key):
sys.exit("Error in the key or symbol set.")
def encryptMessage(key, message):
def encryptMessage(key: str, message: str) -> str:
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
@ -39,7 +39,7 @@ def encryptMessage(key, message):
return translateMessage(key, message, "encrypt")
def decryptMessage(key, message):
def decryptMessage(key: str, message: str) -> str:
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
@ -47,7 +47,7 @@ def decryptMessage(key, message):
return translateMessage(key, message, "decrypt")
def translateMessage(key, message, mode):
def translateMessage(key: str, message: str, mode: str) -> str:
translated = ""
charsA = LETTERS
charsB = key

View File

@ -1,7 +1,7 @@
# https://en.wikipedia.org/wiki/Trifid_cipher
def __encryptPart(messagePart, character2Number):
def __encryptPart(messagePart: str, character2Number: dict) -> str:
one, two, three = "", "", ""
tmp = []
@ -16,7 +16,7 @@ def __encryptPart(messagePart, character2Number):
return one + two + three
def __decryptPart(messagePart, character2Number):
def __decryptPart(messagePart: str, character2Number: dict) -> (str, str, str):
tmp, thisPart = "", ""
result = []
@ -32,7 +32,7 @@ def __decryptPart(messagePart, character2Number):
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
alphabet = alphabet.replace(" ", "").upper()
message = message.replace(" ", "").upper()
@ -83,7 +83,9 @@ def __prepare(message, alphabet):
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)
encrypted, encrypted_numeric = "", ""
@ -96,7 +98,9 @@ def encryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
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)
decrypted_numeric = []
decrypted = ""

View File

@ -22,7 +22,7 @@ def main():
print("Output:\n%s" % (text + "|"))
def encryptMessage(key, message):
def encryptMessage(key: int, message: str) -> str:
"""
>>> encryptMessage(6, 'Harshil Darji')
'Hlia rDsahrij'
@ -36,7 +36,7 @@ def encryptMessage(key, message):
return "".join(cipherText)
def decryptMessage(key, message):
def decryptMessage(key: int, message: str) -> str:
"""
>>> decryptMessage(6, 'Hlia rDsahrij')
'Harshil Darji'

View File

@ -17,7 +17,7 @@ def main():
print(translated)
def encryptMessage(key, message):
def encryptMessage(key: str, message: str) -> str:
"""
>>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.')
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
@ -25,7 +25,7 @@ def encryptMessage(key, message):
return translateMessage(key, message, "encrypt")
def decryptMessage(key, message):
def decryptMessage(key: str, message: str) -> str:
"""
>>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
'This is Harshil Darji from Dharmaj.'
@ -33,7 +33,7 @@ def decryptMessage(key, message):
return translateMessage(key, message, "decrypt")
def translateMessage(key, message, mode):
def translateMessage(key: str, message: str, mode: str) -> str:
translated = []
keyIndex = 0
key = key.upper()

View File

@ -19,7 +19,7 @@
class XORCipher:
def __init__(self, key=0):
def __init__(self, key: int = 0):
"""
simple constructor that receives a key or uses
default key = 0
@ -28,7 +28,7 @@ class XORCipher:
# private field
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
output: encrypted string 'content' as a list of chars
@ -53,7 +53,7 @@ class XORCipher:
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
output: decrypted string 'content' as a list of chars
@ -78,7 +78,7 @@ class XORCipher:
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
output: encrypted string 'content'
@ -103,7 +103,7 @@ class XORCipher:
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
output: decrypted string 'content'
@ -128,7 +128,7 @@ class XORCipher:
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)
output: returns true if encrypt process was
@ -153,7 +153,7 @@ class XORCipher:
return True
def decrypt_file(self, file, key):
def decrypt_file(self, file: str, key: int) -> bool:
"""
input: filename (str) and a key (int)
output: returns true if decrypt process was