pkcs7.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import typing
  5. from cryptography import utils
  6. from cryptography import x509
  7. from cryptography.hazmat.primitives import hashes, serialization
  8. from cryptography.hazmat.primitives.asymmetric import ec, rsa
  9. from cryptography.utils import _check_byteslike
  10. def load_pem_pkcs7_certificates(data: bytes) -> typing.List[x509.Certificate]:
  11. from cryptography.hazmat.backends.openssl.backend import backend
  12. return backend.load_pem_pkcs7_certificates(data)
  13. def load_der_pkcs7_certificates(data: bytes) -> typing.List[x509.Certificate]:
  14. from cryptography.hazmat.backends.openssl.backend import backend
  15. return backend.load_der_pkcs7_certificates(data)
  16. def serialize_certificates(
  17. certs: typing.List[x509.Certificate],
  18. encoding: serialization.Encoding,
  19. ) -> bytes:
  20. from cryptography.hazmat.backends.openssl.backend import backend
  21. return backend.pkcs7_serialize_certificates(certs, encoding)
  22. _ALLOWED_PKCS7_HASH_TYPES = typing.Union[
  23. hashes.SHA1,
  24. hashes.SHA224,
  25. hashes.SHA256,
  26. hashes.SHA384,
  27. hashes.SHA512,
  28. ]
  29. _ALLOWED_PRIVATE_KEY_TYPES = typing.Union[
  30. rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey
  31. ]
  32. class PKCS7Options(utils.Enum):
  33. Text = "Add text/plain MIME type"
  34. Binary = "Don't translate input data into canonical MIME format"
  35. DetachedSignature = "Don't embed data in the PKCS7 structure"
  36. NoCapabilities = "Don't embed SMIME capabilities"
  37. NoAttributes = "Don't embed authenticatedAttributes"
  38. NoCerts = "Don't embed signer certificate"
  39. class PKCS7SignatureBuilder:
  40. def __init__(
  41. self,
  42. data: typing.Optional[bytes] = None,
  43. signers: typing.List[
  44. typing.Tuple[
  45. x509.Certificate,
  46. _ALLOWED_PRIVATE_KEY_TYPES,
  47. _ALLOWED_PKCS7_HASH_TYPES,
  48. ]
  49. ] = [],
  50. additional_certs: typing.List[x509.Certificate] = [],
  51. ):
  52. self._data = data
  53. self._signers = signers
  54. self._additional_certs = additional_certs
  55. def set_data(self, data: bytes) -> "PKCS7SignatureBuilder":
  56. _check_byteslike("data", data)
  57. if self._data is not None:
  58. raise ValueError("data may only be set once")
  59. return PKCS7SignatureBuilder(data, self._signers)
  60. def add_signer(
  61. self,
  62. certificate: x509.Certificate,
  63. private_key: _ALLOWED_PRIVATE_KEY_TYPES,
  64. hash_algorithm: _ALLOWED_PKCS7_HASH_TYPES,
  65. ) -> "PKCS7SignatureBuilder":
  66. if not isinstance(
  67. hash_algorithm,
  68. (
  69. hashes.SHA1,
  70. hashes.SHA224,
  71. hashes.SHA256,
  72. hashes.SHA384,
  73. hashes.SHA512,
  74. ),
  75. ):
  76. raise TypeError(
  77. "hash_algorithm must be one of hashes.SHA1, SHA224, "
  78. "SHA256, SHA384, or SHA512"
  79. )
  80. if not isinstance(certificate, x509.Certificate):
  81. raise TypeError("certificate must be a x509.Certificate")
  82. if not isinstance(
  83. private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)
  84. ):
  85. raise TypeError("Only RSA & EC keys are supported at this time.")
  86. return PKCS7SignatureBuilder(
  87. self._data,
  88. self._signers + [(certificate, private_key, hash_algorithm)],
  89. )
  90. def add_certificate(
  91. self, certificate: x509.Certificate
  92. ) -> "PKCS7SignatureBuilder":
  93. if not isinstance(certificate, x509.Certificate):
  94. raise TypeError("certificate must be a x509.Certificate")
  95. return PKCS7SignatureBuilder(
  96. self._data, self._signers, self._additional_certs + [certificate]
  97. )
  98. def sign(
  99. self,
  100. encoding: serialization.Encoding,
  101. options: typing.Iterable[PKCS7Options],
  102. backend: typing.Any = None,
  103. ) -> bytes:
  104. if len(self._signers) == 0:
  105. raise ValueError("Must have at least one signer")
  106. if self._data is None:
  107. raise ValueError("You must add data to sign")
  108. options = list(options)
  109. if not all(isinstance(x, PKCS7Options) for x in options):
  110. raise ValueError("options must be from the PKCS7Options enum")
  111. if encoding not in (
  112. serialization.Encoding.PEM,
  113. serialization.Encoding.DER,
  114. serialization.Encoding.SMIME,
  115. ):
  116. raise ValueError(
  117. "Must be PEM, DER, or SMIME from the Encoding enum"
  118. )
  119. # Text is a meaningless option unless it is accompanied by
  120. # DetachedSignature
  121. if (
  122. PKCS7Options.Text in options
  123. and PKCS7Options.DetachedSignature not in options
  124. ):
  125. raise ValueError(
  126. "When passing the Text option you must also pass "
  127. "DetachedSignature"
  128. )
  129. if PKCS7Options.Text in options and encoding in (
  130. serialization.Encoding.DER,
  131. serialization.Encoding.PEM,
  132. ):
  133. raise ValueError(
  134. "The Text option is only available for SMIME serialization"
  135. )
  136. # No attributes implies no capabilities so we'll error if you try to
  137. # pass both.
  138. if (
  139. PKCS7Options.NoAttributes in options
  140. and PKCS7Options.NoCapabilities in options
  141. ):
  142. raise ValueError(
  143. "NoAttributes is a superset of NoCapabilities. Do not pass "
  144. "both values."
  145. )
  146. from cryptography.hazmat.backends.openssl.backend import (
  147. backend as ossl,
  148. )
  149. return ossl.pkcs7_sign(self, encoding, options)