Skip to content

Instantly share code, notes, and snippets.

@allanlei
Last active September 9, 2021 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allanlei/54583d567672badb6c0c45da6a063350 to your computer and use it in GitHub Desktop.
Save allanlei/54583d567672badb6c0c45da6a063350 to your computer and use it in GitHub Desktop.
openssl smime sign with `nodetach`

This is the rough equivalent of

openssl smime -sign
    -signer cert.crt
    -inkey cert.key
    -certfile intermediate.pem 
    -nodetach 
    -outform der 
    -in mdm.mobileconfig 
    -out mdm-signed.mobileconfig
sign(
    data=b'abc123',
    certificate=cryptography.x509.load_pem_x509_certificate(...)
    ca=[
        cryptography.x509.load_pem_x509_certificate(...) for .. in ...
    ]
    key=cryptography.hazmat.primitives.serialization.load_pem_private_key(...)
)
# -*- coding: utf-8 -*-
import typing
import cryptography
def sign(
data: bytes,
certificate: cryptography.x509.Certificate,
key: cryptography.hazmat.primitives.serialization.base._PRIVATE_KEY_TYPES,
certificate_authorities: list[cryptography.x509.Certificate]=None,
hash_algorithm: cryptography.hazmat.primitives.serialization.pkcs7._ALLOWED_PKCS7_HASH_TYPES=cryptography.hazmat.primitives.hashes.SHA512(),
encoding: cryptography.hazmat.primitives.serialization.Encoding=cryptography.hazmat.primitives.serialization.Encoding.DER,
) -> bytes:
return cryptography.hazmat.primitives.serialization.pkcs7.PKCS7SignatureBuilder(
data=data,
signers=[
(certificate, key, hash_algorithm),
],
additional_certs=certificate_authorities or [],
).sign(
encoding, [],
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment