# 9. `example_pkcs7.py` — PKCS#7 certificate bundles
[← Example index](index.md) · [example_pkcs7.py on Codeberg](https://codeberg.org/abbra/synta/src/branch/main/examples/example_pkcs7.py)
Bindings: `load_der_pkcs7_certificates`, `load_pem_pkcs7_certificates`.
- Load a `.p7b` file and print the subject of each extracted certificate.
- Demonstrate PEM-encoded PKCS#7 with `load_pem_pkcs7_certificates`.
- Show `ValueError` for non-PKCS#7 input.
## Source
```python
#!/usr/bin/env python3
"""
Example 8: PKCS#7 certificate bundles.
Demonstrates: load_der_pkcs7_certificates, load_pem_pkcs7_certificates.
Test vectors: tests/vectors/test_bundle.p7b (1 cert)
tests/vectors/test_bundle_2certs.p7b (2 certs)
"""
import pathlib
import synta
VECTORS = pathlib.Path(__file__).parent.parent / "tests" / "vectors"
def section(title):
print(f"\n{'─' * 60}\n{title}\n{'─' * 60}")
def demo_load_der_p7b_single():
section("load_der_pkcs7_certificates — single certificate")
path = VECTORS / "test_bundle.p7b"
if not path.exists():
print(f" Skipped: {path} not found")
return
data = path.read_bytes()
certs = synta.load_der_pkcs7_certificates(data)
print(f" Loaded {len(certs)} certificate(s)")
for i, cert in enumerate(certs):
print(f" [{i}] subject={cert.subject} sig_alg={cert.signature_algorithm}")
def demo_load_der_p7b_multi():
section("load_der_pkcs7_certificates — two certificates")
path = VECTORS / "test_bundle_2certs.p7b"
if not path.exists():
print(f" Skipped: {path} not found")
return
data = path.read_bytes()
certs = synta.load_der_pkcs7_certificates(data)
print(f" Loaded {len(certs)} certificate(s)")
for i, cert in enumerate(certs):
print(f" [{i}] subject={cert.subject}")
assert len(certs) == 2
def demo_load_pem_p7b():
section("load_pem_pkcs7_certificates — PEM-encoded PKCS#7")
path = VECTORS / "test_bundle.p7b"
if not path.exists():
print(f" Skipped: {path} not found")
return
# Convert the DER p7b to PEM so we can exercise load_pem_pkcs7_certificates
der_data = path.read_bytes()
pem_data = synta.der_to_pem(der_data, "PKCS7")
certs_from_pem = synta.load_pem_pkcs7_certificates(pem_data)
certs_from_der = synta.load_der_pkcs7_certificates(der_data)
assert len(certs_from_pem) == len(certs_from_der)
print(f" PEM and DER loaders both return {len(certs_from_pem)} cert(s): OK")
for i, cert in enumerate(certs_from_pem):
print(f" [{i}] {cert.subject}")
def demo_invalid_input():
section("ValueError for non-PKCS#7 input")
try:
synta.load_der_pkcs7_certificates(b"\x30\x03\x02\x01\x01")
print(" No error raised (unexpected)")
except ValueError as e:
print(f" ValueError: {e}")
def main():
print("=" * 60)
print("Example 8: PKCS#7 certificate bundles")
print("=" * 60)
demo_load_der_p7b_single()
demo_load_der_p7b_multi()
demo_load_pem_p7b()
demo_invalid_input()
print("\nAll PKCS#7 examples completed.")
if __name__ == "__main__":
main()
```