1.. hazmat:: 2 3Key Serialization 4================= 5 6.. module:: cryptography.hazmat.primitives.serialization 7 8.. testsetup:: 9 10 import base64 11 12 pem_data = b""" 13 -----BEGIN RSA PRIVATE KEY----- 14 MIICXgIBAAKBgQDn09PV9KPE7Q+N5K5UtNLT1DLl8z/pKM2pP5tXqWx2OsEw00lC 15 kDHdHESwzS050s/8rtkERKKyusCzCm9+vC1pQzUlmtibfF4PQAQc1pJL6KHqlidg 16 Hw49atYmnC25CaeXt65pAYXoIacOZ8k5X7FW3Eagex8nG0iMw4ObOtg6CwIDAQAB 17 AoGBAL31l/4YYN1rNrSZLrQgGyUSGsbLxJHEKolFon95R3O1fzoH117gkstQb4TE 18 Cwv3jw/JIfBaYUq8tku/AE9D2Jx51x7kYaCuQIMTavKIgkXKfxTQCQDjSEfkvXMW 19 4WOIj5sYdSCNbzLbaeFsWG32bSsBTy/sSheDIlCEFnqDuqwBAkEA+wYfJEMDf5nS 20 VCQd9VKGM4HVeTWBioaWBFCflFdhc1Vb65dsNDp8iIMZgAHC2LEX5dMUmgqXk7AT 21 lwFlIeW4CwJBAOxsSfuIVMuPKyx1xQ6ebpC7zeVxIOdswcM8ain91MSGDdKZw6pF 22 ioFh3kUbKHw4yqqHbdRmUDAJ1mcgGJQOxgECQQCmQaGylKfmhWymyd0FtIip6J4I 23 z4ViyEznwrZOu6kRiEF/QiUqWmpMx/fFrmTsvC5Fy43jkIxgBsiSxRvEXa+NAkB+ 24 5m0bhwTEslchKSGZhC6inzuYAQ4BSh4C1mXBnk5bIf0/Ymtk9KiwY8CzZS1o5+7Y 25 c5LfI/+8mTss5UxsBDYBAkEA6NqhcsNWndIJZiWUU4u+RjFUQXqH8WCyJmEDCNxs 26 7SGRS1DTUGX4Y70m9dQpguy6Zg+gpHC+o+ERZR06uEQr+w== 27 -----END RSA PRIVATE KEY----- 28 """.strip() 29 public_pem_data = b""" 30 -----BEGIN PUBLIC KEY----- 31 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDn09PV9KPE7Q+N5K5UtNLT1DLl 32 8z/pKM2pP5tXqWx2OsEw00lCkDHdHESwzS050s/8rtkERKKyusCzCm9+vC1pQzUl 33 mtibfF4PQAQc1pJL6KHqlidgHw49atYmnC25CaeXt65pAYXoIacOZ8k5X7FW3Eag 34 ex8nG0iMw4ObOtg6CwIDAQAB 35 -----END PUBLIC KEY----- 36 """.strip() 37 der_data = base64.b64decode( 38 b"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALskegl+DrI3Msw5Z63x" 39 b"nj1rgoPR0KykwBi+jZgAwHv/B0TJyhy6NuEnaf+x442L7lepOqoWQzlUGXyuaSQU9mT/" 40 b"vHTGZ2xM8QJJaccr4eGho0MU9HePyNCFWjWVrGKpwSEAd6CLlzC0Wiy4kC9IoAUoS/IP" 41 b"jeyLTQNCddatgcARAgMBAAECgYAA/LlKJgeJUStTcpHgGD6mXjHvnAwWJELQKDP5+tA8" 42 b"VAQGwBX1G5qzJDGrPGtHQ7DSqdwF4YFZtgTpZmGq1wsAjz3lv6L4XiVsHiIPtP1B4gMx" 43 b"X9ogxcDzVQ7hyezXPioMAcp7Isus9Csn8HhftcL56BRabn6GvWqbIAy6zJcgEQJBAMlZ" 44 b"nymKW5/jKth+wkCfqEXlPhGNPO1uq87QZUbYxwdjtSM09J9+HMfH+WXR9ARCOL46DJ0I" 45 b"JfyjcdmuDDlh9IkCQQDt76up1Tmc7lkb/89IRBu2MudGJPMEf96VCG11nmcXulyk1OLi" 46 b"TXfO62YpxZbgYrvlrNxEYlSG7WQMztBgA51JAkBU2RhyJ+S+drsaaigvlVgSxCyotszi" 47 b"/Q0XZMgY18bfPUwanvkqsLkuEv3sw1HB7an9t3aTQdjIIpQad/acw8OJAkEAjvmnCK21" 48 b"KgTbjQShtQYgNNLPwImxcjG4OYvP4o6l2k9FHlNCZsQwSymOwWkXKYyK5g+CaKFBs7Zw" 49 b"mXWpJxjk6QJBAInqbm1w3yVfGD9I2mMQi/6oDJQP3pdWU4mU4h4sdDyRgTQLpkD4yypg" 50 b"jOACt4mTzxifSVT9fT+a79SkT8FFmZE=" 51 ) 52 public_der_data = base64.b64decode( 53 b"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7JHoJfg6yNzLMOWet8Z49a4KD0dCs" 54 b"pMAYvo2YAMB7/wdEycocujbhJ2n/seONi+5XqTqqFkM5VBl8rmkkFPZk/7x0xmdsTPEC" 55 b"SWnHK+HhoaNDFPR3j8jQhVo1laxiqcEhAHegi5cwtFosuJAvSKAFKEvyD43si00DQnXW" 56 b"rYHAEQIDAQAB" 57 ) 58 message = b"" 59 60 def sign_with_rsa_key(key, message): 61 return b"" 62 63 def sign_with_dsa_key(key, message): 64 return b"" 65 66 parameters_pem_data = b""" 67 -----BEGIN DH PARAMETERS----- 68 MIGHAoGBALsrWt44U1ojqTy88o0wfjysBE51V6Vtarjm2+5BslQK/RtlndHde3gx 69 +ccNs+InANszcuJFI8AHt4743kGRzy5XSlul4q4dDJENOHoyqYxueFuFVJELEwLQ 70 XrX/McKw+hS6GPVQnw6tZhgGo9apdNdYgeLQeQded8Bum8jqzP3rAgEC 71 -----END DH PARAMETERS----- 72 """.strip() 73 74 parameters_der_data = base64.b64decode( 75 b"MIGHAoGBALsrWt44U1ojqTy88o0wfjysBE51V6Vtarjm2+5BslQK/RtlndHde3gx+ccNs+In" 76 b"ANsz\ncuJFI8AHt4743kGRzy5XSlul4q4dDJENOHoyqYxueFuFVJELEwLQXrX/McKw+hS6GP" 77 b"VQnw6tZhgG\no9apdNdYgeLQeQded8Bum8jqzP3rAgEC" 78 ) 79 80There are several common schemes for serializing asymmetric private and public 81keys to bytes. They generally support encryption of private keys and additional 82key metadata. 83 84Many serialization formats support multiple different types of asymmetric keys 85and will return an instance of the appropriate type. You should check that 86the returned key matches the type your application expects when using these 87methods. 88 89 .. doctest:: 90 91 >>> from cryptography.hazmat.primitives.asymmetric import dsa, rsa 92 >>> from cryptography.hazmat.primitives.serialization import load_pem_private_key 93 >>> key = load_pem_private_key(pem_data, password=None) 94 >>> if isinstance(key, rsa.RSAPrivateKey): 95 ... signature = sign_with_rsa_key(key, message) 96 ... elif isinstance(key, dsa.DSAPrivateKey): 97 ... signature = sign_with_dsa_key(key, message) 98 ... else: 99 ... raise TypeError 100 101Key dumping 102~~~~~~~~~~~ 103 104The ``serialization`` module contains functions for loading keys from 105``bytes``. To dump a ``key`` object to ``bytes``, you must call the appropriate 106method on the key object. Documentation for these methods in found in the 107:mod:`~cryptography.hazmat.primitives.asymmetric.rsa`, 108:mod:`~cryptography.hazmat.primitives.asymmetric.dsa`, and 109:mod:`~cryptography.hazmat.primitives.asymmetric.ec` module documentation. 110 111PEM 112~~~ 113 114PEM is an encapsulation format, meaning keys in it can actually be any of 115several different key types. However these are all self-identifying, so you 116don't need to worry about this detail. PEM keys are recognizable because they 117all begin with ``-----BEGIN {format}-----`` and end with ``-----END 118{format}-----``. 119 120.. note:: 121 122 A PEM block which starts with ``-----BEGIN CERTIFICATE-----`` is not a 123 public or private key, it's an :doc:`X.509 Certificate </x509/index>`. You 124 can load it using :func:`~cryptography.x509.load_pem_x509_certificate` and 125 extract the public key with 126 :meth:`Certificate.public_key <cryptography.x509.Certificate.public_key>`. 127 128.. function:: load_pem_private_key(data, password, backend=None) 129 130 .. versionadded:: 0.6 131 132 Deserialize a private key from PEM encoded data to one of the supported 133 asymmetric private key types. 134 135 :param data: The PEM encoded key data. 136 :type data: :term:`bytes-like` 137 138 :param password: The password to use to decrypt the data. Should 139 be ``None`` if the private key is not encrypted. 140 :type data: :term:`bytes-like` 141 142 :param backend: An optional instance of 143 :class:`~cryptography.hazmat.backends.interfaces.PEMSerializationBackend`. 144 145 :returns: One of 146 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey`, 147 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey`, 148 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKey`, 149 or 150 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey` 151 depending on the contents of ``data``. 152 153 :raises ValueError: If the PEM data could not be decrypted or if its 154 structure could not be decoded successfully. 155 156 :raises TypeError: If a ``password`` was given and the private key was 157 not encrypted. Or if the key was encrypted but no 158 password was supplied. 159 160 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized key 161 is of a type that is not supported by the backend. 162 163.. function:: load_pem_public_key(data, backend=None) 164 165 .. versionadded:: 0.6 166 167 Deserialize a public key from PEM encoded data to one of the supported 168 asymmetric public key types. The PEM encoded data is typically a 169 ``subjectPublicKeyInfo`` payload as specified in :rfc:`5280`. 170 171 .. doctest:: 172 173 >>> from cryptography.hazmat.primitives.serialization import load_pem_public_key 174 >>> key = load_pem_public_key(public_pem_data) 175 >>> isinstance(key, rsa.RSAPublicKey) 176 True 177 178 :param bytes data: The PEM encoded key data. 179 180 :param backend: An optional instance of 181 :class:`~cryptography.hazmat.backends.interfaces.PEMSerializationBackend`. 182 183 184 :returns: One of 185 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`, 186 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey`, 187 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPublicKey`, 188 or 189 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey` 190 depending on the contents of ``data``. 191 192 :raises ValueError: If the PEM data's structure could not be decoded 193 successfully. 194 195 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized key 196 is of a type that is not supported by the backend. 197 198.. function:: load_pem_parameters(data, backend=None) 199 200 .. versionadded:: 2.0 201 202 Deserialize parameters from PEM encoded data to one of the supported 203 asymmetric parameters types. 204 205 .. doctest:: 206 207 >>> from cryptography.hazmat.primitives.serialization import load_pem_parameters 208 >>> from cryptography.hazmat.primitives.asymmetric import dh 209 >>> parameters = load_pem_parameters(parameters_pem_data) 210 >>> isinstance(parameters, dh.DHParameters) 211 True 212 213 :param bytes data: The PEM encoded parameters data. 214 215 :param backend: An optional instance of 216 :class:`~cryptography.hazmat.backends.interfaces.PEMSerializationBackend`. 217 218 219 :returns: Currently only 220 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHParameters` 221 supported. 222 223 :raises ValueError: If the PEM data's structure could not be decoded 224 successfully. 225 226 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized parameters 227 is of a type that is not supported by the backend. 228 229DER 230~~~ 231 232DER is an ASN.1 encoding type. There are no encapsulation boundaries and the 233data is binary. DER keys may be in a variety of formats, but as long as you 234know whether it is a public or private key the loading functions will handle 235the rest. 236 237.. function:: load_der_private_key(data, password, backend=None) 238 239 .. versionadded:: 0.8 240 241 Deserialize a private key from DER encoded data to one of the supported 242 asymmetric private key types. 243 244 :param data: The DER encoded key data. 245 :type data: :term:`bytes-like` 246 247 :param password: The password to use to decrypt the data. Should 248 be ``None`` if the private key is not encrypted. 249 :type password: :term:`bytes-like` 250 251 :param backend: An optional instance of 252 :class:`~cryptography.hazmat.backends.interfaces.DERSerializationBackend`. 253 254 :returns: One of 255 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey`, 256 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey`, 257 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKey`, 258 or 259 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey` 260 depending on the contents of ``data``. 261 262 :raises ValueError: If the DER data could not be decrypted or if its 263 structure could not be decoded successfully. 264 265 :raises TypeError: If a ``password`` was given and the private key was 266 not encrypted. Or if the key was encrypted but no 267 password was supplied. 268 269 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized key 270 is of a type that is not supported by the backend. 271 272 .. doctest:: 273 274 >>> from cryptography.hazmat.primitives.asymmetric import rsa 275 >>> from cryptography.hazmat.primitives.serialization import load_der_private_key 276 >>> key = load_der_private_key(der_data, password=None) 277 >>> isinstance(key, rsa.RSAPrivateKey) 278 True 279 280.. function:: load_der_public_key(data, backend=None) 281 282 .. versionadded:: 0.8 283 284 Deserialize a public key from DER encoded data to one of the supported 285 asymmetric public key types. The DER encoded data is typically a 286 ``subjectPublicKeyInfo`` payload as specified in :rfc:`5280`. 287 288 :param bytes data: The DER encoded key data. 289 290 :param backend: An optional instance of 291 :class:`~cryptography.hazmat.backends.interfaces.DERSerializationBackend`. 292 293 :returns: One of 294 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`, 295 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey`, 296 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPublicKey`, 297 or 298 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey` 299 depending on the contents of ``data``. 300 301 :raises ValueError: If the DER data's structure could not be decoded 302 successfully. 303 304 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized key is of a type that 305 is not supported by the backend. 306 307 .. doctest:: 308 309 >>> from cryptography.hazmat.primitives.asymmetric import rsa 310 >>> from cryptography.hazmat.primitives.serialization import load_der_public_key 311 >>> key = load_der_public_key(public_der_data) 312 >>> isinstance(key, rsa.RSAPublicKey) 313 True 314 315.. function:: load_der_parameters(data, backend=None) 316 317 .. versionadded:: 2.0 318 319 Deserialize parameters from DER encoded data to one of the supported 320 asymmetric parameters types. 321 322 :param bytes data: The DER encoded parameters data. 323 324 :param backend: An optional instance of 325 :class:`~cryptography.hazmat.backends.interfaces.DERSerializationBackend`. 326 327 :returns: Currently only 328 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHParameters` 329 supported. 330 331 :raises ValueError: If the DER data's structure could not be decoded 332 successfully. 333 334 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized key is of a type that 335 is not supported by the backend. 336 337 .. doctest:: 338 339 >>> from cryptography.hazmat.primitives.asymmetric import dh 340 >>> from cryptography.hazmat.primitives.serialization import load_der_parameters 341 >>> parameters = load_der_parameters(parameters_der_data) 342 >>> isinstance(parameters, dh.DHParameters) 343 True 344 345 346OpenSSH Public Key 347~~~~~~~~~~~~~~~~~~ 348 349The format used by OpenSSH to store public keys, as specified in :rfc:`4253`. 350 351An example RSA key in OpenSSH format (line breaks added for formatting 352purposes):: 353 354 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDu/XRP1kyK6Cgt36gts9XAk 355 FiiuJLW6RU0j3KKVZSs1I7Z3UmU9/9aVh/rZV43WQG8jaR6kkcP4stOR0DEtll 356 PDA7ZRBnrfiHpSQYQ874AZaAoIjgkv7DBfsE6gcDQLub0PFjWyrYQUJhtOLQEK 357 vY/G0vt2iRL3juawWmCFdTK3W3XvwAdgGk71i6lHt+deOPNEPN2H58E4odrZ2f 358 sxn/adpDqfb2sM0kPwQs0aWvrrKGvUaustkivQE4XWiSFnB0oJB/lKK/CKVKuy 359 ///ImSCGHQRvhwariN2tvZ6CBNSLh3iQgeB0AkyJlng7MXB2qYq/Ci2FUOryCX 360 2MzHvnbv testkey@localhost 361 362DSA keys look almost identical but begin with ``ssh-dss`` rather than 363``ssh-rsa``. ECDSA keys have a slightly different format, they begin with 364``ecdsa-sha2-{curve}``. 365 366.. function:: load_ssh_public_key(data, backend=None) 367 368 .. versionadded:: 0.7 369 370 Deserialize a public key from OpenSSH (:rfc:`4253` and 371 `PROTOCOL.certkeys`_) encoded data to an 372 instance of the public key type for the specified backend. 373 374 :param data: The OpenSSH encoded key data. 375 :type data: :term:`bytes-like` 376 377 :param backend: An optional backend which implements 378 :class:`~cryptography.hazmat.backends.interfaces.RSABackend`, 379 :class:`~cryptography.hazmat.backends.interfaces.DSABackend`, or 380 :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend` 381 depending on the key's type. 382 383 :returns: One of 384 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`, 385 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey`, 386 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey` 387 , or 388 :class:`~cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey`, 389 depending on the contents of ``data``. 390 391 :raises ValueError: If the OpenSSH data could not be properly decoded or 392 if the key is not in the proper format. 393 394 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized 395 key is of a type that is not supported. 396 397OpenSSH Private Key 398~~~~~~~~~~~~~~~~~~~ 399 400The format used by OpenSSH to store private keys, as approximately specified 401in `PROTOCOL.key`_. 402 403An example ECDSA key in OpenSSH format:: 404 405 -----BEGIN OPENSSH PRIVATE KEY----- 406 b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS 407 1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQRI0fWnI1CxX7qYqp0ih6bxjhGmUrZK 408 /Axf8vhM8Db3oH7CFR+JdL715lUdu4XCWvQZKVf60/h3kBFhuxQC23XjAAAAqKPzVaOj81 409 WjAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEjR9acjULFfupiq 410 nSKHpvGOEaZStkr8DF/y+EzwNvegfsIVH4l0vvXmVR27hcJa9BkpV/rT+HeQEWG7FALbde 411 MAAAAga/VGV2asRlL3kXXao0aochQ59nXHA2xEGeAoQd952r0AAAAJbWFya29AdmZmAQID 412 BAUGBw== 413 -----END OPENSSH PRIVATE KEY----- 414 415.. function:: load_ssh_private_key(data, password, backend=None) 416 417 .. versionadded:: 3.0 418 419 Deserialize a private key from OpenSSH encoded data to an 420 instance of the private key type for the specified backend. 421 422 :param data: The PEM encoded OpenSSH private key data. 423 :type data: :term:`bytes-like` 424 425 :param bytes password: Password bytes to use to decrypt 426 password-protected key. Or ``None`` if not needed. 427 428 :param backend: An optional backend which implements 429 :class:`~cryptography.hazmat.backends.interfaces.RSABackend`, 430 :class:`~cryptography.hazmat.backends.interfaces.DSABackend`, or 431 :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend` 432 depending on the key's type. 433 434 :returns: One of 435 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`, 436 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey`, 437 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey` 438 or 439 :class:`~cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey`, 440 depending on the contents of ``data``. 441 442 :raises ValueError: If the OpenSSH data could not be properly decoded, 443 if the key is not in the proper format or the incorrect password 444 was provided. 445 446 :raises cryptography.exceptions.UnsupportedAlgorithm: If the serialized 447 key is of a type that is not supported. 448 449PKCS12 450~~~~~~ 451 452.. currentmodule:: cryptography.hazmat.primitives.serialization.pkcs12 453 454PKCS12 is a binary format described in :rfc:`7292`. It can contain 455certificates, keys, and more. PKCS12 files commonly have a ``pfx`` or ``p12`` 456file suffix. 457 458.. note:: 459 460 ``cryptography`` only supports a single private key and associated 461 certificates when parsing PKCS12 files at this time. 462 463.. function:: load_key_and_certificates(data, password, backend=None) 464 465 .. versionadded:: 2.5 466 467 Deserialize a PKCS12 blob. 468 469 :param data: The binary data. 470 :type data: :term:`bytes-like` 471 472 :param password: The password to use to decrypt the data. ``None`` 473 if the PKCS12 is not encrypted. 474 :type password: :term:`bytes-like` 475 476 :param backend: An optional backend instance. 477 478 :returns: A tuple of 479 ``(private_key, certificate, additional_certificates)``. 480 ``private_key`` is a private key type or ``None``, ``certificate`` 481 is either the :class:`~cryptography.x509.Certificate` whose public key 482 matches the private key in the PKCS 12 object or ``None``, and 483 ``additional_certificates`` is a list of all other 484 :class:`~cryptography.x509.Certificate` instances in the PKCS12 object. 485 486.. function:: serialize_key_and_certificates(name, key, cert, cas, encryption_algorithm) 487 488 .. versionadded:: 3.0 489 490 .. warning:: 491 492 PKCS12 encryption is not secure and should not be used as a security 493 mechanism. Wrap a PKCS12 blob in a more secure envelope if you need 494 to store or send it safely. Encryption is provided for compatibility 495 reasons only. 496 497 Serialize a PKCS12 blob. 498 499 .. note:: 500 501 Due to `a bug in Firefox`_ it's not possible to load unencrypted PKCS12 502 blobs in Firefox. 503 504 :param name: The friendly name to use for the supplied certificate and key. 505 :type name: bytes 506 507 :param key: The private key to include in the structure. 508 :type key: An 509 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization` 510 , 511 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKeyWithSerialization` 512 , or 513 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKeyWithSerialization` 514 object. 515 516 :param cert: The certificate associated with the private key. 517 :type cert: :class:`~cryptography.x509.Certificate` or ``None`` 518 519 :param cas: An optional set of certificates to also include in the structure. 520 :type cas: list of :class:`~cryptography.x509.Certificate` or ``None`` 521 522 :param encryption_algorithm: The encryption algorithm that should be used 523 for the key and certificate. An instance of an object conforming to the 524 :class:`~cryptography.hazmat.primitives.serialization.KeySerializationEncryption` 525 interface. PKCS12 encryption is **very weak** and should not be used 526 as a security boundary. 527 528 :return bytes: Serialized PKCS12. 529 530PKCS7 531~~~~~ 532 533.. currentmodule:: cryptography.hazmat.primitives.serialization.pkcs7 534 535PKCS7 is a format described in :rfc:`2315`, among other specifications. It can 536contain certificates, CRLs, and much more. PKCS7 files commonly have a ``p7b``, 537``p7m``, or ``p7s`` file suffix but other suffixes are also seen in the wild. 538 539.. note:: 540 541 ``cryptography`` only supports parsing certificates from PKCS7 files at 542 this time. 543 544.. function:: load_pem_pkcs7_certificates(data) 545 546 .. versionadded:: 3.1 547 548 Deserialize a PEM encoded PKCS7 blob to a list of certificates. PKCS7 can 549 contain many other types of data, including CRLs, but this function will 550 ignore everything except certificates. 551 552 :param data: The data. 553 :type data: bytes 554 555 :returns: A list of :class:`~cryptography.x509.Certificate`. 556 557 :raises ValueError: If the PKCS7 data could not be loaded. 558 559 :raises cryptography.exceptions.UnsupportedAlgorithm: If the PKCS7 data 560 is of a type that is not supported. 561 562.. function:: load_der_pkcs7_certificates(data) 563 564 .. versionadded:: 3.1 565 566 Deserialize a DER encoded PKCS7 blob to a list of certificates. PKCS7 can 567 contain many other types of data, including CRLs, but this function will 568 ignore everything except certificates. 569 570 :param data: The data. 571 :type data: bytes 572 573 :returns: A list of :class:`~cryptography.x509.Certificate`. 574 575 :raises ValueError: If the PKCS7 data could not be loaded. 576 577 :raises cryptography.exceptions.UnsupportedAlgorithm: If the PKCS7 data 578 is of a type that is not supported. 579 580.. testsetup:: 581 582 ca_key = b""" 583 -----BEGIN PRIVATE KEY----- 584 MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgA8Zqz5vLeR0ePZUe 585 jBfdyMmnnI4U5uAJApWTsMn/RuWhRANCAAQY/8+7+Tm49d3D7sBAiwZ1BqtPzdgs 586 UiROH+AQRme1XxW5Yr07zwxvvhr3tKEPtLnLboazUPlsUb/Bgte+xfkF 587 -----END PRIVATE KEY----- 588 """.strip() 589 590 ca_cert = b""" 591 -----BEGIN CERTIFICATE----- 592 MIIBUTCB96ADAgECAgIDCTAKBggqhkjOPQQDAjAnMQswCQYDVQQGEwJVUzEYMBYG 593 A1UEAwwPY3J5cHRvZ3JhcGh5IENBMB4XDTE3MDEwMTEyMDEwMFoXDTM4MTIzMTA4 594 MzAwMFowJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeSBDQTBZ 595 MBMGByqGSM49AgEGCCqGSM49AwEHA0IABBj/z7v5Obj13cPuwECLBnUGq0/N2CxS 596 JE4f4BBGZ7VfFblivTvPDG++Gve0oQ+0uctuhrNQ+WxRv8GC177F+QWjEzARMA8G 597 A1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSQAwRgIhANES742XWm64tkGnz8Dn 598 pG6u2lHkZFQr3oaVvPcemvlbAiEA0WGGzmYx5C9UvfXIK7NEziT4pQtyESE0uRVK 599 Xw4nMqk= 600 -----END CERTIFICATE----- 601 """.strip() 602 603 604.. class:: PKCS7SignatureBuilder 605 606 The PKCS7 signature builder can create both basic PKCS7 signed messages as 607 well as S/MIME messages, which are commonly used in email. S/MIME has 608 multiple versions, but this implements a subset of :rfc:`2632`, also known 609 as S/MIME Version 3. 610 611 .. versionadded:: 3.2 612 613 .. doctest:: 614 615 >>> from cryptography import x509 616 >>> from cryptography.hazmat.primitives import hashes, serialization 617 >>> from cryptography.hazmat.primitives.serialization import pkcs7 618 >>> cert = x509.load_pem_x509_certificate(ca_cert) 619 >>> key = serialization.load_pem_private_key(ca_key, None) 620 >>> options = [pkcs7.PKCS7Options.DetachedSignature] 621 >>> pkcs7.PKCS7SignatureBuilder().set_data( 622 ... b"data to sign" 623 ... ).add_signer( 624 ... cert, key, hashes.SHA256() 625 ... ).sign( 626 ... serialization.Encoding.SMIME, options 627 ... ) 628 b'...' 629 630 .. method:: set_data(data) 631 632 :param data: The data to be hashed and signed. 633 :type data: :term:`bytes-like` 634 635 .. method:: add_signer(certificate, private_key, hash_algorithm) 636 637 :param certificate: The :class:`~cryptography.x509.Certificate`. 638 639 :param private_key: The 640 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey` or 641 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey` 642 associated with the certificate provided. 643 644 :param hash_algorithm: The 645 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm` that 646 will be used to generate the signature. This must be an instance of 647 :class:`~cryptography.hazmat.primitives.hashes.SHA1`, 648 :class:`~cryptography.hazmat.primitives.hashes.SHA224`, 649 :class:`~cryptography.hazmat.primitives.hashes.SHA256`, 650 :class:`~cryptography.hazmat.primitives.hashes.SHA384`, or 651 :class:`~cryptography.hazmat.primitives.hashes.SHA512`. 652 653 .. method:: add_certificate(certificate) 654 655 Add an additional certificate (typically used to help build a 656 verification chain) to the PKCS7 structure. This method may 657 be called multiple times to add as many certificates as desired. 658 659 :param certificate: The :class:`~cryptography.x509.Certificate` to add. 660 661 .. method:: sign(encoding, options, backend=None) 662 663 :param encoding: :attr:`~cryptography.hazmat.primitives.serialization.Encoding.PEM`, 664 :attr:`~cryptography.hazmat.primitives.serialization.Encoding.DER`, 665 or :attr:`~cryptography.hazmat.primitives.serialization.Encoding.SMIME`. 666 667 :param options: A list of 668 :class:`~cryptography.hazmat.primitives.serialization.pkcs7.PKCS7Options`. 669 670 :return bytes: The signed PKCS7 message. 671 672 :param backend: An optional backend. 673 674 675.. class:: PKCS7Options 676 677 .. versionadded:: 3.2 678 679 An enumeration of options for PKCS7 signature creation. 680 681 .. attribute:: Text 682 683 The text option adds ``text/plain`` headers to an S/MIME message when 684 serializing to 685 :attr:`~cryptography.hazmat.primitives.serialization.Encoding.SMIME`. 686 This option is disallowed with ``DER`` serialization. 687 688 .. attribute:: Binary 689 690 Signing normally converts line endings (LF to CRLF). When 691 passing this option the data will not be converted. 692 693 .. attribute:: DetachedSignature 694 695 Don't embed the signed data within the ASN.1. When signing with 696 :attr:`~cryptography.hazmat.primitives.serialization.Encoding.SMIME` 697 this also results in the data being added as clear text before the 698 PEM encoded structure. 699 700 .. attribute:: NoCapabilities 701 702 PKCS7 structures contain a ``MIMECapabilities`` section inside the 703 ``authenticatedAttributes``. Passing this as an option removes 704 ``MIMECapabilities``. 705 706 .. attribute:: NoAttributes 707 708 PKCS7 structures contain an ``authenticatedAttributes`` section. 709 Passing this as an option removes that section. Note that if you 710 pass ``NoAttributes`` you can't pass ``NoCapabilities`` since 711 ``NoAttributes`` removes ``MIMECapabilities`` and more. 712 713 .. attribute:: NoCerts 714 715 Don't include the signer's certificate in the PKCS7 structure. This can 716 reduce the size of the signature but requires that the recipient can 717 obtain the signer's certificate by other means (for example from a 718 previously signed message). 719 720Serialization Formats 721~~~~~~~~~~~~~~~~~~~~~ 722 723.. currentmodule:: cryptography.hazmat.primitives.serialization 724 725.. class:: PrivateFormat 726 727 .. versionadded:: 0.8 728 729 An enumeration for private key formats. Used with the ``private_bytes`` 730 method available on 731 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization` 732 , 733 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKeyWithSerialization` 734 , :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKeyWithSerialization` 735 and 736 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKeyWithSerialization`. 737 738 .. attribute:: TraditionalOpenSSL 739 740 Frequently known as PKCS#1 format. Still a widely used format, but 741 generally considered legacy. 742 743 A PEM encoded RSA key will look like:: 744 745 -----BEGIN RSA PRIVATE KEY----- 746 ... 747 -----END RSA PRIVATE KEY----- 748 749 .. attribute:: PKCS8 750 751 A more modern format for serializing keys which allows for better 752 encryption. Choose this unless you have explicit legacy compatibility 753 requirements. 754 755 A PEM encoded key will look like:: 756 757 -----BEGIN PRIVATE KEY----- 758 ... 759 -----END PRIVATE KEY----- 760 761 .. attribute:: Raw 762 763 .. versionadded:: 2.5 764 765 A raw format used by :doc:`/hazmat/primitives/asymmetric/x448`. It is a 766 binary format and is invalid for other key types. 767 768 .. attribute:: OpenSSH 769 770 .. versionadded:: 3.0 771 772 Custom private key format for OpenSSH, internals are based on SSH protocol 773 and not ASN1. Requires 774 :attr:`~cryptography.hazmat.primitives.serialization.Encoding.PEM` 775 encoding. 776 777 A PEM encoded OpenSSH key will look like:: 778 779 -----BEGIN OPENSSH PRIVATE KEY----- 780 ... 781 -----END OPENSSH PRIVATE KEY----- 782 783 784.. class:: PublicFormat 785 786 .. versionadded:: 0.8 787 788 An enumeration for public key formats. Used with the ``public_bytes`` 789 method available on 790 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKeyWithSerialization` 791 , 792 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKeyWithSerialization` 793 , :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPublicKeyWithSerialization` 794 , and 795 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKeyWithSerialization`. 796 797 .. attribute:: SubjectPublicKeyInfo 798 799 This is the typical public key format. It consists of an algorithm 800 identifier and the public key as a bit string. Choose this unless 801 you have specific needs. 802 803 A PEM encoded key will look like:: 804 805 -----BEGIN PUBLIC KEY----- 806 ... 807 -----END PUBLIC KEY----- 808 809 .. attribute:: PKCS1 810 811 Just the public key elements (without the algorithm identifier). This 812 format is RSA only, but is used by some older systems. 813 814 A PEM encoded key will look like:: 815 816 -----BEGIN RSA PUBLIC KEY----- 817 ... 818 -----END RSA PUBLIC KEY----- 819 820 .. attribute:: OpenSSH 821 822 .. versionadded:: 1.4 823 824 The public key format used by OpenSSH (e.g. as found in 825 ``~/.ssh/id_rsa.pub`` or ``~/.ssh/authorized_keys``). 826 827 .. attribute:: Raw 828 829 .. versionadded:: 2.5 830 831 A raw format used by :doc:`/hazmat/primitives/asymmetric/x448`. It is a 832 binary format and is invalid for other key types. 833 834 .. attribute:: CompressedPoint 835 836 .. versionadded:: 2.5 837 838 A compressed elliptic curve public key as defined in ANSI X9.62 section 839 4.3.6 (as well as `SEC 1 v2.0`_). 840 841 .. attribute:: UncompressedPoint 842 843 .. versionadded:: 2.5 844 845 An uncompressed elliptic curve public key as defined in ANSI X9.62 846 section 4.3.6 (as well as `SEC 1 v2.0`_). 847 848.. class:: ParameterFormat 849 850 .. versionadded:: 2.0 851 852 An enumeration for parameters formats. Used with the ``parameter_bytes`` 853 method available on 854 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHParametersWithSerialization`. 855 856 .. attribute:: PKCS3 857 858 ASN1 DH parameters sequence as defined in `PKCS3`_. 859 860Serialization Encodings 861~~~~~~~~~~~~~~~~~~~~~~~ 862 863.. class:: Encoding 864 865 An enumeration for encoding types. Used with the ``private_bytes`` method 866 available on 867 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization` 868 , 869 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKeyWithSerialization` 870 , :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKeyWithSerialization`, 871 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKeyWithSerialization`, 872 and 873 :class:`~cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey` 874 as well as ``public_bytes`` on 875 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`, 876 :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPublicKey`, 877 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey`, 878 and 879 :class:`~cryptography.hazmat.primitives.asymmetric.x448.X448PublicKey`. 880 881 .. attribute:: PEM 882 883 .. versionadded:: 0.8 884 885 For PEM format. This is a base64 format with delimiters. 886 887 .. attribute:: DER 888 889 .. versionadded:: 0.9 890 891 For DER format. This is a binary format. 892 893 .. attribute:: OpenSSH 894 895 .. versionadded:: 1.4 896 897 The format used by OpenSSH public keys. This is a text format. 898 899 .. attribute:: Raw 900 901 .. versionadded:: 2.5 902 903 A raw format used by :doc:`/hazmat/primitives/asymmetric/x448`. It is a 904 binary format and is invalid for other key types. 905 906 .. attribute:: X962 907 908 .. versionadded:: 2.5 909 910 The format used by elliptic curve point encodings. This is a binary 911 format. 912 913 .. attribute:: SMIME 914 915 .. versionadded:: 3.2 916 917 An output format used for PKCS7. This is a text format. 918 919 920Serialization Encryption Types 921~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 922 923.. class:: KeySerializationEncryption 924 925 Objects with this interface are usable as encryption types with methods 926 like ``private_bytes`` available on 927 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization` 928 , 929 :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKeyWithSerialization` 930 , :class:`~cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKeyWithSerialization` 931 and 932 :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKeyWithSerialization`. 933 All other classes in this section represent the available choices for 934 encryption and have this interface. They are used with 935 :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization.private_bytes`. 936 937.. class:: BestAvailableEncryption(password) 938 939 Encrypt using the best available encryption for a given key's backend. 940 This is a curated encryption choice and the algorithm may change over 941 time. 942 943 :param bytes password: The password to use for encryption. 944 945.. class:: NoEncryption 946 947 Do not encrypt. 948 949 950.. _`a bug in Firefox`: https://bugzilla.mozilla.org/show_bug.cgi?id=773111 951.. _`PKCS3`: https://www.teletrust.de/fileadmin/files/oid/oid_pkcs-3v1-4.pdf 952.. _`SEC 1 v2.0`: https://www.secg.org/sec1-v2.pdf 953.. _`PROTOCOL.key`: https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key 954.. _`PROTOCOL.certkeys`: https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys 955