示例#1
0
def decode_hex16(value, size=None, minimum=False):
    """Decode hexlified field.

    :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.

    """
    if size is not None and ((not minimum and len(value) != size * 2) or
                             (minimum and len(value) < size * 2)):
        raise errors.DeserializationError()
    try:
        return binascii.unhexlify(value)
    except TypeError as error:
        raise errors.DeserializationError(error)
示例#2
0
def decode_csr(b64der):
    """Decode JOSE Base-64 DER-encoded CSR."""
    try:
        return util.ComparableX509(
            M2Crypto.X509.load_request_der_string(decode_b64jose(b64der)))
    except M2Crypto.X509.X509Error as error:
        raise errors.DeserializationError(error)
示例#3
0
 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)
示例#4
0
 def decode(cls, value):
     """Decoder."""
     # 4.1.10
     if '/' not in value:
         if ';' in value:
             raise errors.DeserializationError('Unexpected semi-colon')
         return cls.PREFIX + value
     return value
示例#5
0
 def x5c(value):  # pylint: disable=missing-docstring,no-self-argument
     try:
         return tuple(
             util.ComparableX509(
                 M2Crypto.X509.load_cert_der_string(base64.b64decode(cert)))
             for cert in value)
     except M2Crypto.X509.X509Error as error:
         raise errors.DeserializationError(error)
示例#6
0
def decode_b64jose(data, size=None, minimum=False):
    """Decode JOSE Base-64 field.

    :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.

    """
    try:
        decoded = b64.b64decode(data)
    except TypeError 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()

    return decoded
示例#7
0
 def x5c(value):  # pylint: disable=missing-docstring,no-self-argument
     try:
         return tuple(
             util.ComparableX509(
                 OpenSSL.crypto.load_certificate(
                     OpenSSL.crypto.FILETYPE_ASN1, base64.b64decode(cert)))
             for cert in value)
     except OpenSSL.crypto.Error as error:
         raise errors.DeserializationError(error)
示例#8
0
    def _check_required(cls, jobj):
        missing = set()
        for _, field in six.iteritems(cls._fields):
            if not field.omitempty and field.json_name not in jobj:
                missing.add(field.json_name)

        if missing:
            raise errors.DeserializationError(
                'The following field are required: {0}'.format(
                    ','.join(missing)))
示例#9
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)
示例#10
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']))
示例#11
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)
示例#12
0
 def from_compact(cls, compact):
     """Compact deserialization."""
     try:
         protected, payload, signature = compact.split('.')
     except ValueError:
         raise errors.DeserializationError(
             'Compact JWS serialization should comprise of exactly'
             ' 3 dot-separated components')
     sig = cls.signature_cls(protected=json_util.decode_b64jose(protected),
                             signature=json_util.decode_b64jose(signature))
     return cls(payload=json_util.decode_b64jose(payload),
                signatures=(sig, ))
示例#13
0
    def get_type_cls(cls, jobj):
        """Get the registered class for ``jobj``."""
        if cls in six.itervalues(cls.TYPES):
            assert jobj[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)
示例#14
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()

    return decoded
示例#15
0
 def fields_from_json(cls, jobj):
     """Deserialize fields from JSON."""
     cls._check_required(jobj)
     fields = {}
     for slot, field in six.iteritems(cls._fields):
         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
示例#16
0
    def from_compact(cls, compact):
        """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, ))
示例#17
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()
示例#18
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
 def y(value):
     if value == 500:
         raise errors.DeserializationError()
     return value
示例#20
0
 def crit(unused_value):
     # pylint: disable=missing-docstring,no-self-argument,no-self-use
     raise errors.DeserializationError(
         '"crit" is not supported, please subclass')