def _decode_param(cls, data: str) -> int: """Decode Base64urlUInt.""" try: binary = json_util.decode_b64jose(data) if not binary: raise errors.DeserializationError() return int.from_bytes(binary, byteorder="big") except ValueError: # invalid literal for long() with base 16 raise errors.DeserializationError()
def _decode_param(cls, data: str, name: str, valid_length: int) -> int: """Decode Base64urlUInt.""" try: binary = json_util.decode_b64jose(data) if len(binary) != valid_length: raise errors.DeserializationError( f'Expected parameter "{name}" to be {valid_length} bytes ' f'after base64-decoding; got {len(binary)} bytes instead') return int.from_bytes(binary, byteorder="big") except ValueError: # invalid literal for long() with base 16 raise errors.DeserializationError()
def x5c(value): # pylint: disable=missing-docstring,no-self-argument try: return tuple(util.ComparableX509(crypto.load_certificate( crypto.FILETYPE_ASN1, base64.b64decode(cert))) for cert in value) except crypto.Error as error: raise errors.DeserializationError(error)
def json_loads(cls, json_string): """Deserialize from JSON document string.""" try: loads = json.loads(json_string) except ValueError as error: raise errors.DeserializationError(error) return cls.from_json(loads)
def json_loads(cls: Type[GenericJSONDeSerializable], json_string: Union[str, bytes]) -> GenericJSONDeSerializable: """Deserialize from JSON document string.""" try: loads = json.loads(json_string) except ValueError as error: raise errors.DeserializationError(error) return cls.from_json(loads)
def decode(cls, value: str) -> str: """Decoder.""" # 4.1.10 if '/' not in value: if ';' in value: raise errors.DeserializationError('Unexpected semi-colon') return cls.PREFIX + value return value
def _crv_to_curve(cls, crv: str) -> ec.EllipticCurve: # crv is case-sensitive if crv == 'P-256': return ec.SECP256R1() if crv == 'P-384': return ec.SECP384R1() if crv == 'P-521': return ec.SECP521R1() raise errors.DeserializationError()
def x5c(value): try: return tuple( util.ComparableX509( crypto.load_certificate(crypto.FILETYPE_ASN1, base64.b64decode(cert))) for cert in value) except crypto.Error as error: raise errors.DeserializationError(error)
def _check_required(cls, jobj: Mapping[str, Any]) -> None: missing = set() for _, field in cls._fields.items(): if not field.omitempty and field.json_name not in jobj: missing.add(field.json_name) if missing: raise errors.DeserializationError( 'The following fields are required: {0}'.format( ','.join(missing)))
def decode_hex16(value, size=None, minimum=False): """Decode hexlified field. :param unicode value: :param int size: Required length (after decoding). :param bool minimum: If ``True``, then `size` will be treated as minimum required length, as opposed to exact equality. :rtype: bytes """ value = value.encode() if size is not None and ((not minimum and len(value) != size * 2) or (minimum and len(value) < size * 2)): raise errors.DeserializationError() error_cls = TypeError if six.PY2 else binascii.Error try: return binascii.unhexlify(value) except error_cls as error: raise errors.DeserializationError(error)
def from_json(cls, jobj): if 'signature' in jobj and 'signatures' in jobj: raise errors.DeserializationError('Flat mixed with non-flat') elif 'signature' in jobj: # flat return cls(payload=json_util.decode_b64jose(jobj.pop('payload')), signatures=(cls.signature_cls.from_json(jobj), )) else: return cls(payload=json_util.decode_b64jose(jobj['payload']), signatures=tuple( cls.signature_cls.from_json(sig) for sig in jobj['signatures']))
def from_json(cls, jobj: Mapping[str, Any]) -> 'JWS': if 'signature' in jobj and 'signatures' in jobj: raise errors.DeserializationError('Flat mixed with non-flat') elif 'signature' in jobj: # flat filtered = {key: value for key, value in jobj.items() if key != "payload"} return cls(payload=json_util.decode_b64jose(jobj['payload']), signatures=(cls.signature_cls.from_json(filtered),)) else: return cls(payload=json_util.decode_b64jose(jobj['payload']), signatures=tuple(cls.signature_cls.from_json(sig) for sig in jobj['signatures']))
def decode_hex16(value: str, size: Optional[int] = None, minimum: bool = False) -> bytes: """Decode hexlified field. :param unicode value: :param int size: Required length (after decoding). :param bool minimum: If ``True``, then `size` will be treated as minimum required length, as opposed to exact equality. :rtype: bytes """ value_b = value.encode() if size is not None and ((not minimum and len(value_b) != size * 2) or (minimum and len(value_b) < size * 2)): raise errors.DeserializationError() try: return binascii.unhexlify(value_b) except binascii.Error as error: raise errors.DeserializationError(error)
def decode_csr(b64der): """Decode JOSE Base-64 DER-encoded CSR. :param unicode b64der: :rtype: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509` """ try: return util.ComparableX509(OpenSSL.crypto.load_certificate_request( OpenSSL.crypto.FILETYPE_ASN1, decode_b64jose(b64der))) except OpenSSL.crypto.Error as error: raise errors.DeserializationError(error)
def decode_cert(b64der: str) -> util.ComparableX509: """Decode JOSE Base-64 DER-encoded certificate. :param unicode b64der: :rtype: `OpenSSL.crypto.X509` wrapped in `.ComparableX509` """ try: return util.ComparableX509( crypto.load_certificate(crypto.FILETYPE_ASN1, decode_b64jose(b64der))) except crypto.Error as error: raise errors.DeserializationError(error)
def decode_b64jose(data, size=None, minimum=False): """Decode JOSE Base-64 field. :param unicode data: :param int size: Required length (after decoding). :param bool minimum: If ``True``, then `size` will be treated as minimum required length, as opposed to exact equality. :rtype: bytes """ error_cls = TypeError if six.PY2 else binascii.Error try: decoded = b64.b64decode(data.encode()) except error_cls as error: raise errors.DeserializationError(error) if size is not None and ((not minimum and len(decoded) != size) or (minimum and len(decoded) < size)): raise errors.DeserializationError( "Expected at least or exactly {0} bytes".format(size)) return decoded
def get_type_cls(cls, jobj): """Get the registered class for ``jobj``.""" if cls in six.itervalues(cls.TYPES): if cls.type_field_name not in jobj: raise errors.DeserializationError( "Missing type field ({0})".format(cls.type_field_name)) # cls is already registered type_cls, force to use it # so that, e.g Revocation.from_json(jobj) fails if # jobj["type"] != "revocation". return cls if not isinstance(jobj, dict): raise errors.DeserializationError( "{0} is not a dictionary object".format(jobj)) try: typ = jobj[cls.type_field_name] except KeyError: raise errors.DeserializationError("missing type field") try: return cls.TYPES[typ] except KeyError: raise errors.UnrecognizedTypeError(typ, jobj)
def fields_from_json(cls, jobj: Mapping[str, Any]) -> Any: """Deserialize fields from JSON.""" cls._check_required(jobj) fields = {} for slot, field in cls._fields.items(): if field.json_name not in jobj and field.omitempty: fields[slot] = field.default else: value = jobj[field.json_name] try: fields[slot] = field.decode(value) except errors.DeserializationError as error: raise errors.DeserializationError( 'Could not decode {0!r} ({1!r}): {2}'.format( slot, value, error)) return fields
def from_compact(cls, compact: bytes) -> 'JWS': """Compact deserialization. :param bytes compact: """ try: protected, payload, signature = compact.split(b'.') except ValueError: raise errors.DeserializationError( 'Compact JWS serialization should comprise of exactly' ' 3 dot-separated components') sig = cls.signature_cls( protected=b64.b64decode(protected).decode('utf-8'), signature=b64.b64decode(signature)) return cls(payload=b64.b64decode(payload), signatures=(sig,))
def y(value): if value == 500: raise errors.DeserializationError() return value
def _decode_param(cls, data): """Decode Base64urlUInt.""" try: return int(binascii.hexlify(json_util.decode_b64jose(data)), 16) except ValueError: # invalid literal for long() with base 16 raise errors.DeserializationError()
def crit(unused_value: Any) -> Any: raise errors.DeserializationError( '"crit" is not supported, please subclass')
def fields_from_json(cls, jobj: Mapping[str, Any]) -> Dict[str, Any]: fields = super().fields_from_json(jobj) fields_with_combined = cls._with_combined(fields) if 'alg' not in fields_with_combined['combined'].not_omitted(): raise errors.DeserializationError('alg not present') return fields_with_combined
def fields_from_json(cls, jobj): fields = super(Signature, cls).fields_from_json(jobj) fields_with_combined = cls._with_combined(fields) if 'alg' not in fields_with_combined['combined'].not_omitted(): raise errors.DeserializationError('alg not present') return fields_with_combined
def crit(unused_value: Any) -> Any: # pylint: disable=missing-docstring,no-self-argument,no-self-use raise errors.DeserializationError( '"crit" is not supported, please subclass')