### Install SimpleCrypto Source: https://github.com/boppreh/simplecrypto/blob/master/docs/index.md Use pip to install the SimpleCrypto library. Ensure PyCrypto is installed, especially on Windows where a prebuilt installer might be necessary. ```default pip install simplecrypto ``` -------------------------------- ### RsaKeypair Signing and Verification Source: https://context7.com/boppreh/simplecrypto/llms.txt Shows how to sign messages using a private key and verify the signature using the corresponding public key. ```APIDOC ## RsaKeypair Signing and Verification ### Description Sign messages using a private key and verify the signature using the corresponding public key. ### Usage ```python from simplecrypto import RsaKeypair skey = RsaKeypair(2048) pkey = skey.publickey # Sign a message message_to_sign = 'authenticated message' signature = skey.sign(message_to_sign) # Verify the signature valid = pkey.verify(message_to_sign, signature) print(valid) # Output: True ``` ``` -------------------------------- ### RSA Keypair Signing and Verification Source: https://context7.com/boppreh/simplecrypto/llms.txt Illustrates signing a message with a private key and verifying the signature using the corresponding public key. ```python signature = skey.sign('authenticated message') valid = pkey.verify('authenticated message', signature) print(valid) # True ``` -------------------------------- ### Persist and Reload RSA Keypair Source: https://context7.com/boppreh/simplecrypto/llms.txt Shows how to serialize an RSA keypair to a file and then reload it, verifying that the reloaded keypair is identical to the original. ```python with open('rsa.key', 'wb') as f: f.write(skey.serialize()) reloaded = RsaKeypair(open('rsa.key', 'rb').read()) print(skey == reloaded) # True ``` -------------------------------- ### Generate RSA Keypair and Encrypt/Decrypt Source: https://github.com/boppreh/simplecrypto/blob/master/README.rst Create an RSA keypair, encrypt a message with the public key, and decrypt it with the private key. Supports key sizes like 2048 bits. ```python from simplecrypto import RsaKeypair skey = RsaKeypair(2048) publickey = skey.publickey m = publickey.encrypt('secret message') skey.decrypt(m) # b'secret message' ``` -------------------------------- ### Serialize and Reload RSA Public Key Source: https://context7.com/boppreh/simplecrypto/llms.txt Demonstrates serializing an RSA public key to a file and reloading it using `RsaPublicKey`. The reloaded key can be used for encryption. ```python from simplecrypto import RsaKeypair, RsaPublicKey skey = RsaKeypair(2048) pkey = skey.publickey # Serialize and reload just the public key with open('rsa_pub.key', 'wb') as f: f.write(pkey.serialize()) reloaded_pub = RsaPublicKey(open('rsa_pub.key', 'rb').read()) print(pkey == reloaded_pub) # True # Use the reloaded key to encrypt ciphertext = reloaded_pub.encrypt('hello') print(skey.decrypt(ciphertext)) # b'hello' ``` -------------------------------- ### RsaKeypair Encryption and Decryption Source: https://context7.com/boppreh/simplecrypto/llms.txt Demonstrates how to encrypt messages using a public key and decrypt them using the corresponding private key. Supports long messages by automatically using AES session key wrapping. ```APIDOC ## RsaKeypair Encryption and Decryption ### Description Encrypt messages using a public key and decrypt them using the corresponding private key. Long messages are handled automatically using AES session key wrapping. ### Usage ```python from simplecrypto import RsaKeypair skey = RsaKeypair(2048) # Initialize keypair with key size pkey = skey.publickey # Encrypt a message ciphertext = pkey.encrypt('secret message') # Decrypt the message plaintext = skey.decrypt(ciphertext) print(plaintext) # Output: b'secret message' # Handling long messages long_msg = 'long message ' * 100 ciphertext_long = pkey.encrypt(long_msg) print(skey.decrypt(ciphertext_long)[:12]) # Output: b'long message' ``` ### Persisting and Reloading Keypairs Keypairs can be serialized to bytes and reloaded. ### Usage ```python from simplecrypto import RsaKeypair # Assume skey is an existing RsaKeypair object with open('rsa.key', 'wb') as f: f.write(skey.serialize()) # Reload the keypair with open('rsa.key', 'rb') as f: reloaded_keypair_data = f.read() reloaded = RsaKeypair(reloaded_keypair_data) print(skey == reloaded) # Output: True ``` ``` -------------------------------- ### RSA Keypair Encryption and Decryption Source: https://context7.com/boppreh/simplecrypto/llms.txt Demonstrates basic RSA encryption using a public key and decryption using a private key. Handles both short and long messages, with long messages automatically using AES session key wrapping. ```python ciphertext = pkey.encrypt('secret message') plaintext = skey.decrypt(ciphertext) print(plaintext) # b'secret message' ``` ```python long_msg = 'long message ' * 100 ciphertext = pkey.encrypt(long_msg) print(skey.decrypt(ciphertext)[:12]) # b'long message' ``` -------------------------------- ### Byte Padding Utilities Source: https://context7.com/boppreh/simplecrypto/llms.txt Includes functions for padding messages to a specific byte length or to a multiple of a block size using a specified padding byte. `pad_multiple` defaults to null bytes for padding. ```python from simplecrypto import pad, pad_multiple # Pad to a fixed length print(pad('short', 10, '.')) # b'short.....' # Pad to the next multiple of 16 (common for AES blocks) print(pad_multiple('hello', 16)) # b'hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' # Already aligned — no padding added print(pad_multiple('exactly sixteen!', 16)) # b'exactly sixteen!' ``` -------------------------------- ### Sign and Verify Messages with RSA Source: https://github.com/boppreh/simplecrypto/blob/master/README.rst Sign a message using an RSA private key and verify the signature using the corresponding public key. Ensures message authenticity. ```python from simplecrypto import RsaKeypair skey = RsaKeypair(2048) publickey = skey.publickey s = skey.sign('authenticated message') publickey.verify('authenticated message', s) # True ``` -------------------------------- ### Miscellaneous Crypto Helpers Source: https://github.com/boppreh/simplecrypto/blob/master/docs/examples.md Utilize miscellaneous helper functions for base64 encoding/decoding, hex conversion, padding, and generating random bytes. ```python import simplecrypto simplecrypto.base64('message') # 'bWVzc2FnZQ==' simplecrytpo.from_hex('FF') # b'\xff' simplecrypto.pad('short', 10, '.') # b'short.....' random(5) # b'A\xd5\x12\x054' five random bytes ``` -------------------------------- ### AES-256 Encryption and Decryption Shortcuts Source: https://context7.com/boppreh/simplecrypto/llms.txt Provides one-line AES-256 CFB mode encryption and decryption. The key can be a string or bytes. Ciphertext is returned as a base64 string. Decrypting with an incorrect key produces garbage bytes without raising an error. ```python from simplecrypto import encrypt, decrypt ciphertext = encrypt('secret message', 'my password') print(ciphertext) # 'uRKa9xX7zW6QT1yJxIQb5E/0DzaxQglVggnFam5K' (base64) plaintext = decrypt(ciphertext, 'my password') print(plaintext) # b'secret message' # Wrong key raises no error but produces garbage bytes wrong = decrypt(ciphertext, 'wrong password') print(wrong) # b'\x9a\x12...' (garbage) ``` -------------------------------- ### to_base64 / from_base64 Source: https://context7.com/boppreh/simplecrypto/llms.txt Provides functions for Base64 encoding and decoding strings or bytes to/from ASCII strings. An alias `base64` is also available for encoding. ```APIDOC ## Base64 Encoding/Decoding: to_base64 / from_base64 ### Description Converts strings or bytes to a base64 ASCII string, or decodes base64 back to bytes. The `base64` function is an alias for `to_base64`. ### Parameters - `to_base64(message)`: Encodes `message` (str or bytes) to a base64 string. - `from_base64(message)`: Decodes a base64 `message` (str) back to bytes. ### Usage ```python from simplecrypto import to_base64, from_base64, base64 # Encode encoded_str = to_base64('message') print(encoded_str) # Output: 'bWVzc2FnZQ==' # Decode decoded_bytes = from_base64('bWVzc2FnZQ==') print(decoded_bytes) # Output: b'message' # Using the alias for encoding encoded_alias = base64('hello') print(encoded_alias) # Output: 'aGVsbG8=' ``` ``` -------------------------------- ### Generate MD5, SHA1, and SHA256 Hashes Source: https://github.com/boppreh/simplecrypto/blob/master/docs/examples.md Use md5, sha1, or the default hash (SHA-256) function to generate cryptographic hashes of messages. ```python from simplecrypto import md5, sha1, hash md5('The quick brown fox jumps over the lazy dog') # '9e107d9d372bb6826bd81d3542a419d6' sha1('The quick brown fox jumps over the lazy dog') # '2fd4e1c67a2d28fced849ee1bb76e7391b93eb12' # 'hash' defaults to SHA-256 hash('message') # 'ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d' ``` -------------------------------- ### Type Normalization to Bytes and String Source: https://context7.com/boppreh/simplecrypto/llms.txt Provides utilities to convert various string and bytes-like inputs into raw `bytes` using `to_bytes`, and to decode `bytes` into a UTF-8 `str` using `to_str`. ```python from simplecrypto import to_bytes, to_str print(to_bytes('hello')) # b'hello' print(to_bytes(b'already bytes')) # b'already bytes' print(to_str(b'hello')) # 'hello' ``` -------------------------------- ### encrypt(message, key) / decrypt(encrypted_message, key) Source: https://context7.com/boppreh/simplecrypto/llms.txt Provides one-line AES-256 CFB encryption and decryption. The key can be a string or bytes, and the ciphertext is returned as a base64 string. ```APIDOC ## encrypt(message, key) / decrypt(encrypted_message, key) ### Description One-line AES-256 CFB encryption and decryption. The key can be a string or bytes; the ciphertext is returned as a base64 string. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (string or bytes) - Required - The message to encrypt. - **key** (string or bytes) - Required - The encryption key. - **encrypted_message** (string) - Required - The base64 encoded ciphertext to decrypt. ### Request Example ```python from simplecrypto import encrypt, decrypt ciphertext = encrypt('secret message', 'my password') print(ciphertext) # 'uRKa9xX7zW6QT1yJxIQb5E/0DzaxQglVggnFam5K' (base64) plaintext = decrypt(ciphertext, 'my password') print(plaintext) # b'secret message' # Wrong key raises no error but produces garbage bytes wrong = decrypt(ciphertext, 'wrong password') print(wrong) # b'\x9a\x12...' (garbage) ``` ### Response #### Success Response (200) - **ciphertext** (string) - The base64 encoded encrypted message. - **plaintext** (bytes) - The decrypted message. ### Response Example ```json { "ciphertext": "uRKa9xX7zW6QT1yJxIQb5E/0DzaxQglVggnFam5K" } ``` ```json { "plaintext": "b'secret message'" } ``` ``` -------------------------------- ### to_hex / from_hex Source: https://context7.com/boppreh/simplecrypto/llms.txt Offers functions for Hexadecimal encoding and decoding of strings or bytes to/from hexadecimal strings. An alias `hex` is available for encoding. ```APIDOC ## Hex Encoding/Decoding: to_hex / from_hex ### Description Converts strings or bytes to a hexadecimal string, or decodes a hex string back to bytes. The `hex` function is an alias for `to_hex`. ### Parameters - `to_hex(message)`: Encodes `message` (str or bytes) to a hexadecimal string. - `from_hex(message)`: Decodes a hexadecimal `message` (str) back to bytes. ### Usage ```python from simplecrypto import to_hex, from_hex, hex # Encode to hex hex_str = to_hex('AB') print(hex_str) # Output: '4142' # Decode from hex decoded_bytes = from_hex('FF') print(decoded_bytes) # Output: b'\xff' # Using the alias for encoding hex_alias = hex(b'\x00\xff') print(hex_alias) # Output: '00ff' ``` ``` -------------------------------- ### RsaKeypair Source: https://context7.com/boppreh/simplecrypto/llms.txt Manages RSA keypairs for asymmetric encryption. It supports key generation, encryption (via public key), decryption, signing, and serialization. Long messages are handled efficiently using AES-256 session keys. ```APIDOC ## RsaKeypair ### Description Generates or loads an RSA keypair. Supports encryption (delegated to the public key), decryption, signing, and serialization. Long messages are automatically encrypted via a random AES-256 session key for performance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **bits** (int) - Optional - The number of bits for the RSA keypair. Defaults to 2048. ### Methods - **publickey**: Returns the public key object associated with this private key. - **encrypt(message)**: Encrypts a message using the public key. Returns a bytes object. - **decrypt(ciphertext)**: Decrypts a ciphertext using the private key. Returns bytes. - **sign(message)**: Signs a message using the private key. Returns a signature. - **verify(message, signature)**: Verifies a signature against a message using the public key. Returns True if valid, False otherwise. - **serialize()**: Returns the serialized private key. - **load(private_key_bytes)**: Class method to load a private key from bytes. ### Request Example ```python from simplecrypto import RsaKeypair # Generate a 2048-bit RSA keypair skey = RsaKeypair(2048) pkey = skey.publickey # Encrypt a message using the public key encrypted_data = pkey.encrypt('sensitive information') # Decrypt the message using the private key decrypted_data = skey.decrypt(encrypted_data) print(decrypted_data) # b'sensitive information' # Sign a message signature = skey.sign('data to sign') # Verify the signature print(pkey.verify('data to sign', signature)) # True # Serialize and load the private key private_key_bytes = skey.serialize() loaded_skey = RsaKeypair.load(private_key_bytes) print(skey.decrypt(pkey.encrypt('test')) == loaded_skey.decrypt(pkey.encrypt('test'))) # True ``` ### Response #### Success Response (200) - **encrypted_data** (bytes) - The encrypted message. - **decrypted_data** (bytes) - The decrypted message. - **signature** (bytes) - The digital signature. - **is_valid** (boolean) - Indicates if the signature verification was successful. ### Response Example ```json { "encrypted_data": "..." } ``` ```json { "decrypted_data": "b'sensitive information'" } ``` ```json { "signature": "..." } ``` ```json { "is_valid": true } ``` ``` -------------------------------- ### to_bytes / to_str Source: https://context7.com/boppreh/simplecrypto/llms.txt Utility functions for converting between string and bytes types, ensuring consistent data representation. ```APIDOC ## Type Normalization: to_bytes / to_str ### Description Converts any string or bytes-like value to raw `bytes`, or decodes bytes back to a UTF-8 `str`. ### Parameters - `to_bytes(message)`: Converts `message` (str or bytes) to `bytes`. - `to_str(message)`: Decodes `message` (bytes) to a UTF-8 `str`. ### Usage ```python from simplecrypto import to_bytes, to_str # Convert string to bytes bytes_from_str = to_bytes('hello') print(bytes_from_str) # Output: b'hello' # Already bytes, no change bytes_input = b'already bytes' print(to_bytes(bytes_input)) # Output: b'already bytes' # Convert bytes to string str_from_bytes = to_str(b'hello') print(str_from_bytes) # Output: 'hello' ``` ``` -------------------------------- ### Base64 Encoding and Decoding Source: https://context7.com/boppreh/simplecrypto/llms.txt Provides functions for Base64 encoding strings or bytes into an ASCII string and decoding Base64 strings back into bytes. `base64` is an alias for `to_base64`. ```python from simplecrypto import to_base64, from_base64, base64 encoded = to_base64('message') print(encoded) # 'bWVzc2FnZQ==' decoded = from_base64('bWVzc2FnZQ==') print(decoded) # b'message' # `base64` is an alias for to_base64 print(base64('hello')) # 'aGVsbG8=' ``` -------------------------------- ### RSA Keypair Generation Source: https://context7.com/boppreh/simplecrypto/llms.txt Generates an RSA keypair for asymmetric encryption. Supports encryption (via public key), decryption, signing, and serialization. Long messages are handled efficiently using a temporary AES-256 session key. ```python from simplecrypto import RsaKeypair # Generate a 2048-bit RSA keypair skey = RsaKeypair(2048) pkey = skey.publickey ``` -------------------------------- ### pad / pad_multiple Source: https://context7.com/boppreh/simplecrypto/llms.txt Provides byte padding functionality to ensure messages reach an exact byte length or a multiple of a specified block size using a configurable padding byte. ```APIDOC ## Byte Padding: pad / pad_multiple ### Description Pads a message to an exact byte length or to the next multiple of a given block size, using a configurable padding byte. ### Parameters - `pad(message, length, padding)`: Pads `message` (bytes) to `length` bytes using `padding` (bytes). - `pad_multiple(message, len_multiple)`: Pads `message` (bytes) to the next multiple of `len_multiple` bytes, using null bytes (`\x00`) for padding. ### Usage ```python from simplecrypto import pad, pad_multiple # Pad to a fixed length padded_fixed = pad('short', 10, '.') print(padded_fixed) # Output: b'short.....' # Pad to the next multiple of 16 message_to_pad = 'hello' padded_multiple = pad_multiple(message_to_pad.encode(), 16) print(padded_multiple) # Output: b'hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' # Already aligned — no padding added aligned_message = 'exactly sixteen!' print(pad_multiple(aligned_message.encode(), 16)) # Output: b'exactly sixteen!' ``` ``` -------------------------------- ### Secure Message Sending and Receiving Protocol Source: https://github.com/boppreh/simplecrypto/blob/master/docs/examples.md Use the send and receive helper functions for secure communication between parties. Messages are signed and encrypted for specified recipients. Unauthorized recipients will encounter an EncryptionError. ```python from simplecrypto import RsaKeypair from simplecrypto import send, receive alice = RsaKeypair() bob = RsaKeypair() charlie = RsaKeypair() # Prepares a message from Alice to Bob and Charlie. # The message is signed and encrypted. m = send('secret message', alice, bob, charlie) # Bob opens the message from Alice. receive(m, bob, alice) # b'secret message' # Charlie opens the message from Alice. receive(m, charlie, alice) # b'secret message' # Eve tries to eavesdrop. eve = RsaKeypair() receive(m, eve, alice) # EncryptionError! ``` -------------------------------- ### AES-256 Key Management Source: https://context7.com/boppreh/simplecrypto/llms.txt Manages AES-256 keys, allowing generation, derivation from passphrases or bytes, serialization for persistence, and reloading. Supports explicit `encrypt` and `decrypt` methods. ```python from simplecrypto import AesKey from simplecrypto import random # Generate a random AES-256 key key = AesKey() ciphertext = key.encrypt('secret message') print(ciphertext) # 'wFTwwaGMMCAsvmQxhmL7ztDksThtWvGm2gy1e2UV' plaintext = key.decrypt(ciphertext) print(plaintext) # b'secret message' # Derive a key from a passphrase string key = AesKey('my passphrase') # Derive a key from raw bytes key = AesKey(random(32)) # Persist and reload with open('aes.key', 'wb') as f: f.write(key.serialize()) with open('aes.key', 'rb') as f: reloaded_key = AesKey(f.read()) print(key == reloaded_key) # True ``` -------------------------------- ### Asymmetric Encryption and Decryption with RSA Source: https://github.com/boppreh/simplecrypto/blob/master/docs/examples.md Encrypt and decrypt messages using RSA keys. For long messages, AES-256 is used for performance. RSA keypairs and public keys can be exported and imported. ```python from simplecrypto import RsaKeypair, RsaPublicKey skey = RsaKeypair(2048) pkey = skey.publickey m = pkey.encrypt('secret message') skey.decrypt(m) # b'secret message' s = skey.sign('authenticated message') pkey.verify('authenticated message', s) # True # Long messages are encrypted with a random AES-256 key for performance. m = pkey.encrypt('long message ' * 100) skey.decrypt(m) # b'long message long message long message...' # RSA keypairs can be exported and imported. open('key', 'wb').write(skey.serialize()) new_key = RsaKeypair(open('key', 'rb').read()) print(skey == new_key) # True # Individual public keys too. open('key', 'wb').write(pkey.serialize()) new_key = RsaPublicKey(open('key', 'rb').read()) print(pkey == new_key) # True ``` -------------------------------- ### Hexadecimal Encoding and Decoding Source: https://context7.com/boppreh/simplecrypto/llms.txt Offers functions to convert strings or bytes to a hexadecimal string and decode hexadecimal strings back to bytes. `hex` is an alias for `to_hex`. ```python from simplecrypto import to_hex, from_hex, hex print(to_hex('AB')) # '4142' print(from_hex('FF')) # b'\xff' # `hex` is an alias for to_hex print(hex(b'\x00\xff')) # '00ff' ``` -------------------------------- ### RSA Public Key Decryption Attempt Source: https://context7.com/boppreh/simplecrypto/llms.txt Shows that attempting to decrypt a message using only an RSA public key will raise an `EncryptionError`. ```python from simplecrypto import EncryptionError try: reloaded_pub.decrypt(ciphertext) except EncryptionError as e: print(e) # EncryptionError: RSA public keys are unable to decrypt messages. ``` -------------------------------- ### md5(message) Source: https://context7.com/boppreh/simplecrypto/llms.txt Calculates the MD5 hash of a given message and returns it as a lowercase hexadecimal string. Accepts both string and bytes input. ```APIDOC ## md5(message) ### Description Returns the lowercase hexadecimal MD5 digest of a string or bytes message. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (string or bytes) - Required - The message to hash. ### Request Example ```python from simplecrypto import md5 result = md5('The quick brown fox jumps over the lazy dog') print(result) ``` ### Response #### Success Response (200) - **result** (string) - The lowercase hexadecimal MD5 digest. ### Response Example ```json { "result": "9e107d9d372bb6826bd81d3542a419d6" } ``` ``` -------------------------------- ### random Source: https://context7.com/boppreh/simplecrypto/llms.txt Generates cryptographically secure random bytes suitable for key generation and nonces. ```APIDOC ## Cryptographically Secure Random Bytes: random ### Description Returns `n_bytes` of random bytes sourced from `Crypto.Random`, suitable for key generation and nonces. ### Parameters - `random(n_bytes)`: Generates `n_bytes` of cryptographically secure random data. ### Usage ```python from simplecrypto import random # Generate a 16-byte nonce nonce = random(16) print(len(nonce)) # Output: 16 # Generate 32 bytes of key material key_material = random(32) print(type(key_material)) # Output: ``` ``` -------------------------------- ### RsaPublicKey Encryption and Decryption Source: https://context7.com/boppreh/simplecrypto/llms.txt Utilizes a standalone RSA public key for encryption and signature verification. Demonstrates serialization and reloading of public keys. ```APIDOC ## RsaPublicKey Encryption and Decryption ### Description Use a standalone RSA public key for encryption and signature verification. Public keys can be serialized and reloaded. ### Usage ```python from simplecrypto import RsaKeypair, RsaPublicKey, EncryptionError skey = RsaKeypair(2048) public_key = skey.publickey # Serialize and reload the public key with open('rsa_pub.key', 'wb') as f: f.write(public_key.serialize()) with open('rsa_pub.key', 'rb') as f: reloaded_pub_data = f.read() reloaded_pub = RsaPublicKey(reloaded_pub_data) print(public_key == reloaded_pub) # Output: True # Encrypt using the reloaded public key ciphertext = reloaded_pub.encrypt('hello') print(skey.decrypt(ciphertext)) # Output: b'hello' # Attempting to decrypt with a public key raises EncryptionError try: reloaded_pub.decrypt(ciphertext) except EncryptionError as e: print(e) # Output: EncryptionError: RSA public keys are unable to decrypt messages. ``` ``` -------------------------------- ### Encrypt and Decrypt Messages with AES-256 Source: https://github.com/boppreh/simplecrypto/blob/master/README.rst Encrypt messages using AES-256 with a secret key and decrypt them. The encrypted output is a base64 encoded string. ```python from simplecrypto import encrypt, decrypt # `encrypt` and `decrypt` use AES-256. m = encrypt('secret message', 'secret key') print(m) # 'uRKa9xX7zW6QT1yJxIQb5E/0DzaxQglVggnFam5K' decrypt(m, 'secret key') # b'secret message' ``` -------------------------------- ### Symmetric Encryption and Decryption with AES-256 Source: https://github.com/boppreh/simplecrypto/blob/master/docs/examples.md Encrypt and decrypt messages using AES-256 with either a provided key string or a generated AesKey object. Generated keys can be exported and imported. ```python from simplecrypto import encrypt, decrypt, AesKey # `encrypt` and `decrypt` use AES-256. m = encrypt('secret message', 'secret key') print(m) # 'uRKa9xX7zW6QT1yJxIQb5E/0DzaxQglVggnFam5K' decrypt(m, 'secret key') # b'secret message' # Generates a new AES-256 random key. key = AesKey() m = key.encrypt('secret message') print(m) # 'wFTwwaGMMCAsvmQxhmL7ztDksThtWvGm2gy1e2UV' key.decrypt(m) # b'secret message' key = AesKey('secret key') # key from string key = AesKey(random(32)) # key from bytes # AES keys can be exported and imported. open('key', 'wb').write(key.serialize()) new_key = AesKey(open('key', 'rb').read()) print(key == new_key) # True ``` -------------------------------- ### guess_transformation Source: https://context7.com/boppreh/simplecrypto/llms.txt Infers the sequence of hash functions, encoding conversions, and string modifiers applied to a message to produce a known output value. This is useful for reverse-engineering unknown protocols or legacy systems. ```APIDOC ## guess_transformation(message, hash_value) ### Description Given an original message and a known derived value, performs a breadth-first search through combinations of hash functions, encoding conversions, and string modifiers to find the sequence of transformations that produced the target value. Useful for reverse-engineering legacy systems or unknown protocols. ### Parameters - **message** (string or bytes) - The original input message. - **hash_value** (string or bytes) - The known output value derived from the message. ### Returns - list: A list of functions representing the inferred transformation chain. ### Example ```python from simplecrypto import guess_transformation, sha1, to_hex # Known: "hello" was processed to produce this value — what was done? original = 'hello' known_output = sha1('hello') # '...' (simulate a known digest) chain = guess_transformation(original, known_output) print(chain) # [] # Multi-step example: hex-encode then uppercase import simplecrypto target = simplecrypto.to_hex('hello').upper() chain = guess_transformation('hello', target) print([f.__name__ for f in chain]) # ['to_hex', 'upper'] ``` ``` -------------------------------- ### Guess Transformation Chain Source: https://context7.com/boppreh/simplecrypto/llms.txt Use this function to infer a sequence of transformations applied to a message. It performs a breadth-first search through common hash functions, encodings, and modifiers. Useful for reverse-engineering unknown protocols or legacy systems. ```python from simplecrypto import guess_transformation, sha1, to_hex # Known: "hello" was processed to produce this value — what was done? original = 'hello' known_output = sha1('hello') # '...' (simulate a known digest) chain = guess_transformation(original, known_output) print(chain) # [] ``` ```python # Multi-step example: hex-encode then uppercase import simplecrypto target = simplecrypto.to_hex('hello').upper() chain = guess_transformation('hello', target) print([f.__name__ for f in chain]) # ['to_hex', 'upper'] ``` -------------------------------- ### hmac(message, key) / mac(message, key) Source: https://context7.com/boppreh/simplecrypto/llms.txt Generates an HMAC-SHA256 code for a message and key, returning a hex digest. The `mac` function is an alias for `hmac`. ```APIDOC ## hmac(message, key) / mac(message, key) ### Description Returns the HMAC-SHA256 hex digest for a given message and key, providing both integrity and authenticity guarantees. Also aliased as `mac`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (string or bytes) - Required - The message to authenticate. - **key** (string or bytes) - Required - The secret key. ### Request Example ```python from simplecrypto import hmac, mac code = hmac('important data', 'shared secret key') print(code) # 'a3f1c8... (64-character hex string) # Verify by recomputing received = 'important data' assert hmac(received, 'shared secret key') == code, 'Tampered!' # `mac` is an alias for hmac print(mac('data', 'key') == hmac('data', 'key')) # True ``` ### Response #### Success Response (200) - **code** (string) - The HMAC-SHA256 hex digest. ### Response Example ```json { "code": "a3f1c8..." } ``` ``` -------------------------------- ### sha256(message) / hash(message) Source: https://context7.com/boppreh/simplecrypto/llms.txt Generates the SHA-256 hash of a message, returned as a lowercase hexadecimal string. The `hash` function is an alias for `sha256`. ```APIDOC ## sha256(message) / hash(message) ### Description Returns the lowercase hexadecimal SHA-256 digest. Also aliased as `hash` (the default hash function used throughout the library). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (string or bytes) - Required - The message to hash. ### Request Example ```python from simplecrypto import sha256, hash print(sha256('message')) # 'ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d' # `hash` is an alias for sha256 print(hash('message')) # 'ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d' ``` ### Response #### Success Response (200) - **result** (string) - The lowercase hexadecimal SHA-256 digest. ### Response Example ```json { "result": "ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d" } ``` ``` -------------------------------- ### AesKey Source: https://context7.com/boppreh/simplecrypto/llms.txt Represents an AES-256 key object. It can be generated randomly, derived from a passphrase or bytes, serialized, and reloaded. Supports explicit `encrypt`/`decrypt` methods and key persistence. ```APIDOC ## AesKey ### Description A symmetric AES-256 key that can be randomly generated, derived from a passphrase or bytes, serialized, and reloaded. Supports explicit `encrypt` / `decrypt` methods and key persistence. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **key_data** (string, bytes, or None) - Optional - The passphrase or raw bytes to derive the key from. If None, a random key is generated. ### Methods - **encrypt(message)**: Encrypts a message using the AES key. Returns a base64 encoded string. - **decrypt(ciphertext)**: Decrypts a base64 encoded ciphertext using the AES key. Returns bytes. - **serialize()**: Returns the raw bytes of the key for persistence. ### Request Example ```python from simplecrypto import AesKey from simplecrypto import random # Generate a random AES-256 key key = AesKey() ciphertext = key.encrypt('secret message') print(ciphertext) # 'wFTwwaGMMCAsvmQxhmL7ztDksThtWvGm2gy1e2UV' plaintext = key.decrypt(ciphertext) print(plaintext) # b'secret message' # Derive a key from a passphrase string key = AesKey('my passphrase') # Derive a key from raw bytes key = AesKey(random(32)) # Persist and reload with open('aes.key', 'wb') as f: f.write(key.serialize()) with open('aes.key', 'rb') as f: reloaded_key = AesKey(f.read()) print(key == reloaded_key) # True ``` ### Response #### Success Response (200) - **ciphertext** (string) - The base64 encoded encrypted message. - **plaintext** (bytes) - The decrypted message. - **serialized_key** (bytes) - The raw bytes of the key. ### Response Example ```json { "ciphertext": "wFTwwaGMMCAsvmQxhmL7ztDksThtWvGm2gy1e2UV" } ``` ```json { "plaintext": "b'secret message'" } ``` ```json { "serialized_key": "..." } ``` ``` -------------------------------- ### Secure Multi-Recipient Messaging Source: https://context7.com/boppreh/simplecrypto/llms.txt Demonstrates sending a message signed by the sender and encrypted for multiple recipients using `send` and `receive`. Only intended recipients can decrypt the message. ```python from simplecrypto import RsaKeypair, send, receive, EncryptionError alice = RsaKeypair(2048) bob = RsaKeypair(2048) charlie = RsaKeypair(2048) eve = RsaKeypair(2048) # Alice sends a message to both Bob and Charlie payload = send('secret message', alice, bob, charlie) # Bob successfully reads it msg = receive(payload, bob, alice) print(msg) # b'secret message' # Charlie successfully reads it msg = receive(payload, charlie, alice) print(msg) # b'secret message' # Eve cannot read it try: receive(payload, eve, alice) except EncryptionError as e: print(e) # EncryptionError: Unexpected recipient (no respective key found). ``` -------------------------------- ### send / receive - Secure Message Protocol Source: https://context7.com/boppreh/simplecrypto/llms.txt Enables sending signed and encrypted messages to multiple recipients using a shared AES session key. Only listed recipients can decrypt the message. ```APIDOC ## Secure Message Protocol: send / receive ### Description Builds a binary payload that is signed by the sender and encrypted for one or more recipients using a shared AES session key. Any listed recipient can open it; unlisted parties get an `EncryptionError`. ### Parameters - `send(message, sender_key, *recipient_keys)` - `message` (str or bytes): The message to send. - `sender_key` (RsaKeypair): The private key of the sender. - `*recipient_keys` (RsaKeypair): One or more public keys of the recipients. - `receive(payload, recipient_key, sender_key)` - `payload` (bytes): The encrypted binary payload. - `recipient_key` (RsaKeypair): The private key of the recipient trying to decrypt. - `sender_key` (RsaPublicKey): The public key of the sender to verify the signature. ### Usage ```python from simplecrypto import RsaKeypair, send, receive, EncryptionError alice = RsaKeypair(2048) bob = RsaKeypair(2048) charlie = RsaKeypair(2048) eve = RsaKeypair(2048) # Alice sends a message to both Bob and Charlie payload = send('secret message', alice, bob, charlie) # Bob successfully reads it msg_bob = receive(payload, bob, alice.publickey) print(msg_bob) # Output: b'secret message' # Charlie successfully reads it msg_charlie = receive(payload, charlie, alice.publickey) print(msg_charlie) # Output: b'secret message' # Eve cannot read it try: receive(payload, eve, alice.publickey) except EncryptionError as e: print(e) # Output: EncryptionError: Unexpected recipient (no respective key found). ``` ``` -------------------------------- ### sha1(message) Source: https://context7.com/boppreh/simplecrypto/llms.txt Computes the SHA-1 hash of a message and returns it as a lowercase hexadecimal string. Supports string and bytes input. ```APIDOC ## sha1(message) ### Description Returns the lowercase hexadecimal SHA-1 digest of a string or bytes message. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (string or bytes) - Required - The message to hash. ### Request Example ```python from simplecrypto import sha1 result = sha1('The quick brown fox jumps over the lazy dog') print(result) ``` ### Response #### Success Response (200) - **result** (string) - The lowercase hexadecimal SHA-1 digest. ### Response Example ```json { "result": "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12" } ``` ``` -------------------------------- ### Calculate SHA1 Hash Source: https://github.com/boppreh/simplecrypto/blob/master/README.rst Compute the SHA1 hash of a given string. This function is useful for data integrity checks. ```python from simplecrypto import sha1 sha1('The quick brown fox jumps over the lazy dog') # '2fd4e1c67a2d28fced849ee1bb76e7391b93eb12' ``` -------------------------------- ### sha512(message) Source: https://context7.com/boppreh/simplecrypto/llms.txt Computes the SHA-512 hash of a message and returns it as a lowercase hexadecimal string. Accepts string and bytes input. ```APIDOC ## sha512(message) ### Description Returns the lowercase hexadecimal SHA-512 digest of a string or bytes message. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (string or bytes) - Required - The message to hash. ### Request Example ```python from simplecrypto import sha512 print(sha512('message')) # 'f8f3726... (128-character hex string) ``` ### Response #### Success Response (200) - **result** (string) - The lowercase hexadecimal SHA-512 digest. ### Response Example ```json { "result": "f8f3726..." } ``` ``` -------------------------------- ### Base64 Encode a Message Source: https://github.com/boppreh/simplecrypto/blob/master/README.rst Encode a string into a base64 representation. Useful for transmitting binary data in text formats. ```python from simplecrypto import base64 base64('message') # 'bWVzc2FnZQ==' ``` -------------------------------- ### SHA-256 Hash Calculation (and alias 'hash') Source: https://context7.com/boppreh/simplecrypto/llms.txt Calculates the SHA-256 digest of a message. Accepts string or bytes input and returns a lowercase hexadecimal string. The `hash` function is an alias for `sha256`. ```python from simplecrypto import sha256, hash print(sha256('message')) # 'ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d' # `hash` is an alias for sha256 print(hash('message')) # 'ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d' ``` -------------------------------- ### MD5 Hash Calculation Source: https://context7.com/boppreh/simplecrypto/llms.txt Calculates the MD5 digest of a message. Accepts string or bytes input and returns a lowercase hexadecimal string. ```python from simplecrypto import md5 result = md5('The quick brown fox jumps over the lazy dog') print(result) # '9e107d9d372bb6826bd81d3542a419d6' result = md5(b'binary data') print(result) # 'f2e4e1c67a2d28fced849ee1bb76e739' (illustrative) ``` -------------------------------- ### HMAC-SHA256 Calculation (and alias 'mac') Source: https://context7.com/boppreh/simplecrypto/llms.txt Calculates the HMAC-SHA256 hex digest for a message and key, ensuring integrity and authenticity. The `mac` function is an alias for `hmac`. ```python from simplecrypto import hmac, mac code = hmac('important data', 'shared secret key') print(code) # 'a3f1c8... (64-character hex string)' # Verify by recomputing received = 'important data' assert hmac(received, 'shared secret key') == code, 'Tampered!' # `mac` is an alias for hmac print(mac('data', 'key') == hmac('data', 'key')) # True ``` -------------------------------- ### Cryptographically Secure Random Bytes Source: https://context7.com/boppreh/simplecrypto/llms.txt Generates a specified number of cryptographically secure random bytes using `Crypto.Random`, suitable for generating keys or nonces. ```python from simplecrypto import random nonce = random(16) print(len(nonce)) # 16 key_material = random(32) print(type(key_material)) ``` -------------------------------- ### SHA-1 Hash Calculation Source: https://context7.com/boppreh/simplecrypto/llms.txt Calculates the SHA-1 digest of a message. Accepts string or bytes input and returns a lowercase hexadecimal string. ```python from simplecrypto import sha1 result = sha1('The quick brown fox jumps over the lazy dog') print(result) # '2fd4e1c67a2d28fced849ee1bb76e7391b93eb12' ``` -------------------------------- ### SHA-512 Hash Calculation Source: https://context7.com/boppreh/simplecrypto/llms.txt Calculates the SHA-512 digest of a message. Accepts string or bytes input and returns a lowercase hexadecimal string. ```python from simplecrypto import sha512 print(sha512('message')) # 'f8f3726... (128-character hex string)' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.