Пример #1
0
 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()
Пример #2
0
 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()
Пример #3
0
 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)
Пример #5
0
 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)
Пример #6
0
 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
Пример #7
0
 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()
Пример #8
0
 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)
Пример #9
0
    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)))
Пример #10
0
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)
Пример #11
0
 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']))
Пример #12
0
 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']))
Пример #13
0
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)
Пример #14
0
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)
Пример #15
0
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)
Пример #16
0
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
Пример #17
0
    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)
Пример #18
0
 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
Пример #19
0
    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,))
Пример #20
0
 def y(value):
     if value == 500:
         raise errors.DeserializationError()
     return value
Пример #21
0
 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()
Пример #22
0
 def crit(unused_value: Any) -> Any:
     raise errors.DeserializationError(
         '"crit" is not supported, please subclass')
Пример #23
0
 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
Пример #24
0
 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
Пример #25
0
 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')