### Standard Python Installation Command (Shell) Source: https://github.com/jauderho/dkimpy/blob/master/README.md Presents the standard command for installing dkimpy using setup.py, with specific flags to manage external dependencies and recording installed files. ```bash python3 setup.py install --single-version-externally-managed --record=/dev/null ``` -------------------------------- ### Installation with Optional Dependencies (Shell) Source: https://github.com/jauderho/dkimpy/blob/master/README.md Shows how to install dkimpy with specific optional dependencies for features like testing, Ed25519 cryptographic capabilities, or ARC support. ```bash pip install -e '.[testing]' ``` ```bash pip install -e '.[ed25519]' ``` -------------------------------- ### Async DKIM Verification Example Source: https://github.com/jauderho/dkimpy/blob/master/README.md Demonstrates how to use the `dkim.verify_async` function for asynchronous DKIM verification in Python. This requires Python 3.5+ and optionally aiodns for improved performance. The input message is read from stdin. ```python >>> sys.stdin = sys.stdin.detach() >>> >>> async def main(): >>> res = await dkim.verify_async(message) >>> return res >>> >>> if __name__ == "__main__": >>> res = asyncio.run(main()) ``` -------------------------------- ### DKIM Class-Based Signing with Custom Headers Source: https://context7.com/jauderho/dkimpy/llms.txt Provides more granular control over DKIM signing using a class-based API. This example demonstrates how to specify which headers to include in the signature and how to customize canonicalization. ```Python import dkim message = b"""From: sender@example.com\r\nTo: recipient@example.org\r\nSubject: Important Message\r\nDate: Mon, 1 Jan 2024 12:00:00 +0000\r\n\r\nMessage body content.\n""" # Create DKIM instance d = dkim.DKIM( message=message, signature_algorithm=b'rsa-sha256', linesep=b'\r\n' ) # Customize which headers to sign d.add_frozen((b'date', b'subject')) # Sign with custom headers with open('private_key.pem', 'rb') as f: private_key = f.read() signature = d.sign( selector=b'mail', domain=b'example.com', privkey=private_key, canonicalize=(b'relaxed', b'relaxed'), include_headers=d.default_sign_headers(), length=False ) # Access signature details print(f"Domain: {d.domain}") print(f"Selector: {d.selector}") print(f"Signed headers: {d.signed_headers}") ``` -------------------------------- ### Python: DKIM Error Handling Source: https://context7.com/jauderho/dkimpy/llms.txt Handle DKIM exceptions properly during signing and verification. This example shows how to catch various DKIM-related errors, such as invalid keys, message formats, parameters, and validation errors. ```python import dkim message = b"Invalid message without proper headers" try: signature = dkim.sign( message=message, selector=b'test', domain=b'example.com', privkey=b'invalid_key' ) except dkim.KeyFormatError as e: print(f"Key format error: {e}") except dkim.MessageFormatError as e: print(f"Message format error: {e}") except dkim.ParameterError as e: print(f"Parameter error: {e}") except dkim.ValidationError as e: print(f"Validation error: {e}") except dkim.DKIMException as e: print(f"DKIM error: {e}") # Verification with error handling signed_message = b"..." try: result = dkim.verify(signed_message, timeout=5) print(f"Verification result: {result}") except dkim.DnsTimeoutError as e: print(f"DNS timeout: {e}") except dkim.KeyFormatError as e: print(f"Invalid public key: {e}") except dkim.DKIMException as e: print(f"Verification error: {e}") ``` -------------------------------- ### Async DKIM Verification with Python Source: https://context7.com/jauderho/dkimpy/llms.txt Performs DKIM signature verification asynchronously using the aiodns library. The dkim.verify_async function is an async coroutine. The example shows how to run this within an asyncio event loop. It also demonstrates how to disable async verification. ```python import dkim import asyncio async def verify_message_async(message): # Requires aiodns package installed result = await dkim.verify_async(message) return result # Example message with DKIM signature message = b"""DKIM-Signature: v=1; a=rsa-sha256; ...\r From: sender@example.com\r \r Message body. """ # Run async verification async def main(): is_valid = await verify_message_async(message) if is_valid: print("Async verification: PASS") else: print("Async verification: FAIL") asyncio.run(main()) # Disable async even when aiodns is available dkim.USE_ASYNC = False result = dkim.verify(message) # Uses synchronous DNS ``` -------------------------------- ### Python: DKIM Custom Header Selection Source: https://context7.com/jauderho/dkimpy/llms.txt Control which headers are signed by DKIM. This example demonstrates how to specify custom headers to include in the DKIM signature, including how to prevent header additions by signing extra times. ```python import dkim message = b"""From: sender@example.com\r\nTo: recipient@example.org\r\nSubject: Custom Headers\r\nX-Custom: value\r\n\r\nBody. " d = dkim.DKIM(message) # Get default headers (SHOULD sign) default_headers = d.default_sign_headers() # Get all headers except SHOULD_NOT all_headers = d.all_sign_headers() # Sign specific headers with open('key.pem', 'rb') as f: key = f.read() signature = d.sign( selector=b'default', domain=b'example.com', privkey=key, include_headers=[b'from', b'to', b'subject', b'x-custom'] ) # Prevent header additions by signing extra times d.add_frozen((b'from', b'subject', b'date')) signature = d.sign(b'default', b'example.com', key) ``` -------------------------------- ### Basic DKIM Testing Commands (Shell) Source: https://github.com/jauderho/dkimpy/blob/master/README.md Illustrates different ways to execute the dkimpy test suite directly from the command line, utilizing environment variables and Python modules. ```bash PYTHONPATH=. python3 dkim ``` ```bash python3 test.py ``` ```bash PYTHONPATH=. python3 -m unittest dkim.tests.test_suite ``` -------------------------------- ### DKIM Signing and Verification Test Scripts (Shell) Source: https://github.com/jauderho/dkimpy/blob/master/README.md Provides shell commands to run the dkimpy test suite, including specific commands for testing ARC signing and verification using provided runner scripts. ```bash PYTHONPATH=. python3 ./testarc.py sign runners/arcsigntest.py ``` ```bash PYTHONPATH=. python3 ./testarc.py validate runners/arcverifytest.py ``` -------------------------------- ### DKIM Class Initialization and Header Modification (Python) Source: https://github.com/jauderho/dkimpy/blob/master/README.md Demonstrates how to instantiate the DKIM class and modify the set of header fields that are oversigned. This is useful for customizing signature behavior. ```python >>> dkim = DKIM() >>> dkim.add_frozen((b'date',b'subject')) >>> [text(x) for x in sorted(dkim.frozen_sign)] ['date', 'from', 'subject'] ``` -------------------------------- ### Sign Messages with dkimsign Command Source: https://context7.com/jauderho/dkimpy/llms.txt Signs email messages using the `dkimsign` command-line utility. It supports signing from standard input, specifying canonicalization algorithms, signing algorithms (RSA, Ed25519), and identity tags. Requires a domain, private key, and selector. ```bash # Sign a message from stdin echo "From: test@example.com To: user@example.org Subject: Test Message body" | dkimsign default example.com private_key.pem # Sign with custom canonicalization dkimsign --hcanon relaxed --bcanon relaxed \ --signalg rsa-sha256 \ default example.com private_key.pem < message.txt # Sign with identity tag dkimsign --identity sender@example.com \ default example.com private_key.pem < message.txt # Sign with Ed25519 dkimsign --signalg ed25519-sha256 \ ed25519 example.com ed25519_key.txt < message.txt ``` -------------------------------- ### Generate DKIM Key Pairs with dknewkey Source: https://context7.com/jauderho/dkimpy/llms.txt Generates DKIM key pairs (private and public keys) using the `dknewkey` command-line utility. It supports RSA and Ed25519 key types. The command outputs a `.key` file containing the private key and a `.dns` file with the public key in DNS TXT record format. ```bash # Generate RSA key pair (2048 bits) dknewkey mykey # Outputs: # - mykey.key (private key in PEM format) # - mykey.dns (DNS TXT record content) # Generate Ed25519 key pair dknewkey --ktype ed25519 mykey_ed25519 # The .dns file contains the public key for DNS: # v=DKIM1; k=rsa; h=sha256; p=MIIBIjANBg... # or # v=DKIM1; k=ed25519; p=MCowBQYDK2VwAyEA... ``` -------------------------------- ### DKIM Signing with Ed25519 Algorithm Source: https://context7.com/jauderho/dkimpy/llms.txt Demonstrates how to sign email messages using the modern Ed25519 cryptographic algorithm. This involves generating an Ed25519 key pair using the `nacl` library and then using the private key for signing. ```Python import dkim import nacl.signing import nacl.encoding # Generate Ed25519 key pair signing_key = nacl.signing.SigningKey.generate() # For signing, you need the private key as base64 private_key_b64 = signing_key.encode(encoder=nacl.encoding.Base64Encoder) message = b"""From: sender@example.com\r\nTo: recipient@example.org\r\nSubject: Ed25519 Test\r\n\r\nMessage signed with Ed25519.\n""" # Sign with Ed25519 signature = dkim.sign( message=message, selector=b'ed25519', domain=b'example.com', privkey=private_key_b64, signature_algorithm=b'ed25519-sha256' ) signed_message = signature + message print("Ed25519 signed message created") # For DNS, publish the public key: # v=DKIM1; k=ed25519; p= public_key = signing_key.verify_key.encode(encoder=nacl.encoding.Base64Encoder) print(f"DNS record: v=DKIM1; k=ed25519; p={public_key.decode('utf-8')}") ``` -------------------------------- ### Flexible TLSRPT DKIM Verification Source: https://github.com/jauderho/dkimpy/blob/master/README.md Illustrates DKIM verification with flexible TLSRPT checks using the `dkim.verify` function. Setting `tlsrpt=True` allows verification when the service type is not specified, while still applying other RFC 8460 requirements. ```python >>> res = dkim.verify(smessage, tlsrpt=True) ``` -------------------------------- ### Verify DKIM Signatures with dkimverify Command Source: https://context7.com/jauderho/dkimpy/llms.txt Verifies DKIM signatures in a message using the `dkimverify` command-line tool. It can verify the first signature found, a specific signature by index, and provide verbose output. The command exits with code 0 for valid signatures and 1 for invalid ones. ```bash # Verify the first signature cat signed_message.txt | dkimverify # Verify specific signature by index (0-based) dkimverify --index 1 < signed_message.txt # Verbose output with logging dkimverify -v < signed_message.txt # Exit codes: 0 = valid, 1 = invalid ``` -------------------------------- ### Sign and Verify TLSRPT Messages with Python Source: https://context7.com/jauderho/dkimpy/llms.txt Handles RFC 8460 TLSRPT (TLS Report) messages by signing and verifying them. It uses dkim.sign with the tlsrpt=True flag for signing and dkim.verify with tlsrpt='strict' or tlsrpt=True for verification. The length tag is not used for TLSRPT. ```python import dkim # TLSRPT message tlsrpt_message = b"""From: tlsrpt@example.com\r To: reports@recipient.org\r Subject: TLSRPT Report\r \r TLS report content. """ with open('tlsrpt_key.pem', 'rb') as f: private_key = f.read() # Sign TLSRPT message (length tag is never used) signature = dkim.sign( message=tlsrpt_message, selector=b'tlsrpt', domain=b'example.com', privkey=private_key, tlsrpt=True ) signed_message = signature + tlsrpt_message # Verify TLSRPT with strict service type checking # DNS record must include: s=tlsrpt is_valid = dkim.verify( message=signed_message, tlsrpt='strict' ) # Or verify with relaxed checking is_valid = dkim.verify( message=signed_message, tlsrpt=True ) ``` -------------------------------- ### Sign ARC Messages with Python Source: https://context7.com/jauderho/dkimpy/llms.txt Signs email messages using the Authenticated Receive Chain (ARC) protocol. It requires a private key file and uses the dkim.arc_sign function to generate ARC headers. The output includes ARC-Authentication-Results, ARC-Message-Signature, and ARC-Seal headers. ```python import dkim message = b"""Authentication-Results: mail.example.org; spf=pass\r From: sender@example.com\r To: recipient@example.org\r Subject: Forwarded Email\r \r Message body. """ with open('private_key.pem', 'rb') as f: private_key = f.read() # Sign with ARC arc_headers = dkim.arc_sign( message=message, selector=b'arc', domain=b'example.org', privkey=private_key, srv_id=b'mail.example.org', signature_algorithm=b'rsa-256' ) # arc_headers is a list of ARC header lines # [ARC-Authentication-Results, ARC-Message-Signature, ARC-Seal] for header in arc_headers: print(header.decode('utf-8')) # Prepend ARC headers to message arc_signed_message = b''.join(arc_headers) + message ``` -------------------------------- ### Strict TLSRPT DKIM Verification Source: https://github.com/jauderho/dkimpy/blob/master/README.md Shows how to perform DKIM verification with strict TLSRPT (TLS Reporting) checks using the `dkim.verify` function. The `tlsrpt='strict'` flag ensures that only public key records with `s=tlsrpt` are considered valid for TLSRPT signatures. ```python >>> res = dkim.verify(smessage, tlsrpt='strict') ``` -------------------------------- ### DKIM Message Signing with RSA-SHA256 Source: https://context7.com/jauderho/dkimpy/llms.txt Signs an RFC822 email message using the DKIM-Signature header with the RSA-SHA256 algorithm. Requires a private key in PEM format. The function returns the DKIM-Signature header, which should be prepended to the original message. ```Python import dkim # Read the message from a file or construct it message = b"""From: sender@example.com\r\nTo: recipient@example.org\r\nSubject: Test Email\r\n\r\nThis is a test message body.\n""" # Read your private key (PEM format for RSA) with open('private_key.pem', 'rb') as f: private_key = f.read() # Sign the message signature = dkim.sign( message=message, selector=b'default', domain=b'example.com', privkey=private_key, signature_algorithm=b'rsa-sha256', canonicalize=(b'relaxed', b'simple') ) # The signature is a DKIM-Signature header line # Prepend it to the original message signed_message = signature + message # Output: DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=example.com; ... print(signed_message.decode('utf-8', errors='ignore')) ``` -------------------------------- ### Verify ARC Chain with Python Source: https://context7.com/jauderho/dkimpy/llms.txt Verifies an ARC (Authenticated Receive Chain) chain on a given message. It uses the dkim.arc_verify function and returns the chain validation status (Pass, Fail, None) along with detailed results for each instance in the chain. A timeout parameter can be specified. ```python import dkim # Message with ARC headers arc_message = b"""ARC-Seal: i=1; a=rsa-sha256; cv=none; d=example.org; s=arc; ...\r ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; ...\r ARC-Authentication-Results: i=1; mail.example.org; spf=pass\r From: sender@example.com\r To: recipient@example.org\r \r Message body. """ # Verify ARC chain cv_result, results, reason = dkim.arc_verify( message=arc_message, timeout=10 ) # Check chain validation status if cv_result == dkim.CV_Pass: print("ARC chain validation: PASS") elif cv_result == dkim.CV_Fail: print("ARC chain validation: FAIL") elif cv_result == dkim.CV_None: print("ARC chain validation: NONE (no chain)") else: print(f"ARC chain terminated: {reason}") # Examine detailed results for result in results: print(f"Instance {result['instance']}: " f"AMS valid={result['ams-valid']}, " f"AS valid={result['as-valid']}") ``` -------------------------------- ### DKIM Message Verification Source: https://context7.com/jauderho/dkimpy/llms.txt Verifies a DKIM signature present in an email message. This function automatically performs DNS lookups to retrieve the public key. It supports custom timeouts and minimum key sizes for verification. ```Python import dkim # Message with existing DKIM-Signature header signed_message = b"""DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple;\n d=example.com; s=default; h=from:to:subject;\n bh=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN/XKdLCPjaYaY=;\n b=ABC123...\nFrom: sender@example.com\r\nTo: recipient@example.org\r\nSubject: Test Email\r\n\r\nThis is a test message body.\n""" # Verify the signature (performs DNS lookup automatically) try: is_valid = dkim.verify(signed_message) if is_valid: print("Signature is valid!") else: print("Signature verification failed") except dkim.DKIMException as e: print(f"DKIM error: {e}") # Verify with custom timeout and minimum key size is_valid = dkim.verify( message=signed_message, minkey=1024, timeout=10 ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.