Ejemplo n.º 1
0
def b32decode(s, _mapping={}):
    """Decode the Base32 encoded bytes-like object or ASCII string s.
    """
    if not _mapping:
        # Delay the initialization of the table to not waste memory
        # if the function is never called
        _mapping.update(zip(B32ALPHABET, count()))
        _mapping.update(zip(B32ALPHABET.lower(), count()))
    s = _bytes_from_decode_data(s)
    decoded = bytearray(len(s) * 5 // 8)
    try:
        idx = acc = 0
        for i, c in enumerate(s):
            acc = (acc << 5) | _mapping[c]
            if i & 7 == 7:
                decoded[idx:idx+5] = acc.to_bytes(5, 'big')
                idx += 5
                acc = 0
    except KeyError:
        raise binascii.Error('Non-base32 digit found') from None
    # Process the last, partial quanta
    if s and i & 7 < 7:
        try:
            i, j = B32PADDING[i & 7]
        except KeyError:
            raise binascii.Error('Incorrect padding')
        else:
            decoded[idx:] = (acc >> j).to_bytes(i, 'big')
    return bytes(decoded)
def b32decode(s, casefold=False, map01=None):
    """Decode the Base32 encoded bytes-like object or ASCII string s.
    Optional casefold is a flag specifying whether a lowercase alphabet is
    acceptable as input.  For security purposes, the default is False.
    RFC 3548 allows for optional mapping of the digit 0 (zero) to the
    letter O (oh), and for optional mapping of the digit 1 (one) to
    either the letter I (eye) or letter L (el).  The optional argument
    map01 when not None, specifies which letter the digit 1 should be
    mapped to (when map01 is not None, the digit 0 is always mapped to
    the letter O).  For security purposes the default is None, so that
    0 and 1 are not allowed in the input.
    The result is returned as a bytes object.  A binascii.Error is raised if
    the input is incorrectly padded or if there are non-alphabet
    characters present in the input.
    """
    global _b32rev
    # Delay the initialization of the table to not waste memory
    # if the function is never called
    if _b32rev is None:
        _b32rev = {v: k for k, v in enumerate(_b32alphabet)}
    s = _bytes_from_decode_data(s)
    if len(s) % 8:
        raise binascii.Error('Incorrect padding')
    # Handle section 2.4 zero and one mapping.  The flag map01 will be either
    # False, or the character to map the digit 1 (one) to.  It should be
    # either L (el) or I (eye).
    if map01 is not None:
        map01 = _bytes_from_decode_data(map01)
        assert len(map01) == 1, repr(map01)
        s = s.translate(bytes.maketrans(b'01', b'O' + map01))
    if casefold:
        s = s.upper()
    # Strip off pad characters from the right.  We need to count the pad
    # characters because this will tell us how many null bytes to remove from
    # the end of the decoded string.
    l = len(s)
    s = s.rstrip(b'=')
    padchars = l - len(s)
    # Now decode the full quanta
    decoded = bytearray()
    b32rev = _b32rev
    for i in range(0, len(s), 8):
        quanta = s[i: i + 8]
        acc = 0
        try:
            for c in quanta:
                acc = (acc << 5) + b32rev[c]
        except KeyError:
            raise binascii.Error('Non-base32 digit found') from None
        decoded += acc.to_bytes(5, 'big')
    # Process the last, partial quanta
    if l % 8 or padchars not in {0, 1, 3, 4, 6}:
        raise binascii.Error('Incorrect padding')
    if padchars and decoded:
        acc <<= 5 * padchars
        last = acc.to_bytes(5, 'big')
        leftover = (43 - 5 * padchars) // 8  # 1: 4, 3: 3, 4: 2, 6: 1
        decoded[-5:] = last[:leftover]
    return bytes(decoded)
Ejemplo n.º 3
0
def b32decode(s, casefold=False, map01=None):
    """Decode the Base32 encoded bytes-like object or ASCII string s.

    Optional casefold is a flag specifying whether a lowercase alphabet is
    acceptable as input.  For security purposes, the default is False.

    RFC 3548 allows for optional mapping of the digit 0 (zero) to the
    letter O (oh), and for optional mapping of the digit 1 (one) to
    either the letter I (eye) or letter L (el).  The optional argument
    map01 when not None, specifies which letter the digit 1 should be
    mapped to (when map01 is not None, the digit 0 is always mapped to
    the letter O).  For security purposes the default is None, so that
    0 and 1 are not allowed in the input.

    The result is returned as a bytes object.  A binascii.Error is raised if
    the input is incorrectly padded or if there are non-alphabet
    characters present in the input.
    """
    global _b32rev
    if _b32rev is None:
        _b32rev = {v: k for k, v in enumerate(_b32alphabet)}
    s = _bytes_from_decode_data(s)
    if len(s) % 8:
        raise binascii.Error('Incorrect padding')
    if map01 is not None:
        map01 = _bytes_from_decode_data(map01)
        assert len(map01) == 1, repr(map01)
        s = s.translate(bytes.maketrans(b'01', b'O' + map01))
    if casefold:
        s = s.upper()
    l = len(s)
    s = s.rstrip(b'=')
    padchars = l - len(s)
    decoded = bytearray()
    b32rev = _b32rev
    for i in range(0, len(s), 8):
        quanta = s[i:i + 8]
        acc = 0
        try:
            for c in quanta:
                acc = (acc << 5) + b32rev[c]
        except KeyError:
            raise binascii.Error('Non-base32 digit found') from None
        decoded += acc.to_bytes(5, 'big')
    if padchars:
        acc <<= 5 * padchars
        last = acc.to_bytes(5, 'big')
        if padchars == 1:
            decoded[-5:] = last[:-1]
        elif padchars == 3:
            decoded[-5:] = last[:-2]
        elif padchars == 4:
            decoded[-5:] = last[:-3]
        elif padchars == 6:
            decoded[-5:] = last[:-4]
        else:
            raise binascii.Error('Incorrect padding')
    return bytes(decoded)
Ejemplo n.º 4
0
def decode_b(encoded):
    defects = []
    pad_err = len(encoded) % 4
    if pad_err:
        defects.append(errors.InvalidBase64PaddingDefect())
        padded_encoded = encoded + b'==='[:4-pad_err]
    else:
        padded_encoded = encoded
    try:
        # The validate kwarg to b64decode is not supported in Py2.x
        if not re.match(b'^[A-Za-z0-9+/]*={0,2}$', padded_encoded):
            raise binascii.Error('Non-base64 digit found')
        return base64.b64decode(padded_encoded), defects
    except binascii.Error:
        # Since we had correct padding, this must an invalid char error.
        defects = [errors.InvalidBase64CharactersDefect()]
        # The non-alphabet characters are ignored as far as padding
        # goes, but we don't know how many there are.  So we'll just
        # try various padding lengths until something works.
        for i in 0, 1, 2, 3:
            try:
                return base64.b64decode(encoded+b'='*i), defects
            except (binascii.Error, TypeError):    # Py2 raises a TypeError
                if i==0:
                    defects.append(errors.InvalidBase64PaddingDefect())
        else:
            # This should never happen.
            raise AssertionError("unexpected binascii.Error")
Ejemplo n.º 5
0
def b64decode(s: bytes,
              altchars: bytes = None,
              validate: bool = False) -> bytes:
    """Decode a Base64 encoded byte string.

    s is the byte string to decode.  Optional altchars must be a
    string of length 2 which specifies the alternative alphabet used
    instead of the '+' and '/' characters.

    The decoded string is returned.  A binascii.Error is raised if s is
    incorrectly padded.

    If validate is False (the default), non-base64-alphabet characters are
    discarded prior to the padding check.  If validate is True,
    non-base64-alphabet characters in the input result in a binascii.Error.
    """
    if not isinstance(s, bytes_types):
        raise TypeError("expected bytes, not %s" % s.__class__.__name__)
    if altchars is not None:
        if not isinstance(altchars, bytes_types):
            raise TypeError("expected bytes, not %s" %
                            altchars.__class__.__name__)
        assert len(altchars) == 2, repr(altchars)
        s = _translate(s, {chr(altchars[0]): b'+', chr(altchars[1]): b'/'})
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s)
    def list_configuration_settings(
        self,
        key_filter=None,
        label_filter=None,
        **kwargs
    ):  # type: (Optional[str], Optional[str], dict) -> azure.core.paging.ItemPaged[ConfigurationSetting]
        """List the configuration settings stored in the configuration service, optionally filtered by
        label and accept_datetime

        :param key_filter: filter results based on their keys. '*' can be
         used as wildcard in the beginning or end of the filter
        :type key_filter: str
        :param label_filter: filter results based on their label. '*' can be
         used as wildcard in the beginning or end of the filter
        :type label_filter: str
        :keyword datetime accept_datetime: filter out ConfigurationSetting created after this datetime
        :keyword list[str] fields: specify which fields to include in the results. Leave None to include all fields
        :keyword dict headers: if "headers" exists, its value (a dict) will be added to the http request header
        :return: An iterator of :class:`ConfigurationSetting`
        :rtype: :class:`azure.core.paging.ItemPaged[ConfigurationSetting]`
        :raises: :class:`HttpResponseError`, :class:`ClientAuthenticationError`

        Example

        .. code-block:: python

            from datetime import datetime, timedelta

            accept_datetime = datetime.today() + timedelta(days=-1)

            all_listed = async_client.list_configuration_settings()
            async for item in all_listed:
                pass  # do something

            filtered_listed = async_client.list_configuration_settings(
                label_filter="Labe*", key_filter="Ke*", accept_datetime=accept_datetime
            )
            async for item in filtered_listed:
                pass  # do something
        """
        select = kwargs.pop("fields", None)
        if select:
            select = ["locked" if x == "read_only" else x for x in select]
        error_map = {401: ClientAuthenticationError}

        try:
            return self._impl.get_key_values(
                label=label_filter,
                key=key_filter,
                select=select,
                cls=lambda objs:
                [ConfigurationSetting._from_key_value(x) for x in objs],
                error_map=error_map,
                **kwargs)
        except ErrorException as error:
            raise HttpResponseError(message=error.message,
                                    response=error.response)
        except binascii.Error:
            raise binascii.Error(
                "Connection string secret has incorrect padding")
    def get_configuration_setting(
        self,
        key,
        label=None,
        etag="*",
        match_condition=MatchConditions.Unconditionally,
        **kwargs
    ):  # type: (str, Optional[str], Optional[str], Optional[MatchConditions], dict) -> ConfigurationSetting

        """Get the matched ConfigurationSetting from Azure App Configuration service

        :param key: key of the ConfigurationSetting
        :type key: str
        :param label: label of the ConfigurationSetting
        :type label: str
        :param etag: check if the ConfigurationSetting is changed. Set None to skip checking etag
        :type etag: str or None
        :param ~azure.core.MatchConditions match_condition: the match condition to use upon the etag
        :keyword datetime accept_datetime: the retrieved ConfigurationSetting that created no later than this datetime
        :keyword dict headers: if "headers" exists, its value (a dict) will be added to the http request header
        :return: The matched ConfigurationSetting object
        :rtype: ~azure.appconfiguration.ConfigurationSetting
        :raises: :class:`HttpResponseError`, :class:`ClientAuthenticationError`, \
        :class:`ResourceNotFoundError`, :class:`ResourceModifiedError`, :class:`ResourceExistsError`

        Example

        .. code-block:: python

            fetched_config_setting = client.get_configuration_setting(
                key="MyKey", label="MyLabel"
            )
        """
        error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError}
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        if match_condition == MatchConditions.IfModified:
            error_map[304] = ResourceNotModifiedError
        if match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        if match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError

        try:
            key_value = self._impl.get_key_value(
                key=key,
                label=label,
                if_match=prep_if_match(etag, match_condition),
                if_none_match=prep_if_none_match(etag, match_condition),
                error_map=error_map,
                **kwargs
            )
            return ConfigurationSetting._from_generated(key_value)
        except ResourceNotModifiedError:
            return None
        except HttpResponseError as error:
            e = error_map[error.status_code]
            raise e(message=error.message, response=error.response)
        except binascii.Error:
            raise binascii.Error("Connection string secret has incorrect padding")
Ejemplo n.º 8
0
def b16decode(s, casefold=False):
    s = _bytes_from_decode_data(s)
    if casefold:
        s = s.upper()
    if re.search(b'[^0-9A-F]', s):
        raise binascii.Error('Non-base16 digit found')
    return binascii.unhexlify(s)
Ejemplo n.º 9
0
def decode_base64(encoded_data: str) -> bytes:
    """
    Decode base64 somewhat like Vuforia does.

    Raises:
        binascii.Error: Vuforia would consider this encoded data as an
        "UNPROCESSABLE_ENTITY".

    Returns:
        The given data, decoded as base64.
    """
    acceptable_characters = string.ascii_letters + string.digits + '+/='
    for character in encoded_data:
        if character not in acceptable_characters:
            raise binascii.Error()

    if len(encoded_data) % 4 == 0:
        decoded = base64.b64decode(encoded_data)
    elif len(encoded_data) % 4 == 1:
        decoded = base64.b64decode(encoded_data[:-1])
    elif len(encoded_data) % 4 == 2:
        decoded = base64.b64decode(encoded_data + '==')
    else:
        assert len(encoded_data) % 4 == 3
        decoded = base64.b64decode(encoded_data + '=')

    return decoded
Ejemplo n.º 10
0
def unhex(es):
    if not isinstance(es, collections.ByteString):
        try:
            es = es.encode("us-ascii")
        except UnicodeError:
            raise binascii.Error("non-ascii character in hex-string")
    return base64.b16decode(es)
    def delete_configuration_setting(self, key, label=None, **kwargs):
        # type: (str, Optional[str], **Any) -> ConfigurationSetting
        """Delete a ConfigurationSetting if it exists

        :param key: key used to identify the ConfigurationSetting
        :type key: str
        :param label: label used to identify the ConfigurationSetting
        :type label: str
        :keyword str etag: check if the ConfigurationSetting is changed. Set None to skip checking etag
        :keyword match_condition: The match condition to use upon the etag
        :paramtype match_condition: :class:`~azure.core.MatchConditions`
        :keyword dict headers: if "headers" exists, its value (a dict) will be added to the http request
        :return: The deleted ConfigurationSetting returned from the service, or None if it doesn't exist.
        :rtype: :class:`~azure.appconfiguration.ConfigurationSetting`
        :raises: :class:`HttpResponseError`, :class:`ClientAuthenticationError`, \
        :class:`ResourceReadOnlyError`, :class:`ResourceModifiedError`, :class:`ResourceNotModifiedError`, \
        :class:`ResourceNotFoundError`, :class:`ResourceExistsError`

        Example

        .. code-block:: python

            deleted_config_setting = client.delete_configuration_setting(
                key="MyKey", label="MyLabel"
            )
        """
        etag = kwargs.pop("etag", None)
        match_condition = kwargs.pop("match_condition",
                                     MatchConditions.Unconditionally)
        custom_headers = CaseInsensitiveDict(
            kwargs.get("headers"))  # type: Mapping[str, Any]
        error_map = {
            401: ClientAuthenticationError,
            409: ResourceReadOnlyError
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        if match_condition == MatchConditions.IfModified:
            error_map[412] = ResourceNotModifiedError
        if match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        if match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError

        try:
            key_value_deleted = self._impl.delete_key_value(
                key=key,
                label=label,
                if_match=prep_if_match(etag, match_condition),
                headers=custom_headers,
                error_map=error_map,
            )
            return ConfigurationSetting._from_generated(
                key_value_deleted)  # type: ignore
        except HttpResponseError as error:
            e = error_map[error.status_code]
            raise e(message=error.message, response=error.response)
        except binascii.Error:
            raise binascii.Error(
                "Connection string secret has incorrect padding")
 def configFromProvisioningCSVFile(self, deviceId, fileName):
     deviceIdStr = "%016X" % deviceId
     with open(fileName) as file:
         reader = csv.DictReader(file,
                                 dialect=csv.unix_dialect,
                                 skipinitialspace=True)
         for row in reader:
             curDeviceId = row.get('Device_Id', None)
             if curDeviceId == None:
                 curDeviceId = row.get('MAC', None)
             if curDeviceId == None:
                 raise Exception(
                     '"Device_Id" column not found in provisioning csv file'
                 )
             if curDeviceId == deviceIdStr:
                 try:
                     self.deviceId = deviceId
                     self._configFromProvisioningCSVRow(row)
                 except binascii.Error as ex:
                     raise binascii.Error(
                         'Invalid base-64 data in provisioning data CSV file: %s\nFile %s, line %d'
                         % (str(ex), fileName, reader.line_num))
                 except ValueError as ex:
                     raise ValueError(
                         'Error in provisioning data CSV file: %s\nFile %s, line %d'
                         % (str(ex), fileName, reader.line_num))
                 return True
     return False
Ejemplo n.º 13
0
def b64decode(s, altchars=None, validate=False):
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s)
Ejemplo n.º 14
0
def decode(s):
    s = _bytes_from_decode_data(s)
    if len(s) % 8:
        raise binascii.Error('Incorrect padding')
    rev = _reverse_table(ZOOKO32_ALPHABET)
    decoded = bytearray()
    for i in range(0, len(s), 8):
        quanta = s[i:i + 8]
        acc = 0
        try:
            for c in quanta:
                acc = (acc << 5) + rev[c]
        except KeyError:
            raise binascii.Error('Non-base32 digit found') from None
        decoded += acc.to_bytes(5, 'big')
    # FIXME: do we need padding handling?
    return bytes(decoded)
    def list_revisions(self,
                       key_filter: Optional[str] = None,
                       label_filter: Optional[str] = None,
                       **kwargs: Any) -> AsyncItemPaged[ConfigurationSetting]:
        """
        Find the ConfigurationSetting revision history.

        :param key_filter: filter results based on their keys. '*' can be
         used as wildcard in the beginning or end of the filter
        :type key_filter: str
        :param label_filter: filter results based on their label. '*' can be
         used as wildcard in the beginning or end of the filter
        :type label_filter: str
        :keyword datetime accept_datetime: filter out ConfigurationSetting created after this datetime
        :keyword list[str] fields: specify which fields to include in the results. Leave None to include all fields
        :return: An iterator of :class:`ConfigurationSetting`
        :rtype: ~azure.core.async_paging.AsyncItemPaged[ConfigurationSetting]
        :raises: :class:`HttpResponseError`, :class:`ClientAuthenticationError`

        Example

        .. code-block:: python

            # in async function
            from datetime import datetime, timedelta

            accept_datetime = datetime.today() + timedelta(days=-1)

            all_revisions = async_client.list_revisions()
            async for item in all_revisions:
                pass  # do something

            filtered_revisions = async_client.list_revisions(
                label_filter="Labe*", key_filter="Ke*", accept_datetime=accept_datetime
            )
            async for item in filtered_revisions:
                pass  # do something
        """
        select = kwargs.pop("fields", None)
        if select:
            select = ["locked" if x == "read_only" else x for x in select]
        error_map = {401: ClientAuthenticationError}

        try:
            return self._impl.get_revisions(  # type: ignore
                label=label_filter,
                key=key_filter,
                select=select,
                cls=lambda objs:
                [ConfigurationSetting._from_generated(x) for x in objs],
                error_map=error_map,
                **kwargs)
        except HttpResponseError as error:
            e = error_map[error.status_code]
            raise e(message=error.message, response=error.response)
        except binascii.Error:
            raise binascii.Error(
                "Connection string secret has incorrect padding")
Ejemplo n.º 16
0
def _b32decode(alphabet, s, casefold=False, map01=None):
    global _b32rev
    # Delay the initialization of the table to not waste memory
    # if the function is never called
    if alphabet not in _b32rev:
        _b32rev[alphabet] = {v: k for k, v in enumerate(alphabet)}
    s = _bytes_from_decode_data(s)
    if len(s) % 8:
        raise binascii.Error('Incorrect padding')
    # Handle section 2.4 zero and one mapping.  The flag map01 will be either
    # False, or the character to map the digit 1 (one) to.  It should be
    # either L (el) or I (eye).
    if map01 is not None:
        map01 = _bytes_from_decode_data(map01)
        assert len(map01) == 1, repr(map01)
        s = s.translate(bytes.maketrans(b'01', b'O' + map01))
    if casefold:
        s = s.upper()
    # Strip off pad characters from the right.  We need to count the pad
    # characters because this will tell us how many null bytes to remove from
    # the end of the decoded string.
    l = len(s)
    s = s.rstrip(b'=')
    padchars = l - len(s)
    # Now decode the full quanta
    decoded = bytearray()
    b32rev = _b32rev[alphabet]
    for i in range(0, len(s), 8):
        quanta = s[i:i + 8]
        acc = 0
        try:
            for c in quanta:
                acc = (acc << 5) + b32rev[c]
        except KeyError:
            raise binascii.Error('Non-base32 digit found') from None
        decoded += acc.to_bytes(5, 'big')
    # Process the last, partial quanta
    if l % 8 or padchars not in {0, 1, 3, 4, 6}:
        raise binascii.Error('Incorrect padding')
    if padchars and decoded:
        acc <<= 5 * padchars
        last = acc.to_bytes(5, 'big')
        leftover = (43 - 5 * padchars) // 8  # 1: 4, 3: 3, 4: 2, 6: 1
        decoded[-5:] = last[:leftover]
    return bytes(decoded)
Ejemplo n.º 17
0
def unb64(es):
    if not isinstance(es, collections.ByteString):
        try:
            es = es.encode("us-ascii")
        except UnicodeError:
            raise binascii.Error("non-ascii character in base64-string")
    if (len(es) % 4) != 0:
        es += b"=" * (4 - (len(es) % 4))
    return base64.b64decode(es)
Ejemplo n.º 18
0
def b32decode(s, casefold=False, map01=None):
    s = _bytes_from_decode_data(s)
    (quanta, leftover) = divmod(len(s), 8)
    if leftover:
        raise binascii.Error('Incorrect padding')
    if map01 is not None:
        map01 = _bytes_from_decode_data(map01)
        s = s.translate(bytes.maketrans(b'01', b'O' + map01))
    if casefold:
        s = s.upper()
    padchars = 0
    mo = re.search(b'(?P<pad>[=]*)$', s)
    if mo:
        padchars = len(mo.group('pad'))
        if padchars > 0:
            s = s[:-padchars]
    parts = []
    acc = 0
    shift = 35
    for c in s:
        val = _b32rev.get(c)
        if val is None:
            raise binascii.Error('Non-base32 digit found')
        acc += _b32rev[c] << shift
        shift -= 5
        while shift < 0:
            parts.append(binascii.unhexlify(bytes('%010x' % acc, 'ascii')))
            acc = 0
            shift = 35
    last = binascii.unhexlify(bytes('%010x' % acc, 'ascii'))
    if padchars == 0:
        last = b''
    elif padchars == 1:
        last = last[:-1]
    elif padchars == 3:
        last = last[:-2]
    elif padchars == 4:
        last = last[:-3]
    elif padchars == 6:
        last = last[:-4]
    else:
        raise binascii.Error('Incorrect padding')
    parts.append(last)
    return b''.join(parts)
Ejemplo n.º 19
0
    def test_failed_base64_decode_service_catalog(self):
        with mock.patch('deuce.storage_driver',
                        spec=swift.SwiftStorageDriver) as swift_driver:
            with mock.patch('base64.b64decode') as b64_decoder:
                b64_decoder.side_effect = binascii.Error('mock')

                self.app_setup(before_hooks_swift)
                response = self.simulate_get(
                    '/v1.0', headers={'x-service-catalog': 'mock'})
                self.assertEqual(self.srmock.status, falcon.HTTP_412)
Ejemplo n.º 20
0
def unb32(es):
    if not isinstance(es, collections.ByteString):
        try:
            es = es.encode("us-ascii")
        except UnicodeError:
            raise binascii.Error("non-ascii character in base32-string")
    if (len(es) % 8) != 0:
        es += b"=" * (8 - (len(es) % 8))
    es = es.upper(
    )  # The whole point of Base32 is that it's case-insensitive :P
    return base64.b32decode(es)
    async def add_configuration_setting(self, configuration_setting, **kwargs):
        # type: (ConfigurationSetting, dict) -> ConfigurationSetting
        """Add a ConfigurationSetting into the Azure App Configuration service.

        :param configuration_setting: the ConfigurationSetting object to be added
        :type configuration_setting: :class:`ConfigurationSetting<azure.appconfiguration.ConfigurationSetting>`
        :keyword dict headers: if "headers" exists, its value (a dict) will be added to the http request header
        :return: The ConfigurationSetting object returned from the App Configuration service
        :rtype: :class:`ConfigurationSetting`
        :raises: :class:`HttpResponseError`, :class:`ClientAuthenticationError`, :class:`ResourceExistsError`

        Example

        .. code-block:: python

            # in async fuction
            config_setting = ConfigurationSetting(
                key="MyKey",
                label="MyLabel",
                value="my value",
                content_type="my content type",
                tags={"my tag": "my tag value"}
            )
            added_config_setting = await async_client.add_configuration_setting(config_setting)
        """
        key_value = KeyValue(
            key=configuration_setting.key,
            label=configuration_setting.label,
            content_type=configuration_setting.content_type,
            value=configuration_setting.value,
            tags=configuration_setting.tags,
        )
        custom_headers = CaseInsensitiveDict(kwargs.get("headers"))
        error_map = {401: ClientAuthenticationError, 412: ResourceExistsError}

        try:
            key_value_added = await self._impl.put_key_value(
                entity=key_value,
                key=key_value.key,
                label=key_value.label,
                if_none_match="*",
                headers=custom_headers,
                error_map=error_map,
            )
            return ConfigurationSetting._from_key_value(key_value_added)
        except ErrorException as error:
            raise HttpResponseError(message=error.message,
                                    response=error.response)
        except binascii.Error:
            raise binascii.Error(
                "Connection string secret has incorrect padding")
def b16decode(s, casefold=False):
    """Decode the Base16 encoded bytes-like object or ASCII string s.
    Optional casefold is a flag specifying whether a lowercase alphabet is
    acceptable as input.  For security purposes, the default is False.
    The result is returned as a bytes object.  A binascii.Error is raised if
    s is incorrectly padded or if there are non-alphabet characters present
    in the input.
    """
    s = _bytes_from_decode_data(s)
    if casefold:
        s = s.upper()
    if re.search(b'[^0-9A-F]', s):
        raise binascii.Error('Non-base16 digit found')
    return binascii.unhexlify(s)
Ejemplo n.º 23
0
 def configFromProvisioningServer(self, serverBaseURL, deviceId, disableServerValidation=False):
     if disableServerValidation:
         ssl._create_default_https_context = ssl._create_unverified_context
     url = serverBaseURL + '/GetWeaveProvisioningInfo?macAddr=%016X' % deviceId 
     with urllib.request.urlopen(url) as resp:
         respData = resp.read()
     respPlist = plistlib.loads(respData, fmt=plistlib.FMT_XML)
     try:
         if self.deviceCert == None:
             self.deviceCert = base64.b64decode(respPlist['nlWeaveCertificate'], validate=True)
         if self.devicePrivateKey == None:
             self.devicePrivateKey = base64.b64decode(respPlist['nlWeavePrivateKey'], validate=True)
         if self.pairingCode == None:
             self.pairingCode = respPlist['nlWeavePairingCode']
     except binascii.Error as ex:
         raise binascii.Error('Invalid base-64 data returned by provisioning server: %s' % (str(ex)))
    async def add_configuration_setting(
            self, configuration_setting: ConfigurationSetting,
            **kwargs: Any) -> ConfigurationSetting:
        """Add a ConfigurationSetting instance into the Azure App Configuration service.

        :param configuration_setting: the ConfigurationSetting object to be added
        :type configuration_setting: :class:`~azure.appconfiguration.ConfigurationSetting`
        :return: The ConfigurationSetting object returned from the App Configuration service
        :rtype: :class:`~azure.appconfiguration.ConfigurationSetting`
        :raises: :class:`HttpResponseError`, :class:`ClientAuthenticationError`, :class:`ResourceExistsError`

        Example

        .. code-block:: python

            # in async fuction
            config_setting = ConfigurationSetting(
                key="MyKey",
                label="MyLabel",
                value="my value",
                content_type="my content type",
                tags={"my tag": "my tag value"}
            )
            added_config_setting = await async_client.add_configuration_setting(config_setting)
        """
        key_value = configuration_setting._to_generated()
        custom_headers = CaseInsensitiveDict(
            kwargs.get("headers"))  # type: Mapping[str, Any]
        error_map = {401: ClientAuthenticationError, 412: ResourceExistsError}

        try:
            key_value_added = await self._impl.put_key_value(
                entity=key_value,
                key=key_value.key,  # type: ignore
                label=key_value.label,
                if_none_match="*",
                headers=custom_headers,
                error_map=error_map,
            )
            return ConfigurationSetting._from_generated(key_value_added)
        except HttpResponseError as error:
            e = error_map[error.status_code]
            raise e(message=error.message, response=error.response)
        except binascii.Error:
            raise binascii.Error(
                "Connection string secret has incorrect padding")
Ejemplo n.º 25
0
def b16decode(s, casefold=False):
    """Decode a Base16 encoded byte string.

    s is the byte string to decode.  Optional casefold is a flag
    specifying whether a lowercase alphabet is acceptable as input.
    For security purposes, the default is False.

    The decoded byte string is returned.  binascii.Error is raised if
    s were incorrectly padded or if there are non-alphabet characters
    present in the string.
    """
    s = _bytes_from_decode_data(s)
    if casefold:
        s = s.upper()
    if re.search(b"[^0-9A-F]", s):
        raise binascii.Error("Non-base16 digit found")
    return binascii.unhexlify(s)
Ejemplo n.º 26
0
def b16decode(s, casefold=False):
    """Decode a Base16 encoded byte string.

    s is the byte string to decode.  Optional casefold is a flag
    specifying whether a lowercase alphabet is acceptable as input.
    For security purposes, the default is False.

    The decoded byte string is returned.  binascii.Error is raised if
    s were incorrectly padded or if there are non-alphabet characters
    present in the string.
    """
    if not isinstance(s, bytes_types):
        raise TypeError("expected bytes, not %s" % s.__class__.__name__)
    if casefold:
        s = s.upper()
    if re.search(b'[^0-9A-F]', s):
        raise binascii.Error('Non-base16 digit found')
    return binascii.unhexlify(s)
Ejemplo n.º 27
0
def b64decode(s, altchars=None, validate=False):
    """Decode a Base64 encoded byte string.
    s is the byte string to decode.  Optional altchars must be a
    string of length 2 which specifies the alternative alphabet used
    instead of the '+' and '/' characters.
    The decoded string is returned.  A binascii.Error is raised if s is
    incorrectly padded.
    If validate is False (the default), non-base64-alphabet characters are
    discarded prior to the padding check.  If validate is True,
    non-base64-alphabet characters in the input result in a binascii.Error.
    """
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s)
def b64decode(s, altchars=None, validate=False):
    """Decode the Base64 encoded bytes-like object or ASCII string s.
    Optional altchars must be a bytes-like object or ASCII string of length 2
    which specifies the alternative alphabet used instead of the '+' and '/'
    characters.
    The result is returned as a bytes object.  A binascii.Error is raised if
    s is incorrectly padded.
    If validate is False (the default), characters that are neither in the
    normal base-64 alphabet nor the alternative alphabet are discarded prior
    to the padding check.  If validate is True, these non-alphabet characters
    in the input result in a binascii.Error.
    """
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.fullmatch(b'[A-Za-z0-9+/]*={0,2}', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s)
Ejemplo n.º 29
0
    def _get_credentials_basic_auth(self, request):
        """ Userid and password parsed from the ``Authorization`` request header."""
        log.debug('_get_credentials_basic_auth')
        authorization = request.headers.get('Authorization')
        if not authorization:
            raise exc.NoAuthorizationHeader('No Authorization Header')
        try:
            authmeth, auth = authorization.split(' ', 1)
        except ValueError:  # not enough values to unpack
            raise ValueError('Auth Header malformed')

        if authmeth.lower() != 'basic':
            raise NotBasicAuth('Auth method is not "Basic Auth"')

        try:
            authbytes = b64decode(auth.strip())
        # can't decode
        except TypeError:
            raise TypeError('Can\'t decode Authorization')
        except binascii.Error:
            raise binascii.Error('Can\'t decode Authorization')

        # try utf-8 first, then latin-1; see discussion in
        # https://github.com/Pylons/pyramid/issues/898
        try:
            auth = authbytes.decode('utf-8')
        except UnicodeDecodeError:
            auth = authbytes.decode('latin-1')

        try:
            username, password = auth.split(':', 1)
        except ValueError:  # not enough values to unpack
            return None
        log.debug(
            '_get_credentials_basic auth returns username:{0}, password:{1}'.
            format(username, password))
        return username, password
Ejemplo n.º 30
0
def b64decode(s, altchars=None, validate=False):
    """Decode the Base64 encoded bytes-like object or ASCII string s.
    Optional altchars must be a bytes-like object or ASCII string of length 2
    which specifies the alternative alphabet used instead of the '+' and '/'
    characters.
    The result is returned as a bytes object.  A binascii.Error is raised if
    s is incorrectly padded.
    If validate is False (the default), characters that are neither in the
    normal base-64 alphabet nor the alternative alphabet are discarded prior
    to the padding check.  If validate is True, these non-alphabet characters
    in the input result in a binascii.Error.
    """
    if _has_extension:
        s = _bytes_from_decode_data(s)
        if altchars is not None:
            altchars = _bytes_from_decode_data(altchars)
            assert len(altchars) == 2, repr(altchars)
        try:
            decoded = _pybase64.decode(s, altchars, validate)
        except LookupError:
            raise binascii.Error('Non-base64 digit found')
        return decoded
    else:
        return base64.b64decode(s, altchars, validate)