1.. hazmat::
2
3Elliptic curve cryptography
4===========================
5
6.. module:: cryptography.hazmat.primitives.asymmetric.ec
7
8
9.. function:: generate_private_key(curve, backend)
10
11    .. versionadded:: 0.5
12
13    Generate a new private key on ``curve`` for use with ``backend``.
14
15    :param curve: An instance of :class:`EllipticCurve`.
16
17    :param backend: An instance of
18        :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend`.
19
20    :returns: A new instance of :class:`EllipticCurvePrivateKey`.
21
22
23.. function:: derive_private_key(private_value, curve, backend)
24
25    .. versionadded:: 1.6
26
27    Derive a private key from ``private_value`` on ``curve`` for use with
28    ``backend``.
29
30    :param int private_value: The secret scalar value.
31
32    :param curve: An instance of :class:`EllipticCurve`.
33
34    :param backend: An instance of
35        :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend`.
36
37    :returns: A new instance of :class:`EllipticCurvePrivateKey`.
38
39
40Elliptic Curve Signature Algorithms
41-----------------------------------
42
43.. class:: ECDSA(algorithm)
44
45    .. versionadded:: 0.5
46
47    The ECDSA signature algorithm first standardized in NIST publication
48    `FIPS 186-3`_, and later in `FIPS 186-4`_.
49
50    :param algorithm: An instance of
51        :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
52
53    .. doctest::
54
55        >>> from cryptography.hazmat.backends import default_backend
56        >>> from cryptography.hazmat.primitives import hashes
57        >>> from cryptography.hazmat.primitives.asymmetric import ec
58        >>> private_key = ec.generate_private_key(
59        ...     ec.SECP384R1(), default_backend()
60        ... )
61        >>> data = b"this is some data I'd like to sign"
62        >>> signature = private_key.sign(
63        ...     data,
64        ...     ec.ECDSA(hashes.SHA256())
65        ... )
66
67    The ``signature`` is a ``bytes`` object, whose contents is DER encoded as
68    described in :rfc:`3279`. This can be decoded using
69    :func:`~cryptography.hazmat.primitives.asymmetric.utils.decode_dss_signature`.
70
71    If your data is too large to be passed in a single call, you can hash it
72    separately and pass that value using
73    :class:`~cryptography.hazmat.primitives.asymmetric.utils.Prehashed`.
74
75    .. doctest::
76
77        >>> from cryptography.hazmat.primitives.asymmetric import utils
78        >>> chosen_hash = hashes.SHA256()
79        >>> hasher = hashes.Hash(chosen_hash, default_backend())
80        >>> hasher.update(b"data & ")
81        >>> hasher.update(b"more data")
82        >>> digest = hasher.finalize()
83        >>> sig = private_key.sign(
84        ...     digest,
85        ...     ec.ECDSA(utils.Prehashed(chosen_hash))
86        ... )
87
88
89    Verification requires the public key, the signature itself, the signed
90    data, and knowledge of the hashing algorithm that was used when producing
91    the signature:
92
93    >>> public_key = private_key.public_key()
94    >>> public_key.verify(signature, data, ec.ECDSA(hashes.SHA256()))
95
96    If the signature is not valid, an
97    :class:`~cryptography.exceptions.InvalidSignature` exception will be raised.
98
99    If your data is too large to be passed in a single call, you can hash it
100    separately and pass that value using
101    :class:`~cryptography.hazmat.primitives.asymmetric.utils.Prehashed`.
102
103    .. doctest::
104
105        >>> chosen_hash = hashes.SHA256()
106        >>> hasher = hashes.Hash(chosen_hash, default_backend())
107        >>> hasher.update(b"data & ")
108        >>> hasher.update(b"more data")
109        >>> digest = hasher.finalize()
110        >>> public_key.verify(
111        ...     sig,
112        ...     digest,
113        ...     ec.ECDSA(utils.Prehashed(chosen_hash))
114        ... )
115
116    .. note::
117        Although in this case the public key was derived from the private one,
118        in a typical setting you will not possess the private key. The
119        `Key loading`_ section explains how to load the public key from other
120        sources.
121
122
123.. class:: EllipticCurvePrivateNumbers(private_value, public_numbers)
124
125    .. versionadded:: 0.5
126
127    The collection of integers that make up an EC private key.
128
129    .. attribute:: public_numbers
130
131        :type: :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers`
132
133        The :class:`EllipticCurvePublicNumbers` which makes up the EC public
134        key associated with this EC private key.
135
136    .. attribute:: private_value
137
138        :type: int
139
140        The private value.
141
142    .. method:: private_key(backend)
143
144        Convert a collection of numbers into a private key suitable for doing
145        actual cryptographic operations.
146
147        :param backend: An instance of
148            :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend`.
149
150        :returns: A new instance of :class:`EllipticCurvePrivateKey`.
151
152
153.. class:: EllipticCurvePublicNumbers(x, y, curve)
154
155    .. warning::
156        The point represented by this object is not validated in any way until
157        :meth:`EllipticCurvePublicNumbers.public_key` is called and may not
158        represent a valid point on the curve. You should not attempt to perform
159        any computations using the values from this class until you have either
160        validated it yourself or called ``public_key()`` successfully.
161
162    .. versionadded:: 0.5
163
164    The collection of integers that make up an EC public key.
165
166     .. attribute:: curve
167
168        :type: :class:`EllipticCurve`
169
170        The elliptic curve for this key.
171
172    .. attribute:: x
173
174        :type: int
175
176        The affine x component of the public point used for verifying.
177
178    .. attribute:: y
179
180        :type: int
181
182        The affine y component of the public point used for verifying.
183
184    .. method:: public_key(backend)
185
186        Convert a collection of numbers into a public key suitable for doing
187        actual cryptographic operations.
188
189        :param backend: An instance of
190            :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend`.
191
192        :raises ValueError: Raised if the point is invalid for the curve.
193        :returns: A new instance of :class:`EllipticCurvePublicKey`.
194
195    .. method:: encode_point()
196
197        .. warning::
198
199            This method is deprecated as of version 2.5. Callers should migrate
200            to using
201            :meth:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.public_bytes`.
202
203        .. versionadded:: 1.1
204
205        Encodes an elliptic curve point to a byte string as described in
206        `SEC 1 v2.0`_ section 2.3.3. This method only supports uncompressed
207        points.
208
209        :return bytes: The encoded point.
210
211    .. classmethod:: from_encoded_point(curve, data)
212
213        .. versionadded:: 1.1
214
215        .. note::
216
217            This has been deprecated in favor of
218            :meth:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.from_encoded_point`
219
220        Decodes a byte string as described in `SEC 1 v2.0`_ section 2.3.3 and
221        returns an :class:`EllipticCurvePublicNumbers`. This method only
222        supports uncompressed points.
223
224        :param curve: An
225            :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve`
226            instance.
227
228        :param bytes data: The serialized point byte string.
229
230        :returns: An :class:`EllipticCurvePublicNumbers` instance.
231
232        :raises ValueError: Raised on invalid point type or data length.
233
234        :raises TypeError: Raised when curve is not an
235            :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve`.
236
237Elliptic Curve Key Exchange algorithm
238-------------------------------------
239
240.. class:: ECDH()
241
242    .. versionadded:: 1.1
243
244    The Elliptic Curve Diffie-Hellman Key Exchange algorithm first standardized
245    in NIST publication `800-56A`_, and later in `800-56Ar2`_.
246
247    For most applications the ``shared_key`` should be passed to a key
248    derivation function. This allows mixing of additional information into the
249    key, derivation of multiple keys, and destroys any structure that may be
250    present.
251
252    .. warning::
253
254        This example does not give `forward secrecy`_ and is only provided as a
255        demonstration of the basic Diffie-Hellman construction. For real world
256        applications always use the ephemeral form described after this example.
257
258    .. doctest::
259
260        >>> from cryptography.hazmat.backends import default_backend
261        >>> from cryptography.hazmat.primitives import hashes
262        >>> from cryptography.hazmat.primitives.asymmetric import ec
263        >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF
264        >>> # Generate a private key for use in the exchange.
265        >>> server_private_key = ec.generate_private_key(
266        ...     ec.SECP384R1(), default_backend()
267        ... )
268        >>> # In a real handshake the peer is a remote client. For this
269        >>> # example we'll generate another local private key though.
270        >>> peer_private_key = ec.generate_private_key(
271        ...     ec.SECP384R1(), default_backend()
272        ... )
273        >>> shared_key = server_private_key.exchange(
274        ...     ec.ECDH(), peer_private_key.public_key())
275        >>> # Perform key derivation.
276        >>> derived_key = HKDF(
277        ...     algorithm=hashes.SHA256(),
278        ...     length=32,
279        ...     salt=None,
280        ...     info=b'handshake data',
281        ...     backend=default_backend()
282        ... ).derive(shared_key)
283        >>> # And now we can demonstrate that the handshake performed in the
284        >>> # opposite direction gives the same final value
285        >>> same_shared_key = peer_private_key.exchange(
286        ...     ec.ECDH(), server_private_key.public_key())
287        >>> # Perform key derivation.
288        >>> same_derived_key = HKDF(
289        ...     algorithm=hashes.SHA256(),
290        ...     length=32,
291        ...     salt=None,
292        ...     info=b'handshake data',
293        ...     backend=default_backend()
294        ... ).derive(same_shared_key)
295        >>> derived_key == same_derived_key
296        True
297
298    ECDHE (or EECDH), the ephemeral form of this exchange, is **strongly
299    preferred** over simple ECDH and provides `forward secrecy`_ when used.
300    You must generate a new private key using :func:`generate_private_key` for
301    each :meth:`~EllipticCurvePrivateKey.exchange` when performing an ECDHE key
302    exchange. An example of the ephemeral form:
303
304    .. doctest::
305
306        >>> from cryptography.hazmat.backends import default_backend
307        >>> from cryptography.hazmat.primitives import hashes
308        >>> from cryptography.hazmat.primitives.asymmetric import ec
309        >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF
310        >>> # Generate a private key for use in the exchange.
311        >>> private_key = ec.generate_private_key(
312        ...     ec.SECP384R1(), default_backend()
313        ... )
314        >>> # In a real handshake the peer_public_key will be received from the
315        >>> # other party. For this example we'll generate another private key
316        >>> # and get a public key from that.
317        >>> peer_public_key = ec.generate_private_key(
318        ...     ec.SECP384R1(), default_backend()
319        ... ).public_key()
320        >>> shared_key = private_key.exchange(ec.ECDH(), peer_public_key)
321        >>> # Perform key derivation.
322        >>> derived_key = HKDF(
323        ...     algorithm=hashes.SHA256(),
324        ...     length=32,
325        ...     salt=None,
326        ...     info=b'handshake data',
327        ...     backend=default_backend()
328        ... ).derive(shared_key)
329        >>> # For the next handshake we MUST generate another private key.
330        >>> private_key_2 = ec.generate_private_key(
331        ...     ec.SECP384R1(), default_backend()
332        ... )
333        >>> peer_public_key_2 = ec.generate_private_key(
334        ...     ec.SECP384R1(), default_backend()
335        ... ).public_key()
336        >>> shared_key_2 = private_key_2.exchange(ec.ECDH(), peer_public_key_2)
337        >>> derived_key_2 = HKDF(
338        ...     algorithm=hashes.SHA256(),
339        ...     length=32,
340        ...     salt=None,
341        ...     info=b'handshake data',
342        ...     backend=default_backend()
343        ... ).derive(shared_key_2)
344
345Elliptic Curves
346---------------
347
348Elliptic curves provide equivalent security at much smaller key sizes than
349other asymmetric cryptography systems such as RSA or DSA. For many operations
350elliptic curves are also significantly faster; `elliptic curve diffie-hellman
351is faster than diffie-hellman`_.
352
353.. note::
354    Curves with a size of `less than 224 bits`_ should not be used. You should
355    strongly consider using curves of at least 224 :term:`bits`.
356
357Generally the NIST prime field ("P") curves are significantly faster than the
358other types suggested by NIST at both signing and verifying with ECDSA.
359
360Prime fields also `minimize the number of security concerns for elliptic-curve
361cryptography`_. However, there is `some concern`_ that both the prime field and
362binary field ("B") NIST curves may have been weakened during their generation.
363
364Currently `cryptography` only supports NIST curves, none of which are
365considered "safe" by the `SafeCurves`_ project run by Daniel J. Bernstein and
366Tanja Lange.
367
368All named curves are instances of :class:`EllipticCurve`.
369
370.. class:: SECP256R1
371
372    .. versionadded:: 0.5
373
374    SECG curve ``secp256r1``. Also called NIST P-256.
375
376
377.. class:: SECP384R1
378
379    .. versionadded:: 0.5
380
381    SECG curve ``secp384r1``. Also called NIST P-384.
382
383
384.. class:: SECP521R1
385
386    .. versionadded:: 0.5
387
388    SECG curve ``secp521r1``. Also called NIST P-521.
389
390
391.. class:: SECP224R1
392
393    .. versionadded:: 0.5
394
395    SECG curve ``secp224r1``. Also called NIST P-224.
396
397
398.. class:: SECP192R1
399
400    .. versionadded:: 0.5
401
402    SECG curve ``secp192r1``. Also called NIST P-192.
403
404
405.. class:: SECP256K1
406
407    .. versionadded:: 0.9
408
409    SECG curve ``secp256k1``.
410
411
412.. class:: BrainpoolP256R1
413
414    .. versionadded:: 2.2
415
416    Brainpool curve specified in :rfc:`5639`. These curves are discouraged
417    for new systems.
418
419.. class:: BrainpoolP384R1
420
421    .. versionadded:: 2.2
422
423    Brainpool curve specified in :rfc:`5639`. These curves are discouraged
424    for new systems.
425
426.. class:: BrainpoolP512R1
427
428    .. versionadded:: 2.2
429
430    Brainpool curve specified in :rfc:`5639`. These curves are discouraged
431    for new systems.
432
433.. class:: SECT571K1
434
435    .. versionadded:: 0.5
436
437    SECG curve ``sect571k1``. Also called NIST K-571. These binary curves are
438    discouraged for new systems.
439
440
441.. class:: SECT409K1
442
443    .. versionadded:: 0.5
444
445    SECG curve ``sect409k1``. Also called NIST K-409. These binary curves are
446    discouraged for new systems.
447
448
449.. class:: SECT283K1
450
451    .. versionadded:: 0.5
452
453    SECG curve ``sect283k1``. Also called NIST K-283. These binary curves are
454    discouraged for new systems.
455
456
457.. class:: SECT233K1
458
459    .. versionadded:: 0.5
460
461    SECG curve ``sect233k1``. Also called NIST K-233. These binary curves are
462    discouraged for new systems.
463
464
465.. class:: SECT163K1
466
467    .. versionadded:: 0.5
468
469    SECG curve ``sect163k1``. Also called NIST K-163. These binary curves are
470    discouraged for new systems.
471
472
473.. class:: SECT571R1
474
475    .. versionadded:: 0.5
476
477    SECG curve ``sect571r1``. Also called NIST B-571. These binary curves are
478    discouraged for new systems.
479
480
481.. class:: SECT409R1
482
483    .. versionadded:: 0.5
484
485    SECG curve ``sect409r1``. Also called NIST B-409. These binary curves are
486    discouraged for new systems.
487
488
489.. class:: SECT283R1
490
491    .. versionadded:: 0.5
492
493    SECG curve ``sect283r1``. Also called NIST B-283. These binary curves are
494    discouraged for new systems.
495
496
497.. class:: SECT233R1
498
499    .. versionadded:: 0.5
500
501    SECG curve ``sect233r1``. Also called NIST B-233. These binary curves are
502    discouraged for new systems.
503
504
505.. class:: SECT163R2
506
507    .. versionadded:: 0.5
508
509    SECG curve ``sect163r2``. Also called NIST B-163. These binary curves are
510    discouraged for new systems.
511
512
513
514
515Key Interfaces
516~~~~~~~~~~~~~~
517
518.. class:: EllipticCurve
519
520    .. versionadded:: 0.5
521
522    A named elliptic curve.
523
524    .. attribute:: name
525
526        :type: str
527
528        The name of the curve. Usually the name used for the ASN.1 OID such as
529        ``secp256k1``.
530
531    .. attribute:: key_size
532
533        :type: int
534
535        Size (in :term:`bits`) of a secret scalar for the curve (as generated
536        by :func:`generate_private_key`).
537
538
539.. class:: EllipticCurveSignatureAlgorithm
540
541    .. versionadded:: 0.5
542    .. versionchanged:: 1.6
543        :class:`~cryptography.hazmat.primitives.asymmetric.utils.Prehashed`
544        can now be used as an ``algorithm``.
545
546    A signature algorithm for use with elliptic curve keys.
547
548    .. attribute:: algorithm
549
550        :type: :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm` or
551            :class:`~cryptography.hazmat.primitives.asymmetric.utils.Prehashed`
552
553        The digest algorithm to be used with the signature scheme.
554
555
556.. class:: EllipticCurvePrivateKey
557
558    .. versionadded:: 0.5
559
560    An elliptic curve private key for use with an algorithm such as `ECDSA`_ or
561    `EdDSA`_. An elliptic curve private key that is not an
562    :term:`opaque key` also implements
563    :class:`EllipticCurvePrivateKeyWithSerialization` to provide serialization
564    methods.
565
566    .. method:: exchange(algorithm, peer_public_key)
567
568        .. versionadded:: 1.1
569
570        Performs a key exchange operation using the provided algorithm with
571        the peer's public key.
572
573        For most applications the ``shared_key`` should be passed to a key
574        derivation function. This allows mixing of additional information into the
575        key, derivation of multiple keys, and destroys any structure that may be
576        present.
577
578        :param algorithm: The key exchange algorithm, currently only
579            :class:`~cryptography.hazmat.primitives.asymmetric.ec.ECDH` is
580            supported.
581        :param EllipticCurvePublicKey peer_public_key: The public key for the
582            peer.
583
584        :returns bytes: A shared key.
585
586    .. method:: public_key()
587
588        :return: :class:`EllipticCurvePublicKey`
589
590        The EllipticCurvePublicKey object for this private key.
591
592    .. method:: sign(data, signature_algorithm)
593
594        .. versionadded:: 1.5
595
596        Sign one block of data which can be verified later by others using the
597        public key.
598
599        :param bytes data: The message string to sign.
600
601        :param signature_algorithm: An instance of
602            :class:`EllipticCurveSignatureAlgorithm`, such as :class:`ECDSA`.
603
604        :return bytes: Signature.
605
606    .. attribute:: key_size
607
608        .. versionadded:: 1.9
609
610        :type: int
611
612        Size (in :term:`bits`) of a secret scalar for the curve (as generated
613        by :func:`generate_private_key`).
614
615
616.. class:: EllipticCurvePrivateKeyWithSerialization
617
618    .. versionadded:: 0.8
619
620    This interface contains additional methods relating to serialization.
621    Any object with this interface also has all the methods from
622    :class:`EllipticCurvePrivateKey`.
623
624    .. method:: private_numbers()
625
626        Create a :class:`EllipticCurvePrivateNumbers` object.
627
628        :returns: An :class:`EllipticCurvePrivateNumbers` instance.
629
630    .. method:: private_bytes(encoding, format, encryption_algorithm)
631
632        Allows serialization of the key to bytes. Encoding (
633        :attr:`~cryptography.hazmat.primitives.serialization.Encoding.PEM` or
634        :attr:`~cryptography.hazmat.primitives.serialization.Encoding.DER`),
635        format (
636        :attr:`~cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL`
637        or
638        :attr:`~cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8`)
639        and encryption algorithm (such as
640        :class:`~cryptography.hazmat.primitives.serialization.BestAvailableEncryption`
641        or :class:`~cryptography.hazmat.primitives.serialization.NoEncryption`)
642        are chosen to define the exact serialization.
643
644        :param encoding: A value from the
645            :class:`~cryptography.hazmat.primitives.serialization.Encoding` enum.
646
647        :param format: A value from the
648            :class:`~cryptography.hazmat.primitives.serialization.PrivateFormat` enum.
649
650        :param encryption_algorithm: An instance of an object conforming to the
651            :class:`~cryptography.hazmat.primitives.serialization.KeySerializationEncryption`
652            interface.
653
654        :return bytes: Serialized key.
655
656
657.. class:: EllipticCurvePublicKey
658
659    .. versionadded:: 0.5
660
661    An elliptic curve public key.
662
663     .. attribute:: curve
664
665        :type: :class:`EllipticCurve`
666
667        The elliptic curve for this key.
668
669    .. method:: public_numbers()
670
671        Create a :class:`EllipticCurvePublicNumbers` object.
672
673        :returns: An :class:`EllipticCurvePublicNumbers` instance.
674
675    .. method:: public_bytes(encoding, format)
676
677        Allows serialization of the key data to bytes. When encoding the public
678        key the encodings (
679        :attr:`~cryptography.hazmat.primitives.serialization.Encoding.PEM`,
680        :attr:`~cryptography.hazmat.primitives.serialization.Encoding.DER`) and
681        format (
682        :attr:`~cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo`)
683        are chosen to define the exact serialization. When encoding the point
684        the encoding
685        :attr:`~cryptography.hazmat.primitives.serialization.Encoding.X962`
686        should be used with the formats (
687        :attr:`~cryptography.hazmat.primitives.serialization.PublicFormat.UncompressedPoint`
688        or
689        :attr:`~cryptography.hazmat.primitives.serialization.PublicFormat.CompressedPoint`
690        ).
691
692        :param encoding: A value from the
693            :class:`~cryptography.hazmat.primitives.serialization.Encoding` enum.
694
695        :param format: A value from the
696            :class:`~cryptography.hazmat.primitives.serialization.PublicFormat` enum.
697
698        :return bytes: Serialized data.
699
700    .. method:: verify(signature, data, signature_algorithm)
701
702        .. versionadded:: 1.5
703
704        Verify one block of data was signed by the private key associated
705        with this public key.
706
707        :param bytes signature: The signature to verify.
708
709        :param bytes data: The message string that was signed.
710
711        :param signature_algorithm: An instance of
712            :class:`EllipticCurveSignatureAlgorithm`.
713
714        :raises cryptography.exceptions.InvalidSignature: If the signature does
715            not validate.
716
717    .. attribute:: key_size
718
719        .. versionadded:: 1.9
720
721        :type: int
722
723        Size (in :term:`bits`) of a secret scalar for the curve (as generated
724        by :func:`generate_private_key`).
725
726    .. classmethod:: from_encoded_point(curve, data)
727
728        .. versionadded:: 2.5
729
730        Decodes a byte string as described in `SEC 1 v2.0`_ section 2.3.3 and
731        returns an :class:`EllipticCurvePublicKey`. This class method supports
732        compressed points.
733
734        :param curve: An
735            :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve`
736            instance.
737
738        :param bytes data: The serialized point byte string.
739
740        :returns: An :class:`EllipticCurvePublicKey` instance.
741
742        :raises ValueError: Raised when an invalid point is supplied.
743
744        :raises TypeError: Raised when curve is not an
745            :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve`.
746
747
748.. class:: EllipticCurvePublicKeyWithSerialization
749
750    .. versionadded:: 0.6
751
752    Alias for :class:`EllipticCurvePublicKey`.
753
754
755
756Serialization
757~~~~~~~~~~~~~
758
759This sample demonstrates how to generate a private key and serialize it.
760
761
762.. doctest::
763
764    >>> from cryptography.hazmat.backends import default_backend
765    >>> from cryptography.hazmat.primitives import hashes
766    >>> from cryptography.hazmat.primitives.asymmetric import ec
767    >>> from cryptography.hazmat.primitives import serialization
768
769    >>> private_key = ec.generate_private_key(ec.SECP384R1(), default_backend())
770
771    >>> serialized_private = private_key.private_bytes(
772    ...     encoding=serialization.Encoding.PEM,
773    ...     format=serialization.PrivateFormat.PKCS8,
774    ...     encryption_algorithm=serialization.BestAvailableEncryption(b'testpassword')
775    ... )
776    >>> serialized_private.splitlines()[0]
777    b'-----BEGIN ENCRYPTED PRIVATE KEY-----'
778
779You can also serialize the key without a password, by relying on
780:class:`~cryptography.hazmat.primitives.serialization.NoEncryption`.
781
782The public key is serialized as follows:
783
784
785.. doctest::
786
787    >>> public_key = private_key.public_key()
788    >>> serialized_public = public_key.public_bytes(
789    ...     encoding=serialization.Encoding.PEM,
790    ...     format=serialization.PublicFormat.SubjectPublicKeyInfo
791    ... )
792    >>> serialized_public.splitlines()[0]
793    b'-----BEGIN PUBLIC KEY-----'
794
795This is the part that you would normally share with the rest of the world.
796
797
798Key loading
799~~~~~~~~~~~
800
801This extends the sample in the previous section, assuming that the variables
802``serialized_private`` and ``serialized_public`` contain the respective keys
803in PEM format.
804
805.. doctest::
806
807    >>> loaded_public_key = serialization.load_pem_public_key(
808    ...     serialized_public,
809    ...     backend=default_backend()
810    ... )
811
812    >>> loaded_private_key = serialization.load_pem_private_key(
813    ...     serialized_private,
814    ...     # or password=None, if in plain text
815    ...     password=b'testpassword',
816    ...     backend=default_backend()
817    ... )
818
819
820Elliptic Curve Object Identifiers
821~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822
823.. class:: EllipticCurveOID
824
825    .. versionadded:: 2.4
826
827    .. attribute:: SECP192R1
828
829        Corresponds to the dotted string ``"1.2.840.10045.3.1.1"``.
830
831    .. attribute:: SECP224R1
832
833        Corresponds to the dotted string ``"1.3.132.0.33"``.
834
835    .. attribute:: SECP256K1
836
837        Corresponds to the dotted string ``"1.3.132.0.10"``.
838
839    .. attribute:: SECP256R1
840
841        Corresponds to the dotted string ``"1.2.840.10045.3.1.7"``.
842
843    .. attribute:: SECP384R1
844
845        Corresponds to the dotted string ``"1.3.132.0.34"``.
846
847    .. attribute:: SECP521R1
848
849        Corresponds to the dotted string ``"1.3.132.0.35"``.
850
851    .. attribute:: BRAINPOOLP256R1
852
853        .. versionadded:: 2.5
854
855        Corresponds to the dotted string ``"1.3.36.3.3.2.8.1.1.7"``.
856
857    .. attribute:: BRAINPOOLP384R1
858
859        .. versionadded:: 2.5
860
861        Corresponds to the dotted string ``"1.3.36.3.3.2.8.1.1.11"``.
862
863    .. attribute:: BRAINPOOLP512R1
864
865        .. versionadded:: 2.5
866
867        Corresponds to the dotted string ``"1.3.36.3.3.2.8.1.1.13"``.
868
869    .. attribute:: SECT163K1
870
871        .. versionadded:: 2.5
872
873        Corresponds to the dotted string ``"1.3.132.0.1"``.
874
875    .. attribute:: SECT163R2
876
877        .. versionadded:: 2.5
878
879        Corresponds to the dotted string ``"1.3.132.0.15"``.
880
881    .. attribute:: SECT233K1
882
883        .. versionadded:: 2.5
884
885        Corresponds to the dotted string ``"1.3.132.0.26"``.
886
887    .. attribute:: SECT233R1
888
889        .. versionadded:: 2.5
890
891        Corresponds to the dotted string ``"1.3.132.0.27"``.
892
893    .. attribute:: SECT283K1
894
895        .. versionadded:: 2.5
896
897        Corresponds to the dotted string ``"1.3.132.0.16"``.
898
899    .. attribute:: SECT283R1
900
901        .. versionadded:: 2.5
902
903        Corresponds to the dotted string ``"1.3.132.0.17"``.
904
905    .. attribute:: SECT409K1
906
907        .. versionadded:: 2.5
908
909        Corresponds to the dotted string ``"1.3.132.0.36"``.
910
911    .. attribute:: SECT409R1
912
913        .. versionadded:: 2.5
914
915        Corresponds to the dotted string ``"1.3.132.0.37"``.
916
917    .. attribute:: SECT571K1
918
919        .. versionadded:: 2.5
920
921        Corresponds to the dotted string ``"1.3.132.0.38"``.
922
923    .. attribute:: SECT571R1
924
925        .. versionadded:: 2.5
926
927        Corresponds to the dotted string ``"1.3.132.0.39"``.
928
929
930.. _`FIPS 186-3`: https://csrc.nist.gov/csrc/media/publications/fips/186/3/archive/2009-06-25/documents/fips_186-3.pdf
931.. _`FIPS 186-4`: https://csrc.nist.gov/publications/detail/fips/186/4/final
932.. _`800-56A`: https://csrc.nist.gov/publications/detail/sp/800-56a/revised/archive/2007-03-14
933.. _`800-56Ar2`: https://csrc.nist.gov/publications/detail/sp/800-56a/rev-2/final
934.. _`some concern`: https://crypto.stackexchange.com/questions/10263/should-we-trust-the-nist-recommended-ecc-parameters
935.. _`less than 224 bits`: https://www.cosic.esat.kuleuven.be/ecrypt/ecrypt2/documents/D.SPA.20.pdf
936.. _`elliptic curve diffie-hellman is faster than diffie-hellman`: https://digitalcommons.unl.edu/cgi/viewcontent.cgi?article=1100&context=cseconfwork
937.. _`minimize the number of security concerns for elliptic-curve cryptography`: https://cr.yp.to/ecdh/curve25519-20060209.pdf
938.. _`SafeCurves`: https://safecurves.cr.yp.to/
939.. _`ECDSA`: https://en.wikipedia.org/wiki/ECDSA
940.. _`EdDSA`: https://en.wikipedia.org/wiki/EdDSA
941.. _`forward secrecy`: https://en.wikipedia.org/wiki/Forward_secrecy
942.. _`SEC 1 v2.0`: http://www.secg.org/sec1-v2.pdf
943