base64_encoded


"/home/yossef/notes/personal/hashing/base64_encoded.md"

path: personal/hashing/base64_encoded.md

- **fileName**: base64_encoded
- **Created on**: 2025-05-09 20:49:01

create a base64 encoded encryption and decryption


## main char that can encryption
BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

def base64_encode(text: str) -> str:
    """description: for making encryption base64_encoded
    Args:
        text (str): plain text for encryption
    Returns:
        __str__: results from encryption
    """
    # Step 1: Convert each character to its 8-bit binary representation
    binary_string: str = ""
    for char in text:
        # Convert char to ASCII (ord), then to binary, padded to 8 bits
        # check testing.py file if not understand
        binary_string += format(ord(char), '08b')

    # Step 2: pad binary string to be a multiple of 6 bits
    # what the hill this mean? 
    # now if you convert 2 to binary is 10, so now i want each digital to be 8
    # bits for this i making this while to adding 0 to binary string until become
    # 8 digits and that is 
    # by the way why modules 6 because 2^6 is the lawest number you gone encrypt from
    # top check BASE64_CHARS first A = 64 = 2^6
    while len(binary_string) % 6 != 0:
        binary_string += '0'  # Add zeros at the end

    # Step 3: Break binary string into 6-bit chunks and map to Base64 characters
    base64_result: str = ""
    # what now we gone do 
    # 1- takging 6 bits each time 
    # 2- convert the bits to number exa: int("010110", 2) → 22.
    # 3- get the index of BASE64_CHARS based on index exa(22) -> BASE64_CHARS[22]
    # 4- adding the value to base64_results that is easy beasy :D
    for i in range(0, len(binary_string), 6):
        six_bits: str = binary_string[i:i+6]  # Take 6 bits
        index: int = int(six_bits, 2)         # Convert to number (0–63)
        base64_result += BASE64_CHARS[index]  # Get corresponding Base64 char

    # Step 4: Add '=' padding if needed (based on original input length)
    # Padding rules: 1 byte extra → '==', 2 bytes extra → '='
    # Base64 works by encoding 3 bytes (24 bits) of input into 4 
    # characters of output.
    # so why this why?? now when i having a Number M when convert it ot encryption
    # become => TQ if now if the text modules 3 ==1 adding == and if modules 2 adding
    # = now ot simpleify the process in decryption because in  decryption the 
    # number for len must be from Complications for 4 !!!!
    # if not understand you suck :P
    ## IT MIGHT BREAK COMPATIBILITY WITH SOME BASE64 DECODERS

    # original_length = len(text)
    # if original_length % 3 == 1:
    #     base64_result += "=="
    # elif original_length % 3 == 2:
    #     base64_result += "="


    # return results :D
    return base64_result



def base64_decode(encoded: str) -> str:
    """ description: function for decryption text
    Args:
        text (str): encryption text 
    Returns:
        __str__: results from decryption
    """
    clean: str = encoded.rstrip('=') # if you want to remove extra padding 
    binary: str = ''
    # so now making a for  loop for every char in encryption text and then get
    # the index for that char from BASE64_CHARS and then convert this index
    # to binary that it :D
    for char in clean:
        index: int = BASE64_CHARS.index(char)
        binary += f'{index:06b}'

    decoded: str = ''
    
    # the finallll step we take a number of bits(8) and then check if number 
    # bit not vaild (this happend when adding padding if you can't understand 
    # just skip it) and convert this bits to string and that it
    # exa: 01000001 => M 
    for i in range(0, len(binary), 8):
        byte: str = binary[i:i+8]
        if len(byte) < 8:
            break  # Ignore incomplete byte
        decoded += chr(int(byte, 2))

    return decoded

# testing 
def main():
    text: str = "yossef sabry farouk ahemd"
    encoded: str = base64_encode(text)
    decoded: str = base64_decode(encoded)

    print("- original:", text)
    print("- encoded :", encoded)
    print("- decoded :", decoded)

# running
if __name__ == "__main__":
    main()

continue:[[]]
before:./rail_fence.md