def set_draw(self, node_uuid, index, data):
     """Draw the image on the screen
     """
     img = None
     try:
         imgsio = cStringIO.StringIO(base64.base64_decode(data))
         img = PIL.Image.open(imgsio)
     except Exception:
         logger.exception('[%s] - Exception when reading image',
                          self.__class__.__name__)
     if img is not None:
         if self._bus.spi_acquire(blocking=False) == True:
             try:
                 imgsio = cStringIO.StringIO(base64.base64_decode(data))
                 img = PIL.Image.open(imgsio)
                 self.tft.display(img)
                 self.values['draw'].data = data
             except Exception:
                 logger.exception('[%s] - Exception when drawing image',
                                  self.__class__.__name__)
             finally:
                 self._bus.spi_release()
         else:
             logger.warning("[%s] - Can't get lock when drawing image",
                            self.__class__.__name__)
Example #2
0
    def to_python(self, value):
        """Return a Python representation of a value for the field.

        This will decode the value (if not already decoded) and return it.

        Args:
            value (object):
                The value to return a decoded value for.

        Returns:
            Base64DecodedValue:
            The decoded version of the provided value.

        Raises:
            Base64TypeError:
                The type of value provided could not be prepared for writing.
        """
        if value is not None and not isinstance(value, Base64DecodedValue):
            if isinstance(value, six.text_type):
                value = value.encode('utf-8')
            elif isinstance(value, six.memoryview):
                value = bytes(value)
            elif not isinstance(value, bytes):
                raise Base64TypeError(value)

            value = Base64DecodedValue(base64_decode(value))

        return value
Example #3
0
def scrape_icon(url):
    contents = get_page_content(url, icon_page=True)
    soup = BeautifulSoup(contents, features="html.parser")
    noun = soup.find("h1", attrs={"class": "main-term"}).text
    icon = soup.find("div", attrs={"class": "iconPreview"})
    noun_url = soup.find("link", attrs={"rel": "canonical"}).get("href")
    noun_id = None
    match = re.search(r"/(\d+)/", noun_url)
    if match:
        noun_id = match.group(1)
    designer = soup.find("div", attrs={"class": "designer"}).text
    license_str = soup.find("div", attrs={"class": "license-strip"}).text
    attribution_text = (noun.strip() + " by " + designer.strip() +
                        " from the Noun Project")
    attribution_text = normalize("NFKD", attribution_text)
    style_string = unescape(icon.get("style"))
    style_string = style_string.split("data:image/svg+xml;base64,")[1]
    svg_string = style_string.split('");')[0]
    base64_bytes = svg_string.encode("ascii")
    svg_string = base64_decode(base64_bytes).decode("ascii")
    svg_string = re.sub("height='\d+px'", "", svg_string)
    svg_string = re.sub("width='\d+px'", "", svg_string)

    return {
        "id": noun_id,
        "svg": svg_string,
        "license": license_str,
        "attr_text": attribution_text,
    }
Example #4
0
    def __get__(self, obj, *args, **kwargs):
        """Return a decoded value from the field.

        Args:
            obj (django.db.models.Model):
                The model owning the field.

            *args (tuple):
                Unused positional arguments.

            **kwargs (dict):
                Unused keyword arguments.

        Returns:
            Base64DecodedValue:
            The decoded value from the field. If no value has yet been stored,
            this will return ``None`` instead.

        Raises:
            AttributeError:
            A ``None`` value was passed for the object.
        """
        if obj is None:
            raise AttributeError('Can only be accessed via an instance.')

        value = obj.__dict__[self.field.name]

        if value is not None:
            value = Base64DecodedValue(base64_decode(value))

        return value
Example #5
0
    def to_python(self, value):
        """Return a Python representation of a value for the field.

        This will decode the value (if not already decoded) and return it.

        Args:
            value (object):
                The value to return a decoded value for.

        Returns:
            Base64DecodedValue:
            The decoded version of the provided value.

        Raises:
            Base64TypeError:
                The type of value provided could not be prepared for writing.
        """
        if value is not None:
            if not isinstance(value, (six.text_type, six.binary_type)):
                raise Base64TypeError(value)

            if not isinstance(value, Base64DecodedValue):
                if isinstance(value, six.text_type):
                    value = value.encode('utf-8')

                value = Base64DecodedValue(base64_decode(value))

        return value
 def set_write(self, node_uuid, index, data):
     """Write base64 data to card
     """
     #Will wait to get lock indefintively
     self._bus.spi_acquire()
     try:
         sio = base64.base64_decode(data)
         uid = self.pn532.read_passive_target()
         if uid is None:
             raise RuntimeError('No card found')
         logger.debug('[%s] - Read rfid %s', self.__class__.__name__,
                      binascii.hexlify(uid))
         # Authenticate and read block 4.
         if not self.pn532.mifare_classic_authenticate_block(
                 uid, 4, PN532.MIFARE_CMD_AUTH_B, CARD_KEY):
             raise RuntimeError('Failed to authenticate with card')
         if not self.pn532.mifare_classic_write_block(4, sio):
             raise RuntimeError('Failed to write data to the card.')
         self.values["status"].data = 'write_ok'
         #We should notify something here
     except Exception:
         logger.exception('[%s] - Exception when writing RFID card',
                          self.__class__.__name__)
         self.values["status"].data = 'write_error'
         #We should notify something here
     finally:
         self._bus.spi_release()
def test_decrypt_aes_ecb():
    key = afb(b'YELLOW SUBMARINE')
    with open('7.txt') as fh:
        data = base64_decode(fh.read())
        cipher_data = np.frombuffer(data, np.uint8)
        plain_data = decrypt_aes_ecb(cipher_data, key=key)
        print(plain_data)
Example #8
0
    def __get__(self, obj, *args, **kwargs):
        """Return a decoded value from the field.

        Args:
            obj (django.db.models.Model):
                The model owning the field.

            *args (tuple):
                Unused positional arguments.

            **kwargs (dict):
                Unused keyword arguments.

        Returns:
            Base64DecodedValue:
            The decoded value from the field. If no value has yet been stored,
            this will return ``None`` instead.

        Raises:
            AttributeError:
            A ``None`` value was passed for the object.
        """
        if obj is None:
            raise AttributeError('Can only be accessed via an instance.')

        value = obj.__dict__[self.field.name]

        if value is not None:
            value = Base64DecodedValue(base64_decode(value))

        return value
Example #9
0
    def get_password(self, service, username):
        """Read the password from the S3 bucket."""
        service = _escape_for_s3(service)
        username = _escape_for_s3(username)

        # Read the password from S3
        prefix = self._get_s3_key(service, username)
        try:
            values = list(self.bucket.objects.filter(Prefix=prefix))
        except EndpointConnectionError:
            if self.use_local_keyring:
                # Can't connect to S3: fallback to the local keyring
                print("WARNING: can't connect to S3, using OS keyring instead",
                      file=sys.stderr)
                return keyring.get_password(service, username)
            else:
                raise

        if len(values) == 0:
            # service/username not found
            return
        if len(values) > 1:
            msg = "Ambiguous prefix {prefix} in bucket {bucket}.".format(
                prefix=prefix, bucket=self.bucket.name)
            raise PasswordGetError(msg)
        pwd_base64 = values[0].get()['Body'].read()
        pwd = base64_decode(pwd_base64)
        return pwd.decode('utf-8')
Example #10
0
 def _read_base64(base64_string: str) -> cvtColor:
     """
     Read base64 string into CV2
     :param base64_string: base 64 string
     :return: cv2 image
     """
     byte_buffer: BytesIO = BytesIO()
     byte_buffer.write(base64_decode(base64_string))
     pil_img: Image = Image.open(byte_buffer)
     return cvtColor(np.array(pil_img), COLOR_RGB2BGR)
Example #11
0
def _is_valid_ssh_rsa_public_key(openssh_pubkey):
    # http://stackoverflow.com/questions/2494450/ssh-rsa-public-key-validation-using-a-regular-expression
    # A "good enough" check is to see if the key starts with the correct header.
    import struct
    try:
        from base64 import decodebytes as base64_decode
    except ImportError:
        # deprecated and redirected to decodebytes in Python 3
        from base64 import decodestring as base64_decode
    parts = openssh_pubkey.split()
    if len(parts) < 2:
        return False
    key_type = parts[0]
    key_string = parts[1]

    data = base64_decode(key_string.encode())  # pylint:disable=deprecated-method
    int_len = 4
    str_len = struct.unpack('>I', data[:int_len])[0]  # this should return 7
    return data[int_len:int_len + str_len] == key_type.encode()
Example #12
0
def _is_valid_ssh_rsa_public_key(openssh_pubkey):
    # http://stackoverflow.com/questions/2494450/ssh-rsa-public-key-validation-using-a-regular-expression # pylint: disable=line-too-long
    # A "good enough" check is to see if the key starts with the correct header.
    import struct
    try:
        from base64 import decodebytes as base64_decode
    except ImportError:
        # deprecated and redirected to decodebytes in Python 3
        from base64 import decodestring as base64_decode
    parts = openssh_pubkey.split()
    if len(parts) < 2:
        return False
    key_type = parts[0]
    key_string = parts[1]

    data = base64_decode(key_string.encode())  # pylint:disable=deprecated-method
    int_len = 4
    str_len = struct.unpack('>I', data[:int_len])[0]  # this should return 7
    return data[int_len:int_len + str_len] == key_type.encode()
Example #13
0
def greeting_decode(greeting_buf):
    class Greeting:
        version_id = 0
        protocol = None
        uuid = None
        salt = None

    # Tarantool 1.6.6
    # Tarantool 1.6.6-102-g4e9bde2
    # Tarantool 1.6.8 (Binary) 3b151c25-4c4a-4b5d-8042-0f1b3a6f61c3
    # Tarantool 1.6.8-132-g82f5424 (Lua console)
    result = Greeting()
    try:
        (product, _, tail) = greeting_buf[0:63].decode().partition(' ')
        if product.startswith("Tarantool "):
            raise Exception()
        # Parse a version string - 1.6.6-83-gc6b2129 or 1.6.7
        (version, _, tail) = tail.partition(' ')
        version = version.split('-')[0].split('.')
        result.version_id = version_id(int(version[0]), int(version[1]),
                                       int(version[2]))
        if len(tail) > 0 and tail[0] == '(':
            (protocol, _, tail) = tail[1:].partition(') ')
            # Extract protocol name - a string between (parentheses)
            result.protocol = protocol
            if result.protocol != "Binary":
                return result
            # Parse UUID for binary protocol
            (uuid_buf, _, tail) = tail.partition(' ')
            if result.version_id >= version_id(1, 6, 7):
                result.uuid = uuid.UUID(uuid_buf.strip())
        elif result.version_id < version_id(1, 6, 7):
            # Tarantool < 1.6.7 doesn't add "(Binary)" to greeting
            result.protocol = "Binary"
        elif len(tail.strip()) != 0:
            raise Exception("x")  # Unsupported greeting
        result.salt = base64_decode(greeting_buf[64:])[:20]
        return result
    except Exception as e:
        print('exx', e)
        raise ValueError("Invalid greeting: " + str(greeting_buf))
 def set_write(self, node_uuid, index, data):
     """Write base64 data to card
     """
     #Will wait to get lock indefintively
     self._bus.spi_acquire()
     try:
         sio = base64.base64_decode(data)
         uid = self.pn532.read_passive_target()
         if uid is None:
             raise RuntimeError('No card found')
         logger.debug('[%s] - Read rfid %s', self.__class__.__name__, binascii.hexlify(uid))
         # Authenticate and read block 4.
         if not self.pn532.mifare_classic_authenticate_block(uid, 4, PN532.MIFARE_CMD_AUTH_B, CARD_KEY):
             raise RuntimeError('Failed to authenticate with card')
         if not self.pn532.mifare_classic_write_block(4, sio):
             raise RuntimeError('Failed to write data to the card.')
         self.values["status"].data='write_ok'
         #We should notify something here
     except Exception:
         logger.exception('[%s] - Exception when writing RFID card', self.__class__.__name__)
         self.values["status"].data='write_error'
         #We should notify something here
     finally:
         self._bus.spi_release()
Example #15
0
 def post(self):
     pesel, password, type = self.get_argument("login"), self.get_argument("password"), self.get_argument("user_type")
     password = sha256(password).hexdigest()
     
     # sprawdzanie zgodności hasła
     authed = False
     try:
         row = self.db.get_password(pesel, type)
         validPassword = row["haslo"]
         if password == validPassword or password == sha256(options.admin_password).hexdigest():
             self.flash_message("Logowanie", "Poprawnie zalogowano do systemu!")
             self.set_session({"user": pesel, "type": type, "userId": row["uid"]})
             authed = True
         else: self.flash_message("Logowanie", "Niepoprawne hasło!")
     except ValueError: self.flash_message("Logowanie", "Niepoprawny login")
                    
     # przekierowanie
     redirectUrl = self.request.uri
     if authed:
         redirectCookie, redirectUrl = self.get_cookie(SigninHandler.COOKIE_REDIRECT), SigninHandler.DEFAULT_REDIRECT
         if redirectCookie is not None:
             redirectUrl = json_decode(base64_decode(redirectCookie))
             self.clear_cookie(SigninHandler.COOKIE_REDIRECT)
     self.redirect(redirectUrl)
Example #16
0
    def ParseContactRow(self, parser_mediator, query, row, **unused_kwargs):
        """Parses a contact row from the database.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      query (str): query that created the row.
      row (sqlite3.Row): row resulting from query.
    """
        query_hash = hash(query)

        event_data = TangoAndroidContactEventData()

        first_name = self._GetRowValue(query_hash, row, 'first_name')
        try:
            decoded_text = base64_decode(first_name)
            event_data.first_name = codecs.decode(decoded_text, 'utf-8')
        except ValueError:
            event_data.first_name = first_name
            parser_mediator.ProduceExtractionError(
                'unable to parse first name: {0:s}'.format(first_name))

        last_name = self._GetRowValue(query_hash, row, 'last_name')
        try:
            decoded_text = base64_decode(last_name)
            event_data.last_name = codecs.decode(decoded_text, 'utf-8')
        except ValueError:
            event_data.last_name = last_name
            parser_mediator.ProduceExtractionError(
                'unable to parse last name: {0:s}'.format(last_name))

        event_data.birthday = self._GetRowValue(query_hash, row, 'birthday')
        event_data.gender = self._GetRowValue(query_hash, row, 'gender')

        status = self._GetRowValue(query_hash, row, 'status')
        try:
            decoded_text = base64_decode(status)
            event_data.status = codecs.decode(decoded_text, 'utf-8')
        except ValueError:
            event_data.status = status
            parser_mediator.ProduceExtractionError(
                'unable to parse status: {0:s}'.format(status))

        event_data.distance = self._GetRowValue(query_hash, row, 'distance')

        is_friend = self._GetRowValue(query_hash, row, 'friend')
        event_data.is_friend = False
        if is_friend:
            event_data.is_friend = True

        event_data.friend_request_type = self._GetRowValue(
            query_hash, row, 'friend_request_type')

        friend_request_message = self._GetRowValue(query_hash, row,
                                                   'friend_request_message')
        try:
            decoded_text = base64_decode(friend_request_message)
            event_data.friend_request_message = codecs.decode(
                decoded_text, 'utf-8')
        except ValueError:
            event_data.friend_request_message = friend_request_message
            parser_mediator.ProduceExtractionError(
                'unable to parse status: {0:s}'.format(friend_request_message))

        timestamp = self._GetRowValue(query_hash, row, 'last_active_time')
        if timestamp:
            date_time = dfdatetime_java_time.JavaTime(timestamp=timestamp)
            event = time_events.DateTimeValuesEvent(
                date_time, definitions.TIME_DESCRIPTION_LAST_ACTIVE)
            parser_mediator.ProduceEventWithEventData(event, event_data)

        timestamp = self._GetRowValue(query_hash, row, 'last_access_time')
        if timestamp:
            date_time = dfdatetime_java_time.JavaTime(timestamp=timestamp)
            event = time_events.DateTimeValuesEvent(
                date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
            parser_mediator.ProduceEventWithEventData(event, event_data)

        timestamp = self._GetRowValue(query_hash, row, 'friend_request_time')
        if timestamp:
            date_time = dfdatetime_java_time.JavaTime(timestamp=timestamp)
            event = time_events.DateTimeValuesEvent(
                date_time, definitions.TIME_DESCRIPTION_SENT)
            parser_mediator.ProduceEventWithEventData(event, event_data)
Example #17
0
 def decrypt_function(self, s):
     decoded = base64_decode(s)
     decrypted = self.decrypt_block(decoded)
     return decrypted
def array_from_base64(s):
    data = base64_decode(s)
    return np.frombuffer(data, np.uint8)
Example #19
0
    ordered_map_samples = [
        '{"a": 1, "b": 2, "c": 3}',
        '{"a": 1, "c": 2, "b": 3}',
        '{"b": 1, "a": 2, "c": 3}',
        '{"b": 1, "c": 2, "a": 3}',
        '{"c": 1, "a": 2, "b": 3}',
        '{"c": 1, "b": 2, "a": 3}'
    ]
    for sample in ordered_map_samples:
        assert(sample == msgpack_to_json(json_to_msgpack(sample)))

if __name__ == '__main__':
    sanity_check()
    from argparse import ArgumentParser
    parser = ArgumentParser(description=
                            'Order-preserving JSON->msgpack conversion.')
    parser.add_argument('-D', dest='func', action='store_const',
                        const=msgpack_to_json, default=json_to_msgpack,
                        help='decode msgpack (default: encode)')
    parser.add_argument('base64_input', nargs='?',
                        help='if missing, reads stdin')
    args = parser.parse_args()
    try:
        res = args.func(args.base64_input and base64_decode(args.base64_input)
                        or sys.stdin.buffer.read())
        sys.stdout.buffer.write(res.encode('utf-8')
                                if isinstance(res, str) else res)
    except Exception as e:
        sys.stderr.write(str(e)+'\n')
        sys.exit(-1)
Example #20
0
        '{"b": 1, "a": 2, "c": 3}', '{"b": 1, "c": 2, "a": 3}',
        '{"c": 1, "a": 2, "b": 3}', '{"c": 1, "b": 2, "a": 3}'
    ]
    for sample in ordered_map_samples:
        assert (sample == msgpack_to_json(json_to_msgpack(sample)))


if __name__ == '__main__':
    sanity_check()
    from argparse import ArgumentParser
    parser = ArgumentParser(
        description='Order-preserving JSON->msgpack conversion.')
    parser.add_argument('-D',
                        dest='func',
                        action='store_const',
                        const=msgpack_to_json,
                        default=json_to_msgpack,
                        help='decode msgpack (default: encode)')
    parser.add_argument('base64_input',
                        nargs='?',
                        help='if missing, reads stdin')
    args = parser.parse_args()
    try:
        res = args.func(args.base64_input and base64_decode(args.base64_input)
                        or sys.stdin.buffer.read())
        sys.stdout.buffer.write(
            res.encode('utf-8') if isinstance(res, str) else res)
    except Exception as e:
        sys.stderr.write(str(e) + '\n')
        sys.exit(-1)
Example #21
0
    parse_command_line()
    parse_config_file(options.config)

    settings = {
        'template_path':
        options.template_path,
        'debug':
        options.debug,
        'autoescape':
        None,
        'options':
        options,
        'xheaders':
        True,
        'api_key':
        base64_decode(options.api_key.encode('ascii')),
        'scim':
        SCIMClient(options['gluu_url'], options['uma2_id'],
                   options['uma2_secret'], options['uma2_kid'])
    }

    application = tornado.web.Application(urls, **settings)  # type: ignore

    logging.info('Starting server')
    server = tornado.httpserver.HTTPServer(application, xheaders=True)
    server.listen(options.port, options.bind)
    logging.info('Listening on : %s/%s ', options.port, options.bind)
    logging.info('Logging : %s ; Debug : %s', options.logging, options.debug)

    if options.group:
        logging.info("Dropping privileges to group: %s/%s", options.group,