### Install gmpy2 for Large Integer Support Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Install the gmpy2 dependency using pip or poetry to handle integers larger than 512-bit with Obfuskey. ```bash $ pip install gmpy2 ``` ```bash $ poetry install --extras gmpy2 ``` -------------------------------- ### Define Complex Obfusbit Schema Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Example of defining a schema with multiple fields and calculating the total bit requirement. ```python import datetime import uuid from obfuskey import Obfuskey, Obfusbit, alphabets # Define a more complex schema, including a UUID # UUIDs are 128-bit numbers. complex_id_schema = [ {"name": "entity_uuid", "bits": 128}, {"name": "version", "bits": 4}, # e.g., schema version (0-15) {"name": "creation_day", "bits": 9}, # Day of the year (1-366, needs 9 bits for 0-511) {"name": "environment_id", "bits": 2}, # e.g., 0=Dev, 1=Staging, 2=Prod (0-3) {"name": "is_active", "bits": 1}, # Boolean flag (0 or 1) ] # Calculate required bits for this schema: 128 + 4 + 9 + 2 + 1 = 144 bits. # For BASE58 (alphabet length 58), you need `math.ceil(144 / math.log2(58))` which is 25. ``` -------------------------------- ### Initialize Obfuskey and Generate Key Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Instantiate Obfuskey with a predefined alphabet and key length, then generate an obfuscated key from an integer. Use this for basic key generation and retrieval. ```python from obfuskey import Obfuskey, alphabets obfuscator = Obfuskey(alphabets.BASE36, key_length=8) key = obfuscator.get_key(1234567890) # Example: FWQ8H52I value = obfuscator.get_value('FWQ8H52I') # Example: 1234567890 ``` -------------------------------- ### Initialize and Use Obfuskey Source: https://context7.com/bnlucas/obfuskey/llms.txt Basic usage of the Obfuskey class to convert integers to obfuscated keys and back, including accessing instance properties. ```python from obfuskey import Obfuskey, alphabets # Initialize with a predefined alphabet and key length obfuscator = Obfuskey(alphabets.BASE62, key_length=8) # Convert integer to obfuscated key key = obfuscator.get_key(1234567890) print(f"Obfuscated key: {key}") # Example: "d2AaslQJ" # Convert key back to original integer original_value = obfuscator.get_value(key) print(f"Original value: {original_value}") # Output: 1234567890 # Access properties print(f"Maximum value: {obfuscator.maximum_value}") # Max integer this instance can handle print(f"Key length: {obfuscator.key_length}") # 8 print(f"Multiplier: {obfuscator.multiplier}") # Auto-generated prime ``` -------------------------------- ### Handle Obfuskey exceptions Source: https://context7.com/bnlucas/obfuskey/llms.txt Demonstrates catching specific library exceptions for invalid configurations or data overflows. ```python from obfuskey import Obfuskey, Obfusbit, alphabets from obfuskey.exceptions import ( MaximumValueError, NegativeValueError, DuplicateError, MultiplierError, KeyLengthError, UnknownKeyError, BitOverflowError, SchemaValidationError, ) # MaximumValueError - value exceeds capacity obfuscator = Obfuskey(alphabets.BASE62, key_length=2) try: obfuscator.get_key(999999999) # Too large for key_length=2 except MaximumValueError as e: print(f"MaximumValueError: {e}") # NegativeValueError - negative values not allowed try: obfuscator.get_key(-1) except NegativeValueError as e: print(f"NegativeValueError: {e}") # DuplicateError - alphabet has duplicate characters try: Obfuskey("aabbcc") except DuplicateError as e: print(f"DuplicateError: {e}") # MultiplierError - multiplier must be odd integer try: Obfuskey(alphabets.BASE62, multiplier=100) # Even number except MultiplierError as e: print(f"MultiplierError: {e}") # KeyLengthError - key length mismatch on decode obf = Obfuskey(alphabets.BASE62, key_length=6) try: obf.get_value("ABC") # Wrong length except KeyLengthError as e: print(f"KeyLengthError: {e}") # UnknownKeyError - key contains invalid characters try: obf.get_value("!!!!!!") except UnknownKeyError as e: print(f"UnknownKeyError: {e}") # BitOverflowError - value exceeds allocated bits in schema schema = [{"name": "status", "bits": 3}] # Max value: 7 packer = Obfusbit(schema) try: packer.pack({"status": 10}, obfuscate=False) # 10 > 7 except BitOverflowError as e: print(f"BitOverflowError: {e}") # SchemaValidationError - invalid schema definition try: Obfusbit([{"name": "field1"}]) # Missing 'bits' key except SchemaValidationError as e: print(f"SchemaValidationError: {e}") ``` -------------------------------- ### Calculate Minimum Key Length for Obfuskey Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Use this script to determine the minimum key length required for a specific alphabet and total bit count. ```python import math from obfuskey import alphabets # Assuming alphabets is directly importable YOUR_TOTAL_BITS = 144 # Example: Sum of bits from your Obfusbit schema YOUR_ALPHABET = alphabets.BASE58 # Example: Choose your desired alphabet (e.g., alphabets.BASE62, alphabets.BASE64_URL_SAFE) # Calculate the number of states your schema needs to represent (2^N possibilities) required_states = 2 ** YOUR_TOTAL_BITS # Determine the alphabet's length alphabet_length = len(YOUR_ALPHABET) # Calculate the minimum key length using logarithms # This formula is derived from: alphabet_length ** key_length >= 2 ** total_bits # Which simplifies to: key_length >= total_bits / log2(alphabet_length) if alphabet_length <= 1: raise ValueError("Alphabet length must be greater than 1.") # math.log2 gives log base 2, suitable for this calculation minimum_key_length = math.ceil(YOUR_TOTAL_BITS / math.log2(alphabet_length)) print(f"For {YOUR_TOTAL_BITS} total bits and alphabet (length {alphabet_length}):") print(f"Minimum required key_length: {minimum_key_length}") # Optional: Verify the capacity with this calculated key_length max_obfuskey_value = (alphabet_length ** minimum_key_length) - 1 max_schema_value = required_states - 1 print(f"Maximum value Obfuskey can represent with this key_length: {max_obfuskey_value}") print(f"Maximum value schema can produce: {max_schema_value}") if max_obfuskey_value >= max_schema_value: print("Obfuskey capacity is sufficient.") else: # This case should ideally not be reached if minimum_key_length is correctly calculated print("WARNING: Obfuskey capacity is NOT sufficient. This indicates an issue with the calculation.") ``` -------------------------------- ### Obfuscate Packed Values into String Keys with Obfusbit and Obfuskey Source: https://context7.com/bnlucas/obfuskey/llms.txt Combine Obfusbit with Obfuskey to generate obfuscated string keys from packed integer values. Ensure the Obfuskey is initialized with a sufficient key length calculated from the total bits in the schema. ```python import math from obfuskey import Obfuskey, Obfusbit, alphabets # Define schema (total: 27 bits) schema = [ {"name": "category_id", "bits": 4}, {"name": "item_id", "bits": 20}, {"name": "status", "bits": 3}, ] # Calculate required key_length for the schema total_bits = 27 # 4 + 20 + 3 min_key_length = math.ceil(total_bits / math.log2(len(alphabets.BASE58))) print(f"Minimum key length needed: {min_key_length}") # 5 # Create Obfuskey with sufficient capacity obfuscator = Obfuskey(alphabets.BASE58, key_length=5) print(f"Obfuskey max value: {obfuscator.maximum_value}") # 656,356,799 # Initialize Obfusbit with obfuscator packer = Obfusbit(schema, obfuskey=obfuscator) # Pack and obfuscate values = {"category_id": 5, "item_id": 123456, "status": 1} obfuscated_key = packer.pack(values, obfuscate=True) print(f"Obfuscated key: {obfuscated_key}") # Example: "3xK9m" # Unpack and de-obfuscate unpacked = packer.unpack(obfuscated_key, obfuscated=True) print(f"Unpacked values: {unpacked}") ``` -------------------------------- ### Pack and Unpack Values to/from Bytes with Obfusbit Source: https://context7.com/bnlucas/obfuskey/llms.txt Use Obfusbit's `pack_bytes` and `unpack_bytes` methods for binary operations. Specify the `byteorder` (e.g., 'big' or 'little') for packing and unpacking bytes. ```python from obfuskey import Obfusbit # Simple schema (total: 16 bits = 2 bytes) schema = [ {"name": "type_id", "bits": 4}, {"name": "sequence", "bits": 12}, ] packer = Obfusbit(schema) # Pack to bytes values = {"type_id": 3, "sequence": 1000} packed_bytes = packer.pack_bytes(values, byteorder="big") print(f"Packed bytes: {packed_bytes.hex()}") # "3e88" print(f"Byte length: {len(packed_bytes)}") # 2 # Unpack from bytes unpacked = packer.unpack_bytes(packed_bytes, byteorder="big") print(f"Unpacked: {unpacked}") # {'type_id': 3, 'sequence': 1000} # Little-endian packing packed_le = packer.pack_bytes(values, byteorder="little") print(f"Little-endian bytes: {packed_le.hex()}") ``` -------------------------------- ### Obfuskey with Custom Alphabet Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Instantiate Obfuskey with a custom alphabet string. This allows for unique character sets in the generated keys. ```python from obfuskey import Obfuskey obfuscator = Obfuskey('012345abcdef') key = obfuscator.get_key(123) # Example: 022d43 ``` -------------------------------- ### Define Custom Alphabets Source: https://context7.com/bnlucas/obfuskey/llms.txt Create obfuscated keys using custom character sets. Each character in the provided string must be unique. ```python from obfuskey import Obfuskey # Custom hexadecimal-like alphabet hex_obfuscator = Obfuskey('0123456789abcdef', key_length=8) key = hex_obfuscator.get_key(255) print(f"Hex-style key: {key}") # Example: "0000d3a1" # Custom alphabet with only lowercase letters alpha_obfuscator = Obfuskey('abcdefghijklmnopqrstuvwxyz', key_length=6) key = alpha_obfuscator.get_key(12345) print(f"Alpha-only key: {key}") # Example: "qbmrst" # URL-friendly custom alphabet url_obfuscator = Obfuskey('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789', key_length=10) key = url_obfuscator.get_key(9999999) print(f"URL-safe key: {key}") ``` -------------------------------- ### Define and validate Obfusbit schema Source: https://context7.com/bnlucas/obfuskey/llms.txt Configures a schema with bit-length constraints and validates input values against those constraints. ```python schema_def = [ {"name": "user_id", "bits": 32}, {"name": "action_type", "bits": 4}, {"name": "timestamp_offset", "bits": 20}, ] schema = ObfusbitSchema(schema_def) # Introspect schema properties print(f"Total bits: {schema.total_bits}") # 56 print(f"Max value: {schema.max_bits}") # 72057594037927935 (2^56 - 1) print(f"Field names: {schema.field_names}") # {'user_id', 'action_type', 'timestamp_offset'} print(f"Definition: {schema.definition}") # Original schema list # Get field-specific info (bits and shift position) user_info = schema.get_field_info("user_id") print(f"user_id info: {user_info}") # {'bits': 32, 'shift': 24} # Validate values before packing values = {"user_id": 1000, "action_type": 5, "timestamp_offset": 50000} schema.validate_values(values) # Raises BitOverflowError if values exceed bits print("Values validated successfully") ``` -------------------------------- ### Obfuskey with Custom Multiplier Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Generate obfuscated keys using a custom multiplier. The multiplier must be an odd integer. This allows for consistent key generation if a specific prime is needed. ```python from obfuskey import Obfuskey, alphabets # Using default multiplier (randomly generated prime) obfuscator_default = Obfuskey(alphabets.BASE62) key_default = obfuscator_default.get_key(12345) # Example: d2Aasl # Using a specific custom multiplier obfuscator_custom = Obfuskey(alphabets.BASE62, multiplier=46485) key_custom = obfuscator_custom.get_key(12345) # Example: 0cpqVJ ``` -------------------------------- ### Pack Multiple Values into Single Integer with Obfusbit Source: https://context7.com/bnlucas/obfuskey/llms.txt Use Obfusbit for packing integer values into a single integer key without obfuscation. Define a schema specifying field names and allocated bits for each value. ```python from obfuskey import Obfuskey, Obfusbit, alphabets # Define schema: field name and bits allocated product_schema = [ {"name": "category_id", "bits": 4}, # Max value: 15 (2^4 - 1) {"name": "item_id", "bits": 20}, # Max value: 1,048,575 {"name": "status", "bits": 3}, # Max value: 7 ] # Initialize without Obfuskey for raw integer packing packer = Obfusbit(product_schema) # Pack values into a single integer values = { "category_id": 5, "item_id": 123456, "status": 1, } packed_int = packer.pack(values, obfuscate=False) print(f"Packed integer: {packed_int}") # 809492485 # Unpack back to original values unpacked = packer.unpack(packed_int, obfuscated=False) print(f"Unpacked: {unpacked}") # {'status': 1, 'item_id': 123456, 'category_id': 5} ``` -------------------------------- ### Obfusbit: Pack and Unpack Integers Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Use Obfusbit to pack multiple integer values into a single raw integer based on a defined schema. This is useful for storing packed data in databases without obfuscation. ```python from obfuskey import Obfuskey, Obfusbit # Define your data schema with field names and bit lengths product_schema = [ {"name": "category_id", "bits": 4}, # Max value 15 {"name": "item_id", "bits": 20}, # Max value ~1 million {"name": "status", "bits": 3}, # Max value 7 (e.g., in_stock=0, low=1, out=2) ] # Initialize Obfusbit without an Obfuskey instance if you only need the raw integer # (e.g., for storage in a database) obb_int_packer = Obfusbit(product_schema) # Values to pack (must be within the bit limits defined in the schema) values_to_pack = { "category_id": 5, "item_id": 123456, "status": 1, # Low stock } # Pack into a single integer (obfuscate=False for raw integer output) packed_id_int = obb_int_packer.pack(values_to_pack, obfuscate=False) print(f"Packed Integer ID: {packed_id_int}") # Example: 809492485 # Unpack back to original values unpacked_values = obb_int_packer.unpack(packed_id_int, obfuscated=False) print(f"Unpacked values: {unpacked_values}") # Example: {'status': 1, 'item_id': 123456, 'category_id': 5} ``` -------------------------------- ### Configure Custom Multiplier Source: https://context7.com/bnlucas/obfuskey/llms.txt Use a specific odd integer multiplier to ensure reproducible key generation across different instances. ```python from obfuskey import Obfuskey, alphabets # Using a specific custom multiplier for reproducibility obfuscator = Obfuskey(alphabets.BASE62, key_length=6, multiplier=46485) # Same input always produces same output with fixed multiplier key = obfuscator.get_key(12345) print(f"Key with custom multiplier: {key}") # "0cpqVJ" # Different multiplier produces different keys obfuscator_default = Obfuskey(alphabets.BASE62, key_length=6) key_default = obfuscator_default.get_key(12345) print(f"Key with auto multiplier: {key_default}") # Different result ``` -------------------------------- ### Pack and Obfuscate Complex Data Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Use Obfusbit to pack and obfuscate complex data structures. Ensure the Obfuskey instance is sufficiently large for the schema to avoid MaximumValueError. The packed string can be unpacked and de-obfuscated using the same instance. ```python import uuid import datetime from obfuskey import Obfuskey, Obfusbit # Assuming complex_id_schema is defined elsewhere # complex_id_schema = {...} obfuscator_large = Obfuskey(alphabets.BASE58, key_length=26) obb_obfuscated_packer = Obfusbit(complex_id_schema, obfuskey=obfuscator_large) current_uuid = uuid.uuid4() current_day_of_year = datetime.datetime.now().timetuple().tm_yday values_to_pack_complex = { "entity_uuid": current_uuid.int, # Convert UUID object to its 128-bit integer "version": 1, "creation_day": current_day_of_year, "environment_id": 2, # Production "is_active": 1, # True } obfuscated_code = obb_obfuscated_packer.pack(values_to_pack_complex, obfuscate=True) print(f"Obfuscated Complex ID: {obfuscated_code}") unpacked_complex_values = obb_obfuscated_packer.unpack(obfuscated_code, obfuscated=True) print(f"Unpacked Complex Values: {unpacked_complex_values}") reconstructed_uuid = uuid.UUID(int=unpacked_complex_values["entity_uuid"]) print(f"Reconstructed UUID: {reconstructed_uuid}") print(f"Original UUID matches reconstructed: {reconstructed_uuid == current_uuid}") ``` -------------------------------- ### Encode and decode integers with custom alphabets Source: https://context7.com/bnlucas/obfuskey/llms.txt Performs base conversion between integers and strings using utility functions. ```python from obfuskey.utils import encode, decode alphabet = "0123456789ABCDEF" # Hexadecimal # Encode integer to string encoded = encode(255, alphabet) print(f"Encoded: {encoded}") # "FF" encoded_large = encode(65535, alphabet) print(f"Encoded large: {encoded_large}") # "FFFF" # Decode string back to integer decoded = decode("FF", alphabet) print(f"Decoded: {decoded}") # 255 decoded_large = decode("FFFF", alphabet) print(f"Decoded large: {decoded_large}") # 65535 # Works with any alphabet base62_alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" encoded_b62 = encode(1000000, base62_alpha) print(f"Base62 encoded: {encoded_b62}") # "4c92" decoded_b62 = decode(encoded_b62, base62_alpha) print(f"Base62 decoded: {decoded_b62}") # 1000000 ``` -------------------------------- ### Obfuskey with Custom Prime Multiplier Source: https://github.com/bnlucas/obfuskey/blob/main/README.md Override the default prime multiplier using `set_prime_multiplier` with a float or int seed. This generates a new prime for obfuscation, useful for specific seeding requirements. ```python from obfuskey import Obfuskey, alphabets obfuscator = Obfuskey(alphabets.BASE62, key_length=2) key_before_override = obfuscator.get_key(123) # Example: 3f # Using a float seed to generate a different prime multiplier obfuscator.set_prime_multiplier(1.75) key_after_override = obfuscator.get_key(123) # Example: RP ``` -------------------------------- ### Access Predefined Alphabets Source: https://context7.com/bnlucas/obfuskey/llms.txt List of available alphabet constants provided by the library for common encoding schemes. ```python from obfuskey import alphabets # Available alphabets and their sizes print(f"BASE16: {alphabets.BASE16}") # "0123456789ABCDEF" (16 chars) print(f"BASE32: {alphabets.BASE32}") # RFC 4648 Base32 (32 chars) print(f"BASE36: {alphabets.BASE36}") # Alphanumeric uppercase (36 chars) print(f"BASE52: {alphabets.BASE52}") # Letters + digits, no confusables (52 chars) print(f"BASE56: {alphabets.BASE56}") # No 0, 1, O, I, l (56 chars) print(f"BASE58: {alphabets.BASE58}") # Bitcoin-style (58 chars) print(f"BASE62: {alphabets.BASE62}") # Full alphanumeric (62 chars) print(f"BASE64: {alphabets.BASE64}") # Standard Base64 (64 chars) print(f"BASE64_URL_SAFE: {alphabets.BASE64_URL_SAFE}") # URL-safe Base64 (64 chars) print(f"BASE94: {alphabets.BASE94}") # All printable ASCII (94 chars) print(f"CROCKFORD_BASE32: {alphabets.CROCKFORD_BASE32}") # Crockford's Base32 (32 chars) print(f"ZBASE32: {alphabets.ZBASE32}") # z-base-32 human-oriented (32 chars) ``` -------------------------------- ### ObfusbitSchema for Schema Validation and Introspection Source: https://context7.com/bnlucas/obfuskey/llms.txt The ObfusbitSchema class is available for schema validation and introspection purposes within the Obfuskey library. ```python from obfuskey._obfusbit_schema import ObfusbitSchema ``` -------------------------------- ### Handle Large Values like UUIDs with Obfusbit Complex Schema Source: https://context7.com/bnlucas/obfuskey/llms.txt Utilize Obfusbit with a complex schema to handle large values such as UUIDs by allocating sufficient bits. Calculate the required key length based on the total bits and the chosen alphabet. ```python import datetime import uuid import math from obfuskey import Obfuskey, Obfusbit, alphabets # Complex schema including UUID (128 bits total: 128 + 4 + 9 + 2 + 1 = 144) complex_schema = [ {"name": "entity_uuid", "bits": 128}, # Full UUID {"name": "version", "bits": 4}, # Schema version (0-15) {"name": "creation_day", "bits": 9}, # Day of year (1-366) {"name": "environment_id", "bits": 2}, # 0=Dev, 1=Staging, 2=Prod {"name": "is_active", "bits": 1}, # Boolean flag ] # Calculate key length for 144 bits with BASE58 total_bits = 144 min_key_length = math.ceil(total_bits / math.log2(len(alphabets.BASE58))) print(f"Required key length: {min_key_length}") # 25 # Create sufficiently large Obfuskey obfuscator = Obfuskey(alphabets.BASE58, key_length=26) # Initialize Obfusbit packer = Obfusbit(complex_schema, obfuskey=obfuscator) # Pack complex data current_uuid = uuid.uuid4() values = { "entity_uuid": current_uuid.int, # Convert UUID to 128-bit integer "version": 1, "creation_day": datetime.datetime.now().timetuple().tm_yday, "environment_id": 2, # Production "is_active": 1, } obfuscated_key = packer.pack(values, obfuscate=True) print(f"Obfuscated complex ID: {obfuscated_key}") # 26-character string # Unpack and reconstruct UUID unpacked = packer.unpack(obfuscated_key, obfuscated=True) reconstructed_uuid = uuid.UUID(int=unpacked["entity_uuid"]) print(f"UUID matches: {reconstructed_uuid == current_uuid}") # True ``` -------------------------------- ### Override Prime Multiplier Seed Source: https://context7.com/bnlucas/obfuskey/llms.txt Modify the prime multiplier seed to change the internal prime generation pattern. ```python from obfuskey import Obfuskey, alphabets obfuscator = Obfuskey(alphabets.BASE62, key_length=4) # Get key with default prime multiplier key_before = obfuscator.get_key(123) print(f"Before override: {key_before}") # Example: "3f" # Set a new prime multiplier seed obfuscator.set_prime_multiplier(1.75) # Get key with new prime - result will be different key_after = obfuscator.get_key(123) print(f"After override: {key_after}") # Example: "RP" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.