Skip to main content

No project description provided

Project description

Ciphers

Python module for implementing ciphers

Installation

Install using

pip install ciphers_module

Import using

import ciphers_module

Methods

Get Letter Value

Gets the A-Z value of a character

def get_letter_value(letter: str) -> int:
    '''Get the value of an English letter (A = 0, B = 1, C = 2 ...)'''
    return ord(letter) - 65

To Run

get_letter_value(letter)

Get Letter From Value

Gets the character from an A-Z value

def get_letter_from_value(value: int) -> str:
    '''Get the English letter from a value (A = 0, B = 1, C = 2 ...)'''
    return chr(value + 65)

To Run

get_letter_from_value(letter)

Caeser Cipher

Performs a Caeser Cipher on a given string with given shift Negative shift means shifting left

def caeser_cipher(text: str, shift: int, decode: bool = False) -> str:
    '''
    Caeser Cipher\n
    Shifts {text} {shift} amount in positive/negative direction (Right/Left respectively)\n
    Set {decode} to True to decode {text} with shift {shift}
    '''
    # Make everything Upper Case
    text.upper()

    # Begin
    result: str = ""
    for letter in text:
        # Get Value of each Letter
        value: int = get_letter_value(letter)
        # Get Letter from Value
        result += get_letter_from_value(value + shift) if not decode else get_letter_from_value(value - shift) # Handle Decoding

    return result

To Run

caeser_cipher(text, shift, decode) # decode is automatically false

Vigenere Cipher

Performs a Vigenere Cipher on a given string with given key

def vigenere_cipher(text: str, key: str, decode: bool = False) -> str:
    '''
    Vigenere Cipher\n
    Uses a Vigenere Cipher on {text} with key {key}\n
    Set {decode} to True to decode {text} with key {key}
    '''
    # Make everything Upper Case
    text.upper()
    key.upper()

    # Make Lists of Characters
    text_lst: list[str] = list(text)
    key_lst: list[str] = list(key)

    # Edit Length of Key
    if len(key_lst) < len(text_lst):
        key_lst = list(islice(cycle(key_lst), len(text_lst)))
    if len(key_lst) > len(text_lst):
        key_lst = key_lst[:len(key_lst)]

    result: str = ""

    for index, letter in enumerate(text_lst):
        # Get Values of each Letter
        letter_value: int = get_letter_value(letter)
        key_value: int = get_letter_value(key_lst[index]) if not decode else -get_letter_value(key_lst[index]) # Handle Decoding
        # Get Letter from Value
        new_letter: str = get_letter_from_value((letter_value + key_value) % 26)
        result += new_letter

    return result

To Run

vigenere_cipher(text, key, decode) # decode is automatically false

Rail Fence Cipher

Performs a Rail Fence Cipher on a given string with given amount of Rails

def rail_fence_cipher(text: str, rails: int, decode: bool = False):
    '''
    Rail Fence Cipher\n
    Uses a Rail Fence (Zig-Zag) Cipher on {text} with {rails} rails\n
    Set {decode} to True to decode {text} with {rails} rails
    '''
    # Make everything Upper Case
    text.upper()
    
    # Make Rail Fence
    rail_fence = [[""]*len(text) for _ in range(rails)]

    # Variables to move the cursor
    direction = -1
    row = 0

    if decode:  # Decoding
        # Fill the rail_fence with placeholders
        for col in range(len(text)):
            rail_fence[row][col] = '*'

            # Change direction if we've hit the top or bottom rail
            if row == 0 or row == rails - 1:
                direction *= -1

            # Move to the next row
            row += direction

        # Fill the rail rail_fence with the ciphertext
        i = 0
        for row in range(rails):
            for col in range(len(text)):
                if rail_fence[row][col] == '*':
                    rail_fence[row][col] = text[i]
                    i += 1

        # Extract the plaintext from the rail_fence
        result = [rail_fence[row][col] for col in range(len(text)) for row in range(rails) if rail_fence[row][col] is not None]

    else:  # Encoding
        # Fill the rail rail_fence
        for col in range(len(text)):
            rail_fence[row][col] = text[col]

            # Change direction if we've hit the top or bottom rail
            if row == 0 or row == rails - 1:
                direction *= -1

            # Move to the next row
            row += direction

        # Extract the text from the rail_fence
        result = [rail_fence[row][col] for row in range(rails) for col in range(len(text)) if rail_fence[row][col] is not None]

    return "".join(result)

To Run

rail_fence_cipher(text, shift, decode) # decode is automatically false

Following Methods are in the ASCII class

ASCII Decimal Cipher

Encode/Decodes a string in Decimal using ASCII notation

def decimal(text: str, decode: bool = False) -> str:
    '''
    ASCII Decimal\n
    Converts a string to and from decimal using ASCII
    '''
    result: str = ""
    if not decode:
        for letter in text:
            value: str = str(ord(letter))
            result += f"{value} "
        return result
    for number in text.split():
        try:
            value = chr(int(number))
            result += value
        except ValueError:
            print("Not a number")
    return result

To Run

ascii.decimal(text, decode) # decode is automatically false

ASCII Binary Cipher

Encode/Decodes a string in Binary using ASCII notation

def binary(text: str, decode: bool = False) -> str:
    '''
    ASCII Binary\n
    Converts a string to and from binary using ASCII
    '''
    result: str = ""
    if not decode:
        for letter in text:
            value: str = bin(ord(letter)).removeprefix("0b")
            result += f"0{value} "
        return result
    for byte in text.split():
        try:
            value = chr(int(byte, 2))
            result += value
        except ValueError:
            print(f"Not Binary: {byte}")
    return result

To Run

ascii.binary(text, decode) # decode is automatically false

ASCII Octal Cipher

Encode/Decodes a string in Octal using ASCII notation

def octal(text: str, decode: bool = False) -> str:
    '''
    ASCII Octal\n
    Converts a string to and from octal using ASCII
    '''
    result: str = ""
    if not decode:
        for letter in text:
            value: str = oct(ord(letter)).removeprefix("0o")
            result += f"{value} "
        return result
    for octa in text.split():
        try:
            value = chr(int(octa, 8))
            result += value
        except ValueError:
            print(f"Not Octal: {octa}")
    return result

To Run

ascii.octal(text, decode) # decode is automatically false

ASCII Hexadecimal Cipher

Encode/Decodes a string in Hexadecimal using ASCII notation

def hexadecimal(text: str, decode: bool = False) -> str:
    '''
    ASCII Hexadecimal\n
    Converts a string to and from hexadecimal using ASCII
    '''
    result: str = ""
    if not decode:
        for letter in text:
            value: str = hex(ord(letter)).removeprefix("0x")
            result += f"{value} "
        return result
    for hexa in text.split():
        try:
            value = chr(int(hexa, 16))
            result += value
        except ValueError:
            print(f"Not Hexadecimal: {hexa}")
    return result

To Run

ascii.hexadecimal(text, decode) # decode is automatically false

Morse Code

Encode/Decodes a string in Morse Code

def morse_code(text: str, decode: bool = False) -> str:
    '''
    Morse Code\n
    Encodes/Decodes a string in Morse Code
    '''
    code: dict[str, str] = {
        "A": ".-",
        "B": "-...",
        "C": "-.-.",
        "D": "-..",
        "E": ".",
        "F": "..-.",
        "G": "--.",
        "H": "....",
        "I": "..",
        "J": ".---",
        "K": "-.-",
        "L": ".-..",
        "M": "--",
        "N": "-.",
        "O": "---",
        "P": ".--.",
        "Q": "--.-",
        "R": ".-.",
        "S": "...",
        "T": "-",
        "U": "..-",
        "V": "...-",
        "W": ".--",
        "X": "-..-",
        "Y": "-.--",
        "Z": "--..",
        "1": ".----",
        "2": "..---",
        "3": "...--",
        "4": "....-",
        "5": ".....",
        "6": "-....",
        "7": "--...",
        "8": "---..",
        "9": "----.",
        "0": "-----",
        " ": "/",
    }
    
    input_text: str = text.upper()
    if not decode:
        input_tokens: list[str] = [*input_text]

        result: str = ""
        for token in input_tokens:
            try:
                result += code[token] + " "
            except KeyError:
                result += token + " "
        
        return result
    
    input_tokens: list[str] = input_text.split()

    result: str = ""
    for token in input_tokens:
        try:
            result += list(code.keys())[list(code.values()).index(token)]
        except ValueError:
            result += token

    return result

To run

morse_code(text, decode) # decode is automatically false

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ciphers_module-2.0.0.tar.gz (4.4 kB view details)

Uploaded Source

Built Distribution

ciphers_module-2.0.0-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

Details for the file ciphers_module-2.0.0.tar.gz.

File metadata

  • Download URL: ciphers_module-2.0.0.tar.gz
  • Upload date:
  • Size: 4.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.12.4

File hashes

Hashes for ciphers_module-2.0.0.tar.gz
Algorithm Hash digest
SHA256 8212b5854c075fd9dff74cf896fefbd79263596bef8cf8cd6280285e88623ade
MD5 4edd5c2df21edf0fa36f1b3c9a7b7ab3
BLAKE2b-256 d167f0b726d4bc1c01d802b325d74b00d9fba69b8b020d9950b69a8606c87999

See more details on using hashes here.

File details

Details for the file ciphers_module-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for ciphers_module-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 80ff8500c8c9dfb03a115b4c49d5924c954bdd0d8e39de59b9a4c86330032c18
MD5 c40f95ec96403022667779b6c86e6be6
BLAKE2b-256 43ba274a0a25669af4f6e381bf3aff455a9a73a7c2df367b9bd119df2d3cffc6

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page