1JOSEPY(1) josepy JOSEPY(1)
2
3
4
6 josepy - josepy Documentation
7
8 Javascript Object Signing and Encryption (JOSE).
9
10 This package is a Python implementation of the standards developed by
11 IETF Javascript Object Signing and Encryption (Active WG), in particu‐
12 lar the following RFCs:
13
14 • JSON Web Algorithms (JWA)
15
16 • JSON Web Key (JWK)
17
18 • JSON Web Signature (JWS)
19
20 Originally developed as part of the ACME protocol implementation.
21
23 JOSE Base64 is defined as:
24
25 • URL-safe Base64
26
27 • padding stripped
28
29 josepy.b64.b64encode(data: bytes) -> bytes
30 JOSE Base64 encode.
31
32 Parameters
33 data (bytes) -- Data to be encoded.
34
35 Returns
36 JOSE Base64 string.
37
38 Return type
39 bytes
40
41 Raises TypeError -- if data is of incorrect type
42
43 josepy.b64.b64decode(data: bytes | str) -> bytes
44 JOSE Base64 decode.
45
46 Parameters
47 data (bytes or unicode) -- Base64 string to be decoded.
48 If it's unicode, then only ASCII characters are allowed.
49
50 Returns
51 Decoded data.
52
53 Return type
54 bytes
55
56 Raises
57
58 • TypeError -- if input is of incorrect type
59
60 • ValueError -- if input is unicode with non-ASCII char‐
61 acters
62
64 JOSE errors.
65
66 exception josepy.errors.Error
67 Generic JOSE Error.
68
69 exception josepy.errors.DeserializationError
70 JSON deserialization error.
71
72 exception josepy.errors.SerializationError
73 JSON serialization error.
74
75 exception josepy.errors.UnrecognizedTypeError(typ: str, jobj: Any)
76 Unrecognized type error.
77
78 Variables
79
80 • typ (str) -- The unrecognized type of the JSON object.
81
82 • jobj -- Full JSON object.
83
85 JOSE interfaces.
86
87 class josepy.interfaces.JSONDeSerializable
88 Interface for (de)serializable JSON objects.
89
90 Please recall, that standard Python library implements json.JSO‐
91 NEncoder and json.JSONDecoder that perform translations based on
92 respective conversion tables that look pretty much like the one
93 below (for complete tables see relevant Python documentation):
94
95 ┌───────┬────────┐
96 │JSON │ Python │
97 ├───────┼────────┤
98 │object │ dict │
99 ├───────┼────────┤
100 │... │ ... │
101 └───────┴────────┘
102
103 While the above conversion table is about translation of JSON
104 documents to/from the basic Python types only,
105 JSONDeSerializable introduces the following two concepts:
106
107 serialization
108 Turning an arbitrary Python object into Python object
109 that can be encoded into a JSON document. Full serial‐
110 ization produces a Python object composed of only ba‐
111 sic types as required by the conversion table. Partial
112 serialization (accomplished by to_partial_json()) pro‐
113 duces a Python object that might also be built from
114 other JSONDeSerializable objects.
115
116 deserialization
117 Turning a decoded Python object (necessarily one of
118 the basic types as required by the conversion table)
119 into an arbitrary Python object.
120
121 Serialization produces serialized object ("partially serialized
122 object" or "fully serialized object" for partial and full seri‐
123 alization respectively) and deserialization produces deserial‐
124 ized object, both usually denoted in the source code as jobj.
125
126 Wording in the official Python documentation might be confusing
127 after reading the above, but in the light of those definitions,
128 one can view json.JSONDecoder.decode() as decoder and deserial‐
129 izer of basic types, json.JSONEncoder.default() as serializer of
130 basic types, json.JSONEncoder.encode() as serializer and en‐
131 coder of basic types.
132
133 One could extend json to support arbitrary object (de)serializa‐
134 tion either by:
135
136 • overriding json.JSONDecoder.decode() and json.JSONEn‐
137 coder.default() in subclasses
138
139 • or passing object_hook argument (or object_hook_pairs) to
140 json.load()/json.loads() or default argument for
141 json.dump()/json.dumps().
142
143 Interestingly, default is required to perform only partial seri‐
144 alization, as json.dumps() applies default recursively. This is
145 the idea behind making to_partial_json() produce only partial
146 serialization, while providing custom json_dumps() that dumps
147 with default set to json_dump_default().
148
149 To make further documentation a bit more concrete, please, con‐
150 sider the following imaginatory implementation example:
151
152 class Foo(JSONDeSerializable):
153 def to_partial_json(self):
154 return 'foo'
155
156 @classmethod
157 def from_json(cls, jobj):
158 return Foo()
159
160 class Bar(JSONDeSerializable):
161 def to_partial_json(self):
162 return [Foo(), Foo()]
163
164 @classmethod
165 def from_json(cls, jobj):
166 return Bar()
167
168 abstract to_partial_json() -> Any
169 Partially serialize.
170
171 Following the example, partial serialization means the
172 following:
173
174 assert isinstance(Bar().to_partial_json()[0], Foo)
175 assert isinstance(Bar().to_partial_json()[1], Foo)
176
177 # in particular...
178 assert Bar().to_partial_json() != ['foo', 'foo']
179
180 Raises josepy.errors.SerializationError -- in case of any
181 serialization error.
182
183 Returns
184 Partially serializable object.
185
186 to_json() -> Any
187 Fully serialize.
188
189 Again, following the example from before, full serializa‐
190 tion means the following:
191
192 assert Bar().to_json() == ['foo', 'foo']
193
194 Raises josepy.errors.SerializationError -- in case of any
195 serialization error.
196
197 Returns
198 Fully serialized object.
199
200 abstract classmethod from_json(jobj: Any) -> GenericJSONDeSeri‐
201 alizable
202 Deserialize a decoded JSON document.
203
204 Parameters
205 jobj -- Python object, composed of only other ba‐
206 sic data types, as decoded from JSON document. Not
207 necessarily dict (as decoded from "JSON object"
208 document).
209
210 Raises josepy.errors.DeserializationError -- if decoding
211 was unsuccessful, e.g. in case of unparseable X509
212 certificate, or wrong padding in JOSE base64 en‐
213 coded string, etc.
214
215 classmethod json_loads(json_string: str | bytes) -> GenericJSON‐
216 DeSerializable
217 Deserialize from JSON document string.
218
219 json_dumps(**kwargs: Any) -> str
220 Dump to JSON string using proper serializer.
221
222 Returns
223 JSON document string.
224
225 Return type
226 str
227
228 json_dumps_pretty() -> str
229 Dump the object to pretty JSON document string.
230
231 Return type
232 str
233
234 classmethod json_dump_default(python_object: JSONDeSerializable)
235 -> Any
236 Serialize Python object.
237
238 This function is meant to be passed as default to
239 json.dump() or json.dumps(). They call default(python_ob‐
240 ject) only for non-basic Python types, so this function
241 necessarily raises TypeError if python_object is not an
242 instance of IJSONSerializable.
243
244 Please read the class docstring for more information.
245
247 JSON (de)serialization framework.
248
249 The framework presented here is somewhat based on Go's "json" package
250 (especially the omitempty functionality).
251
252 josepy.json_util.field(json_name: str, default: Any = None, omitempty:
253 bool = False, decoder: Callable[[Any], Any] = None, encoder:
254 Callable[[Any], Any] = None) -> Any
255 Convenient function to declare a Field with proper type annota‐
256 tions.
257
258 This function allows to write the following code:
259
260 import josepy class JSON(josepy.JSONObjectWithFields):
261 typ: str = josepy.field('type')
262
263 def other_type(self) -> str:
264 return self.typ
265
266 class josepy.json_util.Field(json_name: str, default: Any = None,
267 omitempty: bool = False, decoder: Callable[[Any], Any] = None, encoder:
268 Callable[[Any], Any] = None)
269 JSON object field.
270
271 Field is meant to be used together with JSONObjectWithFields.
272
273 encoder (decoder) is a callable that accepts a single parameter,
274 i.e. a value to be encoded (decoded), and returns the serialized
275 (deserialized) value. In case of errors it should raise
276 SerializationError (DeserializationError).
277
278 Note, that decoder should perform partial serialization only.
279
280 Variables
281
282 • json_name (str) -- Name of the field when encoded to
283 JSON.
284
285 • default -- Default value (used when not present in JSON
286 object).
287
288 • omitempty (bool) -- If True and the field value is
289 empty, then it will not be included in the serialized
290 JSON object, and default will be used for deserializa‐
291 tion. Otherwise, if False, field is considered as re‐
292 quired, value will always be included in the serialized
293 JSON objected, and it must also be present when deseri‐
294 alizing.
295
296 omit(value: Any) -> bool
297 Omit the value in output?
298
299 decoder(fdec: Callable[[Any], Any]) -> Field
300 Descriptor to change the decoder on JSON object field.
301
302 encoder(fenc: Callable[[Any], Any]) -> Field
303 Descriptor to change the encoder on JSON object field.
304
305 decode(value: Any) -> Any
306 Decode a value, optionally with context JSON object.
307
308 encode(value: Any) -> Any
309 Encode a value, optionally with context JSON object.
310
311 classmethod default_decoder(value: Any) -> Any
312 Default decoder.
313
314 Recursively deserialize into immutable types (
315 josepy.util.frozendict instead of dict(), tuple() instead
316 of list()).
317
318 classmethod default_encoder(value: Any) -> Any
319 Default (passthrough) encoder.
320
321 class josepy.json_util.JSONObjectWithFieldsMeta(name: str, bases:
322 List[str], namespace: Dict[str, Any])
323 Metaclass for JSONObjectWithFields and its subclasses.
324
325 It makes sure that, for any class cls with __metaclass__ set to
326 JSONObjectWithFieldsMeta:
327
328 1. All fields (attributes of type Field) in the class definition
329 are moved to the cls._fields dictionary, where keys are field
330 attribute names and values are fields themselves.
331
332 2. cls.__slots__ is extended by all field attribute names (i.e.
333 not Field.json_name). Original cls.__slots__ are stored in
334 cls._orig_slots.
335
336 In a consequence, for a field attribute name some_field,
337 cls.some_field will be a slot descriptor and not an instance of
338 Field. For example:
339
340 some_field = Field('someField', default=())
341
342 class Foo:
343 __metaclass__ = JSONObjectWithFieldsMeta
344 __slots__ = ('baz',)
345 some_field = some_field
346
347 assert Foo.__slots__ == ('some_field', 'baz')
348 assert Foo._orig_slots == ()
349 assert Foo.some_field is not Field
350
351 assert Foo._fields.keys() == ['some_field']
352 assert Foo._fields['some_field'] is some_field
353
354 As an implementation note, this metaclass inherits from
355 abc.ABCMeta (and not the usual type) to mitigate the metaclass
356 conflict (ImmutableMap and JSONDeSerializable, parents of
357 JSONObjectWithFields, use abc.ABCMeta as its metaclass).
358
359 class josepy.json_util.JSONObjectWithFields(**kwargs: Any)
360 JSON object with fields.
361
362 Example:
363
364 class Foo(JSONObjectWithFields):
365 bar = Field('Bar')
366 empty = Field('Empty', omitempty=True)
367
368 @bar.encoder
369 def bar(value):
370 return value + 'bar'
371
372 @bar.decoder
373 def bar(value):
374 if not value.endswith('bar'):
375 raise errors.DeserializationError('No bar suffix!')
376 return value[:-3]
377
378 assert Foo(bar='baz').to_partial_json() == {'Bar': 'bazbar'}
379 assert Foo.from_json({'Bar': 'bazbar'}) == Foo(bar='baz')
380 assert (Foo.from_json({'Bar': 'bazbar', 'Empty': '!'})
381 == Foo(bar='baz', empty='!'))
382 assert Foo(bar='baz').bar == 'baz'
383
384 encode(name: str) -> Any
385 Encode a single field.
386
387 Parameters
388 name (str) -- Name of the field to be encoded.
389
390 Raises
391
392 • errors.SerializationError -- if field cannot be
393 serialized
394
395 • errors.Error -- if field could not be found
396
397 fields_to_partial_json() -> Dict[str, Any]
398 Serialize fields to JSON.
399
400 to_partial_json() -> Dict[str, Any]
401 Partially serialize.
402
403 Following the example, partial serialization means the
404 following:
405
406 assert isinstance(Bar().to_partial_json()[0], Foo)
407 assert isinstance(Bar().to_partial_json()[1], Foo)
408
409 # in particular...
410 assert Bar().to_partial_json() != ['foo', 'foo']
411
412 Raises josepy.errors.SerializationError -- in case of any
413 serialization error.
414
415 Returns
416 Partially serializable object.
417
418 classmethod fields_from_json(jobj: Mapping[str, Any]) -> Any
419 Deserialize fields from JSON.
420
421 classmethod from_json(jobj: Mapping[str, Any]) -> GenericJSONOb‐
422 jectWithFields
423 Deserialize a decoded JSON document.
424
425 Parameters
426 jobj -- Python object, composed of only other ba‐
427 sic data types, as decoded from JSON document. Not
428 necessarily dict (as decoded from "JSON object"
429 document).
430
431 Raises josepy.errors.DeserializationError -- if decoding
432 was unsuccessful, e.g. in case of unparseable X509
433 certificate, or wrong padding in JOSE base64 en‐
434 coded string, etc.
435
436 josepy.json_util.encode_b64jose(data: bytes) -> str
437 Encode JOSE Base-64 field.
438
439 Parameters
440 data (bytes) --
441
442 Return type
443 str
444
445 josepy.json_util.decode_b64jose(data: str, size: int | None = None,
446 minimum: bool = False) -> bytes
447 Decode JOSE Base-64 field.
448
449 Parameters
450
451 • data (unicode) --
452
453 • size (int) -- Required length (after decoding).
454
455 • minimum (bool) -- If True, then size will be treated as
456 minimum required length, as opposed to exact equality.
457
458 Return type
459 bytes
460
461 josepy.json_util.encode_hex16(value: bytes) -> str
462 Hexlify.
463
464 Parameters
465 value (bytes) --
466
467 Return type
468 unicode
469
470 josepy.json_util.decode_hex16(value: str, size: int | None = None, min‐
471 imum: bool = False) -> bytes
472 Decode hexlified field.
473
474 Parameters
475
476 • value (unicode) --
477
478 • size (int) -- Required length (after decoding).
479
480 • minimum (bool) -- If True, then size will be treated as
481 minimum required length, as opposed to exact equality.
482
483 Return type
484 bytes
485
486 josepy.json_util.encode_cert(cert: ComparableX509) -> str
487 Encode certificate as JOSE Base-64 DER.
488
489 Return type
490 unicode
491
492 josepy.json_util.decode_cert(b64der: str) -> ComparableX509
493 Decode JOSE Base-64 DER-encoded certificate.
494
495 Parameters
496 b64der (unicode) --
497
498 Return type
499 OpenSSL.crypto.X509 wrapped in ComparableX509
500
501 josepy.json_util.encode_csr(csr: ComparableX509) -> str
502 Encode CSR as JOSE Base-64 DER.
503
504 Return type
505 unicode
506
507 josepy.json_util.decode_csr(b64der: str) -> ComparableX509
508 Decode JOSE Base-64 DER-encoded CSR.
509
510 Parameters
511 b64der (unicode) --
512
513 Return type
514 OpenSSL.crypto.X509Req wrapped in ComparableX509
515
516 class josepy.json_util.TypedJSONObjectWithFields(**kwargs: Any)
517 JSON object with type.
518
519 typ: str = NotImplemented
520 Type of the object. Subclasses must override.
521
522 type_field_name: str = 'type'
523 Field name used to distinguish different object types.
524
525 Subclasses will probably have to override this.
526
527 TYPES: Dict[str, Type] = NotImplemented
528 Types registered for JSON deserialization
529
530 classmethod register(type_cls: Type[GenericTypedJSONObjectWith‐
531 Fields], typ: str | None = None) -> Type[GenericTypedJSONOb‐
532 jectWithFields]
533 Register class for JSON deserialization.
534
535 classmethod get_type_cls(jobj: Mapping[str, Any]) -> Type[‐
536 TypedJSONObjectWithFields]
537 Get the registered class for jobj.
538
539 to_partial_json() -> Dict[str, Any]
540 Get JSON serializable object.
541
542 Returns
543 Serializable JSON object representing ACME typed
544 object. validate() will almost certainly not
545 work, due to reasons explained in josepy.inter‐
546 faces.IJSONSerializable.
547
548 Return type
549 dict
550
551 classmethod from_json(jobj: Mapping[str, Any]) ->
552 TypedJSONObjectWithFields
553 Deserialize ACME object from valid JSON object.
554
555 Raises josepy.errors.UnrecognizedTypeError -- if type of
556 the ACME object has not been registered.
557
559 JSON Web Algorithms.
560
561 https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
562
563 class josepy.jwa.JWA
564 JSON Web Algorithm.
565
566 class josepy.jwa.JWASignature(name: str)
567 Base class for JSON Web Signature Algorithms.
568
569 classmethod register(signature_cls: JWASignature) ->
570 JWASignature
571 Register class for JSON deserialization.
572
573 to_partial_json() -> Any
574 Partially serialize.
575
576 Following the example, partial serialization means the
577 following:
578
579 assert isinstance(Bar().to_partial_json()[0], Foo)
580 assert isinstance(Bar().to_partial_json()[1], Foo)
581
582 # in particular...
583 assert Bar().to_partial_json() != ['foo', 'foo']
584
585 Raises josepy.errors.SerializationError -- in case of any
586 serialization error.
587
588 Returns
589 Partially serializable object.
590
591 classmethod from_json(jobj: Any) -> JWASignature
592 Deserialize a decoded JSON document.
593
594 Parameters
595 jobj -- Python object, composed of only other ba‐
596 sic data types, as decoded from JSON document. Not
597 necessarily dict (as decoded from "JSON object"
598 document).
599
600 Raises josepy.errors.DeserializationError -- if decoding
601 was unsuccessful, e.g. in case of unparseable X509
602 certificate, or wrong padding in JOSE base64 en‐
603 coded string, etc.
604
605 abstract sign(key: Any, msg: bytes) -> bytes
606 Sign the msg using key.
607
608 abstract verify(key: Any, msg: bytes, sig: bytes) -> bool
609 Verify the msg and sig using key.
610
611 josepy.jwa.HS256 = HS256
612 HMAC using SHA-256
613
614 josepy.jwa.HS384 = HS384
615 HMAC using SHA-384
616
617 josepy.jwa.HS512 = HS512
618 HMAC using SHA-512
619
620 josepy.jwa.RS256 = RS256
621 RSASSA-PKCS-v1_5 using SHA-256
622
623 josepy.jwa.RS384 = RS384
624 RSASSA-PKCS-v1_5 using SHA-384
625
626 josepy.jwa.RS512 = RS512
627 RSASSA-PKCS-v1_5 using SHA-512
628
629 josepy.jwa.PS256 = PS256
630 RSASSA-PSS using SHA-256 and MGF1 with SHA-256
631
632 josepy.jwa.PS384 = PS384
633 RSASSA-PSS using SHA-384 and MGF1 with SHA-384
634
635 josepy.jwa.PS512 = PS512
636 RSASSA-PSS using SHA-512 and MGF1 with SHA-512
637
638 josepy.jwa.ES256 = ES256
639 ECDSA using P-256 and SHA-256
640
641 josepy.jwa.ES384 = ES384
642 ECDSA using P-384 and SHA-384
643
644 josepy.jwa.ES512 = ES512
645 ECDSA using P-521 and SHA-512
646
648 JSON Web Key.
649
650 class josepy.jwk.JWK(**kwargs: Any)
651 JSON Web Key.
652
653 type_field_name: str = 'kty'
654 Field name used to distinguish different object types.
655
656 Subclasses will probably have to override this.
657
658 TYPES: Dict[str, Type[JWK]] = {'EC': <class 'josepy.jwk.JWKEC'>,
659 'RSA': <class 'josepy.jwk.JWKRSA'>, 'oct': <class
660 'josepy.jwk.JWKOct'>}
661 Types registered for JSON deserialization
662
663 cryptography_key_types: Tuple[Type[Any], ...] = ()
664 Subclasses should override.
665
666 required: Sequence[str] = NotImplemented
667 Required members of public key's representation as de‐
668 fined by JWK/JWA.
669
670 thumbprint(hash_function: ~typing.Callable[[], ~cryptogra‐
671 phy.hazmat.primitives.hashes.HashAlgorithm] = <class 'cryptogra‐
672 phy.hazmat.primitives.hashes.SHA256'>) -> bytes
673 Compute JWK Thumbprint.
674
675 https://tools.ietf.org/html/rfc7638
676
677 Returns
678 bytes
679
680 abstract public_key() -> JWK
681 Generate JWK with public key.
682
683 For symmetric cryptosystems, this would return self.
684
685 classmethod load(data: bytes, password: bytes | None = None,
686 backend: Any | None = None) -> JWK
687 Load serialized key as JWK.
688
689 Parameters
690
691 • data (str) -- Public or private key serialized
692 as PEM or DER.
693
694 • password (str) -- Optional password.
695
696 • backend -- A PEMSerializationBackend and DERSe‐
697 rializationBackend provider.
698
699 Raises errors.Error -- if unable to deserialize, or un‐
700 supported JWK algorithm
701
702 Returns
703 JWK of an appropriate type.
704
705 Return type
706 JWK
707
708 class josepy.jwk.JWKOct(**kwargs: Any)
709 Symmetric JWK.
710
711 typ: str = 'oct'
712 Type of the object. Subclasses must override.
713
714 required: Sequence[str] = ('k', 'kty')
715 Required members of public key's representation as de‐
716 fined by JWK/JWA.
717
718 fields_to_partial_json() -> Dict[str, str]
719 Serialize fields to JSON.
720
721 classmethod fields_from_json(jobj: Mapping[str, Any]) -> JWKOct
722 Deserialize fields from JSON.
723
724 public_key() -> JWKOct
725 Generate JWK with public key.
726
727 For symmetric cryptosystems, this would return self.
728
729 class josepy.jwk.JWKRSA(*args: Any, **kwargs: Any)
730 RSA JWK.
731
732 Variables
733 key -- RSAPrivateKey or RSAPublicKey wrapped in
734 ComparableRSAKey
735
736 typ: str = 'RSA'
737 Type of the object. Subclasses must override.
738
739 cryptography_key_types: Tuple[Type[Any], ...] = (<class 'cryp‐
740 tography.hazmat.primitives.asymmetric.rsa.RSAPublicKey'>, <class
741 'cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey'>)
742 Subclasses should override.
743
744 required: Sequence[str] = ('e', 'kty', 'n')
745 Required members of public key's representation as de‐
746 fined by JWK/JWA.
747
748 public_key() -> JWKRSA
749 Generate JWK with public key.
750
751 For symmetric cryptosystems, this would return self.
752
753 classmethod fields_from_json(jobj: Mapping[str, Any]) -> JWKRSA
754 Deserialize fields from JSON.
755
756 fields_to_partial_json() -> Dict[str, Any]
757 Serialize fields to JSON.
758
759 class josepy.jwk.JWKEC(*args: Any, **kwargs: Any)
760 EC JWK.
761
762 Variables
763 key -- EllipticCurvePrivateKey or EllipticCurvePublicKey
764 wrapped in ComparableECKey
765
766 typ: str = 'EC'
767 Type of the object. Subclasses must override.
768
769 cryptography_key_types: Tuple[Type[Any], ...] = (<class 'cryp‐
770 tography.hazmat.primitives.asymmetric.ec.EllipticCurvePub‐
771 licKey'>, <class 'cryptography.hazmat.primitives.asymmet‐
772 ric.ec.EllipticCurvePrivateKey'>)
773 Subclasses should override.
774
775 required: Sequence[str] = ('crv', 'kty', 'x', 'y')
776 Required members of public key's representation as de‐
777 fined by JWK/JWA.
778
779 fields_to_partial_json() -> Dict[str, Any]
780 Serialize fields to JSON.
781
782 classmethod fields_from_json(jobj: Mapping[str, Any]) -> JWKEC
783 Deserialize fields from JSON.
784
785 public_key() -> JWKEC
786 Generate JWK with public key.
787
788 For symmetric cryptosystems, this would return self.
789
791 JSON Web Signature.
792
793 class josepy.jws.MediaType
794 MediaType field encoder/decoder.
795
796 PREFIX = 'application/'
797 MIME Media Type and Content Type prefix.
798
799 classmethod decode(value: str) -> str
800 Decoder.
801
802 classmethod encode(value: str) -> str
803 Encoder.
804
805 class josepy.jws.Header(**kwargs: Any)
806 JOSE Header.
807
808 WARNING:
809 This class supports only Registered Header Parameter Names
810 (as defined in section 4.1 of the protocol). If you need Pub‐
811 lic Header Parameter Names (4.2) or Private Header Parameter
812 Names (4.3), you must subclass and override from_json() and
813 to_partial_json() appropriately.
814
815 WARNING:
816 This class does not support any extensions through the "crit"
817 (Critical) Header Parameter (4.1.11) and as a conforming im‐
818 plementation, from_json() treats its occurrence as an error.
819 Please subclass if you seek for a different behaviour.
820
821 Variables
822
823 • x5tS256 -- "x5t#S256"
824
825 • typ (str) -- MIME Media Type, inc. MediaType.PREFIX.
826
827 • cty (str) -- Content-Type, inc. MediaType.PREFIX.
828
829 not_omitted() -> Dict[str, Field]
830 Fields that would not be omitted in the JSON object.
831
832 find_key() -> JWK
833 Find key based on header.
834
836 Supports only "jwk" header parameter lookup.
837
838 Returns
839 (Public) key found in the header.
840
841 Return type
842 .JWK
843
844 Raises josepy.errors.Error -- if key could not be found
845
846 class josepy.jws.Signature(**kwargs: Any)
847 JWS Signature.
848
849 Variables
850
851 • combined -- Combined Header (protected and unprotected,
852 Header).
853
854 • protected (unicode) -- JWS protected header (Jose
855 Base-64 decoded).
856
857 • header -- JWS Unprotected Header (Header).
858
859 • signature (str) -- The signature.
860
861 header_cls
862 alias of Header
863
864 verify(payload: bytes, key: JWK | None = None) -> bool
865 Verify.
866
867 Parameters
868
869 • payload (bytes) -- Payload to verify.
870
871 • key (JWK) -- Key used for verification.
872
873 classmethod sign(payload: bytes, key: JWK, alg: JWASignature,
874 include_jwk: bool = True, protect: FrozenSet = frozenset({}),
875 **kwargs: Any) -> Signature
876 Sign.
877
878 Parameters
879
880 • payload (bytes) -- Payload to sign.
881
882 • key (JWK) -- Key for signature.
883
884 • alg (JWASignature) -- Signature algorithm to use
885 to sign.
886
887 • include_jwk (bool) -- If True, insert the JWK
888 inside the signature headers.
889
890 • protect (FrozenSet) -- List of headers to pro‐
891 tect.
892
893 fields_to_partial_json() -> Dict[str, Any]
894 Serialize fields to JSON.
895
896 classmethod fields_from_json(jobj: Mapping[str, Any]) ->
897 Dict[str, Any]
898 Deserialize fields from JSON.
899
900 class josepy.jws.JWS(**kwargs: Any)
901 JSON Web Signature.
902
903 Variables
904
905 • payload (str) -- JWS Payload.
906
907 • signature (str) -- JWS Signatures.
908
909 signature_cls
910 alias of Signature
911
912 verify(key: JWK | None = None) -> bool
913 Verify.
914
915 classmethod sign(payload: bytes, **kwargs: Any) -> JWS
916 Sign.
917
918 property signature: Signature
919 Get a singleton signature.
920
921 Return type
922 JWS.signature_cls
923
924 to_compact() -> bytes
925 Compact serialization.
926
927 Return type
928 bytes
929
930 classmethod from_compact(compact: bytes) -> JWS
931 Compact deserialization.
932
933 Parameters
934 compact (bytes) --
935
936 to_partial_json(flat: bool = True) -> Dict[str, Any]
937 Partially serialize.
938
939 Following the example, partial serialization means the
940 following:
941
942 assert isinstance(Bar().to_partial_json()[0], Foo)
943 assert isinstance(Bar().to_partial_json()[1], Foo)
944
945 # in particular...
946 assert Bar().to_partial_json() != ['foo', 'foo']
947
948 Raises josepy.errors.SerializationError -- in case of any
949 serialization error.
950
951 Returns
952 Partially serializable object.
953
954 classmethod from_json(jobj: Mapping[str, Any]) -> JWS
955 Deserialize a decoded JSON document.
956
957 Parameters
958 jobj -- Python object, composed of only other ba‐
959 sic data types, as decoded from JSON document. Not
960 necessarily dict (as decoded from "JSON object"
961 document).
962
963 Raises josepy.errors.DeserializationError -- if decoding
964 was unsuccessful, e.g. in case of unparseable X509
965 certificate, or wrong padding in JOSE base64 en‐
966 coded string, etc.
967
968 class josepy.jws.CLI
969 JWS CLI.
970
971 classmethod sign(args: Namespace) -> None
972 Sign.
973
974 classmethod verify(args: Namespace) -> bool
975 Verify.
976
977 classmethod run(args: List[str] = None) -> bool | None
978 Parse arguments and sign/verify.
979
981 Internal class delegating to a module, and displaying warnings when at‐
982 tributes related to the deprecated "abstractclassmethod" attributes in
983 the josepy.util module.
984
985 class josepy.util.ComparableX509(wrapped: X509 | X509Req)
986 Wrapper for OpenSSL.crypto.X509** objects that supports __eq__.
987
988 Variables
989 wrapped -- Wrapped certificate or certificate request.
990
991 class josepy.util.ComparableKey(wrapped: RSAPrivateKey | RSAPublicKey |
992 EllipticCurvePrivateKey | EllipticCurvePublicKey)
993 Comparable wrapper for cryptography keys.
994
995 See https://github.com/pyca/cryptography/issues/2122.
996
997 public_key() -> ComparableKey
998 Get wrapped public key.
999
1000 class josepy.util.ComparableRSAKey(wrapped: RSAPrivateKey | RSAPub‐
1001 licKey | EllipticCurvePrivateKey | EllipticCurvePublicKey)
1002 Wrapper for cryptography RSA keys.
1003
1004 Wraps around:
1005
1006 • RSAPrivateKey
1007
1008 • RSAPublicKey
1009
1010 class josepy.util.ComparableECKey(wrapped: RSAPrivateKey | RSAPublicKey
1011 | EllipticCurvePrivateKey | EllipticCurvePublicKey)
1012 Wrapper for cryptography RSA keys. Wraps around: - Elliptic‐
1013 CurvePrivateKey - EllipticCurvePublicKey
1014
1015 class josepy.util.ImmutableMap(**kwargs: Any)
1016 Immutable key to value mapping with attribute access.
1017
1018 update(**kwargs: Any) -> GenericImmutableMap
1019 Return updated map.
1020
1021 class josepy.util.frozendict(*args: Any, **kwargs: Any)
1022 Frozen dictionary.
1023
1025 1.13.0 (2022-03-10)
1026 • Support for Python 3.6 has been deprecated and will be removed in the
1027 next scheduled release.
1028
1029 • Corrected some type annotations.
1030
1031 1.12.0 (2022-01-11)
1032 • Corrected some type annotations.
1033
1034 • Dropped support for cryptography<1.5.
1035
1036 • Added the top level attributes josepy.JWKEC, josepy.JWKOct, and
1037 josepy.ComparableECKey for convenience and consistency.
1038
1039 1.11.0 (2021-11-17)
1040 • Added support for Python 3.10.
1041
1042 • We changed the PGP key used to sign the packages we upload to PyPI.
1043 Going forward, releases will be signed with one of three different
1044 keys. All of these keys are available on major key servers and signed
1045 by our previous PGP key. The fingerprints of these new keys are:
1046
1047 • BF6BCFC89E90747B9A680FD7B6029E8500F7DB16
1048
1049 • 86379B4F0AF371B50CD9E5FF3402831161D1D280
1050
1051 • 20F201346BF8F3F455A73F9A780CC99432A28621
1052
1053 1.10.0 (2021-09-27)
1054 • josepy is now compliant with PEP-561: type checkers will fetch types
1055 from the inline types annotations when josepy is installed as a de‐
1056 pendency in a Python project.
1057
1058 • Added a field function to assist in adding type annotations for
1059 Fields in classes. If the field function is used to define a Field
1060 in a JSONObjectWithFields based class without a type annotation, an
1061 error will be raised.
1062
1063 • josepy's tests can no longer be imported under the name josepy, how‐
1064 ever, they are still included in the package and you can run them by
1065 installing josepy with "tests" extras and running python -m pytest.
1066
1067 1.9.0 (2021-09-09)
1068 • Removed pytest-cache testing dependency.
1069
1070 • Fixed a bug that sometimes caused incorrect padding to be used when
1071 serializing Elliptic Curve keys as JSON Web Keys.
1072
1073 1.8.0 (2021-03-15)
1074 • Removed external mock dependency.
1075
1076 • Removed dependency on six.
1077
1078 • Deprecated the module josepy.magic_typing.
1079
1080 • Fix JWS/JWK generation with EC keys when keys or signatures have
1081 leading zeros.
1082
1083 1.7.0 (2021-02-11)
1084 • Dropped support for Python 2.7.
1085
1086 • Added support for EC keys.
1087
1088 1.6.0 (2021-01-26)
1089 • Deprecated support for Python 2.7.
1090
1091 1.5.0 (2020-11-03)
1092 • Added support for Python 3.9.
1093
1094 • Dropped support for Python 3.5.
1095
1096 • Stopped supporting running tests with python setup.py test which is
1097 deprecated in favor of python -m pytest.
1098
1099 1.4.0 (2020-08-17)
1100 • Deprecated support for Python 3.5.
1101
1102 1.3.0 (2020-01-28)
1103 • Deprecated support for Python 3.4.
1104
1105 • Officially add support for Python 3.8.
1106
1107 1.2.0 (2019-06-28)
1108 • Support for Python 2.6 and 3.3 has been removed.
1109
1110 • Known incompatibilities with Python 3.8 have been resolved.
1111
1112 1.1.0 (2018-04-13)
1113 • Deprecated support for Python 2.6 and 3.3.
1114
1115 • Use the sign and verify methods when they are available in cryptogra‐
1116 phy instead of the deprecated methods signer and verifier.
1117
1118 1.0.1 (2017-10-25)
1119 Stop installing mock as part of the default but only as part of the
1120 testing dependencies.
1121
1122 1.0.0 (2017-10-13)
1123 First release after moving the josepy package into a standalone li‐
1124 brary.
1125
1126 • Index
1127
1128 • Module Index
1129
1130 • Search Page
1131
1133 Let's Encrypt Project
1134
1136 2015-2023, Let's Encrypt Project
1137
1138
1139
1140
11411.13 Jul 21, 2023 JOSEPY(1)