function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def stretch(self, input_image): self.img = cv2.imread(input_image, 0) self.original_image = copy.deepcopy(self.img) x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") self.k = np.sum(x) for i in range(len(x)): prk = x[i] / self.k self.sk += prk last = (self.L - 1) * self.sk if self.rem != 0: self.rem = int(last % last) last = int(last + 1 if self.rem >= 0.5 else last) self.last_list.append(last) self.number_of_rows = int(np.ma.count(self.img) / self.img[1].size) self.number_of_cols = self.img[1].size for i in range(self.number_of_cols): for j in range(self.number_of_rows): num = self.img[j][i] if num != self.last_list[num]: self.img[j][i] = self.last_list[num] cv2.imwrite("output_data/output.jpg", self.img)
digital_image_processing
def plot_histogram(self): plt.hist(self.img.ravel(), 256, [0, 256])
digital_image_processing
def show_image(self): cv2.imshow("Output-Image", self.img) cv2.imshow("Input-Image", self.original_image) cv2.waitKey(5000) cv2.destroyAllWindows()
digital_image_processing
def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = ( 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma))) ) return g
digital_image_processing
def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255): image_row, image_col = image.shape[0], image.shape[1] # gaussian_filter gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4)) # get the gradient and degree by sobel_filter sobel_grad, sobel_theta = sobel_filter(gaussian_out) gradient_direction = np.rad2deg(sobel_theta) gradient_direction += PI dst = np.zeros((image_row, image_col)) for row in range(1, image_row - 1): for col in range(1, image_col - 1): direction = gradient_direction[row, col] if ( 0 <= direction < 22.5 or 15 * PI / 8 <= direction <= 2 * PI or 7 * PI / 8 <= direction <= 9 * PI / 8 ): w = sobel_grad[row, col - 1] e = sobel_grad[row, col + 1] if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e: dst[row, col] = sobel_grad[row, col] elif (PI / 8 <= direction < 3 * PI / 8) or ( 9 * PI / 8 <= direction < 11 * PI / 8 ): sw = sobel_grad[row + 1, col - 1] ne = sobel_grad[row - 1, col + 1] if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne: dst[row, col] = sobel_grad[row, col] elif (3 * PI / 8 <= direction < 5 * PI / 8) or ( 11 * PI / 8 <= direction < 13 * PI / 8 ): n = sobel_grad[row - 1, col] s = sobel_grad[row + 1, col] if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s: dst[row, col] = sobel_grad[row, col] elif (5 * PI / 8 <= direction < 7 * PI / 8) or ( 13 * PI / 8 <= direction < 15 * PI / 8 ): nw = sobel_grad[row - 1, col - 1] se = sobel_grad[row + 1, col + 1] if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se: dst[row, col] = sobel_grad[row, col] if dst[row, col] >= threshold_high: dst[row, col] = strong elif dst[row, col] <= threshold_low: dst[row, col] = 0 else: dst[row, col] = weak for row in range(1, image_row): for col in range(1, image_col): if dst[row, col] == weak: if 255 in ( dst[row, col + 1], dst[row, col - 1], dst[row - 1, col], dst[row + 1, col], dst[row - 1, col - 1], dst[row + 1, col - 1], dst[row - 1, col + 1], dst[row + 1, col + 1], ): dst[row, col] = strong else: dst[row, col] = 0 return dst
digital_image_processing
def __init__(self, input_img, threshold: int): self.min_threshold = 0 # max greyscale value for #FFFFFF self.max_threshold = int(self.get_greyscale(255, 255, 255)) if not self.min_threshold < threshold < self.max_threshold: raise ValueError(f"Factor value should be from 0 to {self.max_threshold}") self.input_img = input_img self.threshold = threshold self.width, self.height = self.input_img.shape[1], self.input_img.shape[0] # error table size (+4 columns and +1 row) greater than input image because of # lack of if statements self.error_table = [ [0 for _ in range(self.height + 4)] for __ in range(self.width + 1) ] self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255
digital_image_processing
def get_greyscale(cls, blue: int, green: int, red: int) -> float: return 0.114 * blue + 0.587 * green + 0.2126 * red
digital_image_processing
def process(self) -> None: for y in range(self.height): for x in range(self.width): greyscale = int(self.get_greyscale(*self.input_img[y][x])) if self.threshold > greyscale + self.error_table[y][x]: self.output_img[y][x] = (0, 0, 0) current_error = greyscale + self.error_table[x][y] else: self.output_img[y][x] = (255, 255, 255) current_error = greyscale + self.error_table[x][y] - 255 self.error_table[y][x + 1] += int(8 / 32 * current_error) self.error_table[y][x + 2] += int(4 / 32 * current_error) self.error_table[y + 1][x] += int(8 / 32 * current_error) self.error_table[y + 1][x + 1] += int(4 / 32 * current_error) self.error_table[y + 1][x + 2] += int(2 / 32 * current_error) self.error_table[y + 1][x - 1] += int(4 / 32 * current_error) self.error_table[y + 1][x - 2] += int(2 / 32 * current_error)
digital_image_processing
def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols))
digital_image_processing
def diophantine(a: int, b: int, c: int) -> tuple[float, float]: assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) function implemented below (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y)
blockchain
def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y)
blockchain
def greatest_common_divisor(a: int, b: int) -> int: if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b
blockchain
def extended_gcd(a: int, b: int) -> tuple[int, int, int]: assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y)
blockchain
def modular_division(a: int, b: int, n: int) -> int: assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x
blockchain
def invert_modulo(a: int, n: int) -> int: (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b
blockchain
def modular_division2(a: int, b: int, n: int) -> int: s = invert_modulo(a, n) x = (b * s) % n return x
blockchain
def extended_gcd(a: int, b: int) -> tuple[int, int, int]: assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y)
blockchain
def extended_euclid(a: int, b: int) -> tuple[int, int]: if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y)
blockchain
def greatest_common_divisor(a: int, b: int) -> int: if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b
blockchain
def extended_euclid(a: int, b: int) -> tuple[int, int]: if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y)
blockchain
def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m
blockchain
def invert_modulo(a: int, n: int) -> int: (b, x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b
blockchain
def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m
blockchain
def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...], None, None]: it = iter(seq) while True: chunk = tuple(itertools.islice(it, size)) if not chunk: return yield chunk
ciphers
def prepare_input(dirty: str) -> str: dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(dirty) - 1): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(clean) & 1: clean += "X" return clean
ciphers
def generate_table(key: str) -> list[str]: # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler table = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(char) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(char) return table
ciphers
def encode(plaintext: str, key: str) -> str: table = generate_table(key) plaintext = prepare_input(plaintext) ciphertext = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for char1, char2 in chunker(plaintext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: ciphertext += table[row1 * 5 + (col1 + 1) % 5] ciphertext += table[row2 * 5 + (col2 + 1) % 5] elif col1 == col2: ciphertext += table[((row1 + 1) % 5) * 5 + col1] ciphertext += table[((row2 + 1) % 5) * 5 + col2] else: # rectangle ciphertext += table[row1 * 5 + col2] ciphertext += table[row2 * 5 + col1] return ciphertext
ciphers
def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key]
ciphers
def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g
ciphers
def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generate_large_prime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key
ciphers
def make_key_files(name: str, key_size: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." ) sys.exit() public_key, private_key = generate_key(key_size) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write(f"{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write(f"{private_key[0]},{private_key[1]}")
ciphers
def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful")
ciphers
def encode(plain: str) -> list[int]: return [ord(elem) - 96 for elem in plain]
ciphers
def decode(encoded: list[int]) -> str: return "".join(chr(elem + 96) for elem in encoded)
ciphers
def main() -> None: encoded = encode(input("-> ").strip().lower()) print("Encoded: ", encoded) print("Decoded:", decode(encoded))
ciphers
def encrypt(plaintext: str, key: str) -> str: if not isinstance(plaintext, str): raise TypeError("plaintext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not plaintext: raise ValueError("plaintext is empty") if not key: raise ValueError("key is empty") key += plaintext plaintext = plaintext.lower() key = key.lower() plaintext_iterator = 0 key_iterator = 0 ciphertext = "" while plaintext_iterator < len(plaintext): if ( ord(plaintext[plaintext_iterator]) < 97 or ord(plaintext[plaintext_iterator]) > 122 ): ciphertext += plaintext[plaintext_iterator] plaintext_iterator += 1 elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122: key_iterator += 1 else: ciphertext += chr( ( (ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator])) - 97 ) % 26 + 97 ) key_iterator += 1 plaintext_iterator += 1 return ciphertext
ciphers
def decrypt(ciphertext: str, key: str) -> str: if not isinstance(ciphertext, str): raise TypeError("ciphertext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not ciphertext: raise ValueError("ciphertext is empty") if not key: raise ValueError("key is empty") key = key.lower() ciphertext_iterator = 0 key_iterator = 0 plaintext = "" while ciphertext_iterator < len(ciphertext): if ( ord(ciphertext[ciphertext_iterator]) < 97 or ord(ciphertext[ciphertext_iterator]) > 122 ): plaintext += ciphertext[ciphertext_iterator] else: plaintext += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key_iterator += 1 ciphertext_iterator += 1 return plaintext
ciphers
def base64_encode(data: bytes) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(data, bytes): raise TypeError( f"a bytes-like object is required, not '{data.__class__.__name__}'" ) binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data) padding_needed = len(binary_stream) % 6 != 0 if padding_needed: # The padding that will be added later padding = b"=" * ((6 - len(binary_stream) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(binary_stream) % 6) else: padding = b"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6], 2)] for index in range(0, len(binary_stream), 6) ).encode() + padding )
ciphers
def base64_decode(encoded_data: str) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str): raise TypeError( "argument should be a bytes-like object or ASCII string, not " f"'{encoded_data.__class__.__name__}'" ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(encoded_data, bytes): try: encoded_data = encoded_data.decode("utf-8") except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters") padding = encoded_data.count("=") # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one encoded_data = encoded_data[:-padding] binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data )[: -padding * 2] else: binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data ) data = [ int(binary_stream[index : index + 8], 2) for index in range(0, len(binary_stream), 8) ] return bytes(data)
ciphers
def rsafactor(d: int, e: int, n: int) -> list[int]: k = d * e - 1 p = 0 q = 0 while p == 0: g = random.randint(2, n - 1) t = k while True: if t % 2 == 0: t = t // 2 x = (g**t) % n y = math.gcd(x - 1, n) if x > 1 and y > 1: p = y q = n // y break # find the correct factors else: break # t is not divisible by 2, break and choose another g return sorted([p, q])
ciphers
def encrypt(text: str) -> tuple[list[int], list[int]]: plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join(plain)
ciphers
def remove_duplicates(key: str) -> str: key_no_dups = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups
ciphers
def create_cipher_map(key: str) -> dict[str, str]: # Create a list of the letters in the alphabet alphabet = [chr(i + 65) for i in range(26)] # Remove duplicate characters from key key = remove_duplicates(key.upper()) offset = len(key) # First fill cipher with key characters cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(cipher_alphabet), 26): char = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 char = alphabet[i - offset] cipher_alphabet[alphabet[i]] = char return cipher_alphabet
ciphers
def encipher(message: str, cipher_map: dict[str, str]) -> str: return "".join(cipher_map.get(ch, ch) for ch in message.upper())
ciphers
def decipher(message: str, cipher_map: dict[str, str]) -> str: # Reverse our cipher mappings rev_cipher_map = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper())
ciphers
def main() -> None: message = input("Enter message to encode or decode: ").strip() key = input("Enter keyword: ").strip() option = input("Encipher or decipher? E/D:").strip()[0].lower() try: func = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option") cipher_map = create_cipher_map(key) print(func(message, cipher_map))
ciphers
def __init__(self, group: int = 14) -> None: if group not in primes: raise ValueError("Unsupported Group") self.prime = primes[group]["prime"] self.generator = primes[group]["generator"] self.__private_key = int(hexlify(urandom(32)), base=16)
ciphers
def get_private_key(self) -> str: return hex(self.__private_key)[2:]
ciphers
def generate_public_key(self) -> str: public_key = pow(self.generator, self.__private_key, self.prime) return hex(public_key)[2:]
ciphers
def is_valid_public_key(self, key: int) -> bool: # check if the other public key is valid based on NIST SP800-56 return ( 2 <= key <= self.prime - 2 and pow(key, (self.prime - 1) // 2, self.prime) == 1 )
ciphers
def generate_shared_key(self, other_key_str: str) -> str: other_key = int(other_key_str, base=16) if not self.is_valid_public_key(other_key): raise ValueError("Invalid public key") shared_key = pow(other_key, self.__private_key, self.prime) return sha256(str(shared_key).encode()).hexdigest()
ciphers
def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool: # check if the other public key is valid based on NIST SP800-56 return ( 2 <= remote_public_key_str <= prime - 2 and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1 )
ciphers
def generate_shared_key_static( local_private_key_str: str, remote_public_key_str: str, group: int = 14 ) -> str: local_private_key = int(local_private_key_str, base=16) remote_public_key = int(remote_public_key_str, base=16) prime = primes[group]["prime"] if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime): raise ValueError("Invalid public key") shared_key = pow(remote_public_key, local_private_key, prime) return sha256(str(shared_key).encode()).hexdigest()
ciphers
def check_keys(key_a: int, key_b: int, mode: str) -> None: if mode == "encrypt": if key_a == 1: sys.exit( "The affine cipher becomes weak when key " "A is set to 1. Choose different key" ) if key_b == 0: sys.exit( "The affine cipher becomes weak when key " "B is set to 0. Choose different key" ) if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1: sys.exit( "Key A must be greater than 0 and key B must " f"be between 0 and {len(SYMBOLS) - 1}." ) if cryptomath.gcd(key_a, len(SYMBOLS)) != 1: sys.exit( f"Key A {key_a} and the symbol set size {len(SYMBOLS)} " "are not relatively prime. Choose a different key." )
ciphers
def encrypt_message(key: int, message: str) -> str: key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "encrypt") cipher_text = "" for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)] else: cipher_text += symbol return cipher_text
ciphers
def decrypt_message(key: int, message: str) -> str: key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "decrypt") plain_text = "" mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS)) for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) plain_text += SYMBOLS[ (sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS) ] else: plain_text += symbol return plain_text
ciphers
def get_random_key() -> int: while True: key_b = random.randint(2, len(SYMBOLS)) key_b = random.randint(2, len(SYMBOLS)) if cryptomath.gcd(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0: return key_b * len(SYMBOLS) + key_b
ciphers
def main() -> None: message = input("Enter message: ").strip() key = int(input("Enter key [2000 - 9000]: ").strip()) mode = input("Encrypt/Decrypt [E/D]: ").strip().lower() if mode.startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif mode.startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ed text: \n{translated}")
ciphers
def get_blocks_from_text( message: str, block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: message_bytes = message.encode("ascii") block_ints = [] for block_start in range(0, len(message_bytes), block_size): block_int = 0 for i in range(block_start, min(block_start + block_size, len(message_bytes))): block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size)) block_ints.append(block_int) return block_ints
ciphers
def get_text_from_blocks( block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE ) -> str: message: list[str] = [] for block_int in block_ints: block_message: list[str] = [] for i in range(block_size - 1, -1, -1): if len(message) + i < message_length: ascii_number = block_int // (BYTE_SIZE**i) block_int = block_int % (BYTE_SIZE**i) block_message.insert(0, chr(ascii_number)) message.extend(block_message) return "".join(message)
ciphers
def encrypt_message( message: str, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: encrypted_blocks = [] n, e = key for block in get_blocks_from_text(message, block_size): encrypted_blocks.append(pow(block, e, n)) return encrypted_blocks
ciphers
def decrypt_message( encrypted_blocks: list[int], message_length: int, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: decrypted_blocks = [] n, d = key for block in encrypted_blocks: decrypted_blocks.append(pow(block, d, n)) return get_text_from_blocks(decrypted_blocks, message_length, block_size)
ciphers
def read_key_file(key_filename: str) -> tuple[int, int, int]: with open(key_filename) as fo: content = fo.read() key_size, n, eor_d = content.split(",") return (int(key_size), int(n), int(eor_d))
ciphers
def encrypt_and_write_to_file( message_filename: str, key_filename: str, message: str, block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: key_size, n, e = read_key_file(key_filename) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Either decrease the block size or use different keys." % (block_size * 8, key_size) ) encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)] encrypted_content = ",".join(encrypted_blocks) encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}" with open(message_filename, "w") as fo: fo.write(encrypted_content) return encrypted_content
ciphers
def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str: key_size, n, d = read_key_file(key_filename) with open(message_filename) as fo: content = fo.read() message_length_str, block_size_str, encrypted_message = content.split("_") message_length = int(message_length_str) block_size = int(block_size_str) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Did you specify the correct key file and encrypted file?" % (block_size * 8, key_size) ) encrypted_blocks = [] for block in encrypted_message.split(","): encrypted_blocks.append(int(block)) return decrypt_message(encrypted_blocks, message_length, (n, d), block_size)
ciphers
def main() -> None: filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.make_key_files("rsa", 1024) message = input("\nEnter message: ") pubkey_filename = "rsa_pubkey.txt" print(f"Encrypting and writing to {filename}...") encrypted_text = encrypt_and_write_to_file(filename, pubkey_filename, message) print("\nEncrypted text:") print(encrypted_text) elif mode == "decrypt": privkey_filename = "rsa_privkey.txt" print(f"Reading from {filename} and decrypting...") decrypted_text = read_from_file_and_decrypt(filename, privkey_filename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decrypted_text) print("\nDecryption:") print(decrypted_text)
ciphers
def __init__(self, key: int = 0): # private field self.__key = key
ciphers
def encrypt(self, content: str, key: int) -> list[str]: # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content]
ciphers
def decrypt(self, content: str, key: int) -> list[str]: # precondition assert isinstance(key, int) and isinstance(content, list) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content]
ciphers
def encrypt_string(self, content: str, key: int = 0) -> str: # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans
ciphers
def decrypt_string(self, content: str, key: int = 0) -> str: # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans
ciphers
def encrypt_file(self, file: str, key: int = 0) -> bool: # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin, open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) except OSError: return False return True
ciphers
def decrypt_file(self, file: str, key: int) -> bool: # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin, open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True
ciphers
def greatest_common_divisor(a: int, b: int) -> int: return b if a == 0 else greatest_common_divisor(b % a, a)
ciphers
def __init__(self, encrypt_key: numpy.ndarray) -> None: self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key self.break_key = encrypt_key.shape[0]
ciphers
def replace_letters(self, letter: str) -> int: return self.key_string.index(letter)
ciphers
def replace_digits(self, num: int) -> str: return self.key_string[round(num)]
ciphers
def check_determinant(self) -> None: det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) req_l = len(self.key_string) if greatest_common_divisor(det, len(self.key_string)) != 1: raise ValueError( f"determinant modular {req_l} of encryption key({det}) is not co prime " f"w.r.t {req_l}.\nTry another key." )
ciphers
def process_text(self, text: str) -> str: chars = [char for char in text.upper() if char in self.key_string] last = chars[-1] while len(chars) % self.break_key != 0: chars.append(last) return "".join(chars)
ciphers
def encrypt(self, text: str) -> str: text = self.process_text(text.upper()) encrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = numpy.array([vec]).T batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[ 0 ] encrypted_batch = "".join( self.replace_digits(num) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted
ciphers
def make_decrypt_key(self) -> numpy.ndarray: det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) det_inv = None for i in range(len(self.key_string)): if (det * i) % len(self.key_string) == 1: det_inv = i break inv_key = ( det_inv * numpy.linalg.det(self.encrypt_key) * numpy.linalg.inv(self.encrypt_key) ) return self.to_int(self.modulus(inv_key))
ciphers
def decrypt(self, text: str) -> str: decrypt_key = self.make_decrypt_key() text = self.process_text(text.upper()) decrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = numpy.array([vec]).T batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0] decrypted_batch = "".join( self.replace_digits(num) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted
ciphers
def main() -> None: n = int(input("Enter the order of the encryption key: ")) hill_matrix = [] print("Enter each row of the encryption key with space separated integers") for _ in range(n): row = [int(x) for x in input().split()] hill_matrix.append(row) hc = HillCipher(numpy.array(hill_matrix)) print("Would you like to encrypt or decrypt some text? (1 or 2)") option = input("\n1. Encrypt\n2. Decrypt\n") if option == "1": text_e = input("What text would you like to encrypt?: ") print("Your encrypted text is:") print(hc.encrypt(text_e)) elif option == "2": text_d = input("What text would you like to decrypt?: ") print("Your decrypted text is:") print(hc.decrypt(text_d))
ciphers
def encrypt(message: str) -> str: return " ".join(MORSE_CODE_DICT[char] for char in message.upper())
ciphers
def decrypt(message: str) -> str: return "".join(REVERSE_DICT[char] for char in message.split())
ciphers
def main() -> None: message = "Morse code here!" print(message) message = encrypt(message) print(message) message = decrypt(message) print(message)
ciphers
def main() -> None: message = input("Enter message: ") key = int(input(f"Enter key [2-{len(message) - 1}]: ")) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encrypt_message(key, message) elif mode.lower().startswith("d"): text = decrypt_message(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}")
ciphers
def encrypt_message(key: int, message: str) -> str: cipher_text = [""] * key for col in range(key): pointer = col while pointer < len(message): cipher_text[col] += message[pointer] pointer += key return "".join(cipher_text)
ciphers
def decrypt_message(key: int, message: str) -> str: num_cols = math.ceil(len(message) / key) num_rows = key num_shaded_boxes = (num_cols * num_rows) - len(message) plain_text = [""] * num_cols col = 0 row = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): col = 0 row += 1 return "".join(plain_text)
ciphers
def translate_message( key: str, message: str, mode: Literal["encrypt", "decrypt"] ) -> str: chars_a = LETTERS if mode == "decrypt" else key chars_b = key if mode == "decrypt" else LETTERS translated = "" # loop through each symbol in the message for symbol in message: if symbol.upper() in chars_a: # encrypt/decrypt the symbol sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: # symbol is not in LETTERS, just add it translated += symbol return translated
ciphers
def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt")
ciphers
def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt")
ciphers
def main() -> None: message = "Hello World" key = "QWERTYUIOPASDFGHJKLZXCVBNM" mode = "decrypt" # set to 'encrypt' or 'decrypt' if mode == "encrypt": translated = encrypt_message(key, message) elif mode == "decrypt": translated = decrypt_message(key, message) print(f"Using the key {key}, the {mode}ed message is: {translated}")
ciphers
def decrypt(message: str) -> None: for key in range(len(string.ascii_uppercase)): translated = "" for symbol in message: if symbol in string.ascii_uppercase: num = string.ascii_uppercase.find(symbol) num = num - key if num < 0: num = num + len(string.ascii_uppercase) translated = translated + string.ascii_uppercase[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}")
ciphers
def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message)
ciphers
def rabin_miller(num: int) -> bool: s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + 1 v = (v**2) % num return True
ciphers
def is_prime_low_num(num: int) -> bool: if num < 2: return False low_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(num)
ciphers
def generate_large_prime(keysize: int = 1024) -> int: while True: num = random.randrange(2 ** (keysize - 1), 2 ** (keysize)) if is_prime_low_num(num): return num
ciphers
def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str: # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters # The final result string result = "" for character in input_string: if character not in alpha: # Append without encryption if character is not in the alphabet result += character else: # Get the index of the new key and make sure it isn't too large new_key = (alpha.index(character) + key) % len(alpha) # Append the encoded character to the alphabet result += alpha[new_key] return result
ciphers
def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str: # Turn on decode mode by making the key negative key *= -1 return encrypt(input_string, key, alphabet)
ciphers