Untitled
import math def calculate_bytes_for_digits(decimal_digits): """ Calculate the number of bytes needed to store an integer based on the number of decimal digits. Args: decimal_digits (int): The number of decimal digits in the integer. Returns: int: The number of bytes required. """ if decimal_digits <= 0: raise ValueError("Decimal digits must be a positive integer.") # Calculate the bit length bit_length = math.ceil(decimal_digits * math.log2(10)) # Convert to bytes bytes_needed = math.ceil(bit_length / 8) return bytes_needed # Example usage print(calculate_bytes_for_digits(5)) # Output: 3 from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import base64 def encrypt_to_base36(input_number: int, key: bytes) -> str: # Ensure input is a 6-digit number if not (100000 <= input_number <= 999999): raise ValueError("Input must be a 6-digit number.") # Convert the input number to bytes input_bytes = input_number.to_bytes(3, byteorder='big') # 6-digit number fits in 3 bytes # Encrypt using AES (ECB mode for simplicity, but can use other modes with IVs) cipher = AES.new(key, AES.MODE_ECB) encrypted_bytes = cipher.encrypt(pad(input_bytes, AES.block_size)) # Convert to integer and encode in base-36 encrypted_int = int.from_bytes(encrypted_bytes[:4], 'big') # Truncate to 4 bytes for size base36_output = "" characters = "0123456789abcdefghijklmnopqrstuvwxyz" while encrypted_int > 0 and len(base36_output) < 6: base36_output = characters[encrypted_int % 36] + base36_output encrypted_int //= 36 return base36_output.rjust(6, "0") def decrypt_from_base36(base36_input: str, key: bytes) -> int: # Decode the base-36 string back to an integer encrypted_int = 0 for char in base36_input: encrypted_int = encrypted_int * 36 + "0123456789abcdefghijklmnopqrstuvwxyz".index(char) # Convert the integer back to bytes encrypted_bytes = encrypted_int.to_bytes(4, byteorder='big') # Decrypt using AES cipher = AES.new(key, AES.MODE_ECB) decrypted_bytes = unpad(cipher.decrypt(encrypted_bytes), AES.block_size) # Convert decrypted bytes back to an integer return int.from_bytes(decrypted_bytes, byteorder='big') # Example usage if __name__ == "__main__": # Encryption key (must be 16 bytes for AES-128) encryption_key = b"your16bytekey!!" # Input number input_number = 123456 # Example 6-digit number # Encrypt encrypted = encrypt_to_base36(input_number, encryption_key) print("Encrypted:", encrypted) # Decrypt decrypted = decrypt_from_base36(encrypted, encryption_key) print("Decrypted:", decrypted)
Leave a Comment