Example #1
0
def readKeys():
    f = open('keys/keys.pem', 'r')
    file = f.read()
    f.close()

    keylist = []
    pksignlist = []

    start = 0
    while '-----BEGIN RSA PRIVATE KEY-----' in file[start:]:
        s = file.find('-----BEGIN RSA PRIVATE KEY-----', start)
        e = file.find('-----END RSA PRIVATE KEY-----', start) + 29 + 1

        sk = file.find('-----BEGIN MASTER KEY SIGN-----', start) + 32
        ek = file.find('-----END MASTER KEY SIGN-----', start) - 1

        keylist.append(RSA.importKey(file[s:e]))
        pksignlist.append(int(file[sk:ek]))
        start = ek + 20

    kh = KeyHandler(keylist[0], pksignlist[0], masterKey.publickey())

    # This is the function
    publickey = KeyHandler.keyFromString(keylist[1])
    print(publickey.exportKey())
    publickeyHash = SHA256.new(publickey.exportKey()).digest()
    return masterKey.publickey().verify(publickeyHash, (pksignlist[1], None))
Example #2
0
 def __init__(self):
     '''
     Constructor
     '''
     self.__mouseHandler = MouseHandler()
     self.__keyHandler = KeyHandler()
     # TODO: CONSIDER IGNORING EVENTS AND PASSING STRAIGHT TO KEYHANDLER/MOUSEHANDLER
     # TODO: MERGE KEY/MOUSE HANDLER INTO INPUTHANDLER?? BETTER CLASS NAME??
     self.__mouseHandler.RegisterEvents()
     self.__keyHandler.RegisterEvents()
Example #3
0
def deleteUser( app, correo ):
    if not correo.strip():
        app.key_notifications.showError( "Se debe seleccionar un correo si se desea borrar un usuario." )
    else:
        result = messagebox.askquestion("Borrar usuario", "¿Realmente desea borrar el usuario '" + correo + "'?", icon='warning')
        if result == 'yes':
            try:
                KeyHandler.deleteKey( correo )
            except Exception as msg:
                app.key_notifications.showError( msg )
            app.resetApp()
            app.users = KeyHandler.getUsers()
            app.keyList.deleteList()
            app.keyList.insertList( app.users )
            app.key_notifications.showSuccess( "Se ha borrado el usuario '" + correo + "' correctamente." )
Example #4
0
def addEditUser( app, correo, key, current ):
    if not correo.strip():
        app.key_notifications.showError( "El correo no puede estar vacio." )
    elif not key.strip():
        app.key_notifications.showError( "La clave no puede estar vacia." )
    else:
        try:
            KeyHandler.setKey( correo, key, current )
        except Exception as msg:
            app.key_notifications.showError( msg )
        app.resetApp()
        app.users = KeyHandler.getUsers()
        app.keyList.deleteList()
        app.keyList.insertList( app.users )
        app.key_notifications.showSuccess( "Se ha creado el usuario '" + correo + "' correctamente." )
Example #5
0
def comprimirArchivos( app ):
    """
    Crea un nuevo 'thread' para ejecutar la funcionalidad del programa
    """
    app.resume.hide()
    try:
        app.key = KeyHandler.getKey()
    except Exception as msg:
        app.importantNotifications.show(msg)
        app.key = None
    if app.key is not None:
        if len(app.files) == 0:
            app.notifications.showError( "No se han seleccionado archivos." )
        else:
            if not app.inputNewName.get().strip() and not app.replaceFiles and not app.keep_name:
                app.notifications.showError( "El campo de texto no puede estar vacio." )
            else:
                app.standByApp()
                app.pbComprimidos.show()
                thread = Thread(
                    name = "thr_comprimir",
                    target = comprimir,
                    args = (app,)
                )
                thread.start()
                checkThread( app, thread )
    else:
        app.notifications.showError( "Se debe elegir una clave de producto." )
Example #6
0
def readKeys():
    f = open('keys/keys.pem','r')
    file = f.read()
    f.close()

    keylist = []
    pksignlist = []

    start = 0
    while '-----BEGIN RSA PRIVATE KEY-----' in file[start:]:
        s = file.find('-----BEGIN RSA PRIVATE KEY-----', start)
        e = file.find('-----END RSA PRIVATE KEY-----', start) + 29 + 1

        sk = file.find('-----BEGIN MASTER KEY SIGN-----', start) + 32
        ek = file.find('-----END MASTER KEY SIGN-----', start) - 1

        keylist.append(RSA.importKey(file[s:e]))
        pksignlist.append(int(file[sk:ek]))
        start = ek + 20

    kh = KeyHandler(keylist[0], pksignlist[0], masterKey.publickey())

    # This is the function
    publickey = KeyHandler.keyFromString(keylist[1])
    print(publickey.exportKey())
    publickeyHash = SHA256.new(publickey.exportKey()).digest()
    return masterKey.publickey().verify(publickeyHash, (pksignlist[1], None))
Example #7
0
 def getKeyPair(self):
     if self.keylist.__len__() == 0:
         sys.exit(
             'All 200 keys are in use. Create more keys with generateKeys.py'
         )
     (key, pksign) = self.keylist.pop()
     return KeyHandler(key, pksign, self.masterkey.publickey())
Example #8
0
class Input(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.__mouseHandler = MouseHandler()
        self.__keyHandler = KeyHandler()
        # TODO: CONSIDER IGNORING EVENTS AND PASSING STRAIGHT TO KEYHANDLER/MOUSEHANDLER
        # TODO: MERGE KEY/MOUSE HANDLER INTO INPUTHANDLER?? BETTER CLASS NAME??
        self.__mouseHandler.RegisterEvents()
        self.__keyHandler.RegisterEvents()

    # Triggers when a key is depressed
    def OnKeyDown(self, key, x, y):
        data = MouseData(key, True, x, y)
        Events.FireEvent("KEYPRESS", data)

    # Triggers when a key is happy
    def OnKeyUp(self, key, x, y):
        data = MouseData(key, False, x, y)
        Events.FireEvent("KEYPRESS", data)

    def OnMousePress(self, button, state, scrx, scry):
        data = MouseData(button, state == 0, scrx, scry)
        Events.FireEvent("MOUSEPRESS", data)

    def OnMouseMove(self, scrx, scry):
        data = MouseData(0, 0, scrx, scry)
        Events.FireEvent("MOUSEMOVE", data)
Example #9
0
File: PyKey.py Project: gehel/pykey
    def __init__(self, device_name, mod_mapping, key_mapping, print_keys=False):

        self._handler = KeyHandler(mod_mapping, key_mapping)
        virtual_mods = set()

        for v_mods in key_mapping.keys():
            virtual_mods.update(v_mods)

        self._key_listener = KeyListener(
            device_name=device_name,
            handler=self._handler,
            mods=mod_mapping.keys(),
            virtual_mods=frozenset(virtual_mods),
            print_keys=print_keys)
Example #10
0
File: PyKey.py Project: gehel/pykey
class PyKey(object):
    """Keyboard handler for AlphaGripp"""

    def __init__(self, device_name, mod_mapping, key_mapping, print_keys=False):

        self._handler = KeyHandler(mod_mapping, key_mapping)
        virtual_mods = set()

        for v_mods in key_mapping.keys():
            virtual_mods.update(v_mods)

        self._key_listener = KeyListener(
            device_name=device_name,
            handler=self._handler,
            mods=mod_mapping.keys(),
            virtual_mods=frozenset(virtual_mods),
            print_keys=print_keys)

    def start(self):
        self._key_listener.start()

    def close(self):
        self._key_listener.close()
        self._handler.close()
def main():
    '''
    The block size is 20 x 20 pixels
    There are magic numbers everywhere, which means this is not very maintainable at the moment
    Also... wall-o-text
    '''
    # Initialize
    pygame.init()
    screenSize = (350, 400)
    screen = pygame.display.set_mode(screenSize)
    pygame.display.set_caption('Destroy all blocks! DO EEET!')
    pygame.mouse.set_visible(False)

    # Create the background
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    backgroundColor = (250, 250, 250)
    background.fill(backgroundColor)

    # Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Prepare game objects
    clock = pygame.time.Clock()
    keyHandler = KeyHandler()
    board = Board((10, 21))
    board.addTetramino(Pieces.getRandomName())

    # Text stuff
    textX = 210
    scoreY = 150
    levelY = 220
    scoreHeight = 15
    headerHeight = 25
    fontFile = 'resources/interstate-black.ttf'

    # Score
    scoreFont = pygame.font.Font(fontFile, scoreHeight)
    scoreSurface = scoreFont.render(str(board.score), 1, (25, 25, 25))
    scorePosition = (textX, scoreY)

    # Level
    levelSurface = scoreFont.render(str(board.blockSpeed), 1, (25, 25, 25))
    levelPosition = (textX, levelY)

    # Score label
    headerFont = pygame.font.Font(fontFile, headerHeight)
    scoreHeader = headerFont.render('Score:', 1, (50, 120, 200))

    # Level label
    levelHeader = headerFont.render('Level:', 1, (200, 50, 0))

    # Piece preview
    piecePreview = pygame.Surface((80, 40))
    piecePreview = piecePreview.convert()
    piecePreview.fill(backgroundColor)
    previewPositionLocal = (0, 0)
    previewPositionGlobal = (textX, 40)
    tetramino = Tetramino(Pieces.getRandomName(), previewPositionLocal, 20)
    tetramino.draw(piecePreview)

    # We need to whiteout the score and level text regions before each new rendering of it
    scoreEraser = pygame.Surface((140, scoreHeight))
    scoreEraser = scoreEraser.convert()
    scoreEraser.fill(backgroundColor)
    levelEraser = pygame.Surface((140, scoreHeight))
    levelEraser = levelEraser.convert()
    levelEraser.fill(backgroundColor)

    # Divides the board space from the information space
    divider = pygame.Surface((5, 400))
    divider = divider.convert()
    divider.fill((125, 125, 125))

    # Blit All the Things!
    background.blit(divider, (200, 0))
    background.blit(scoreHeader, (textX, scoreY - 30))
    background.blit(scoreEraser, scorePosition)
    background.blit(levelHeader, (textX, levelY - 30))
    background.blit(levelEraser, levelPosition)
    background.blit(scoreSurface, scorePosition)
    background.blit(levelSurface, levelPosition)
    background.blit(piecePreview, (textX, 40))
    pygame.display.flip()

    cooldownCounter = 0
    cooldownMax = 30
    lineClearCounter = 0
    lineClearDelay = 10
    collision = False
    gameOver = False
    mainLoopRun = True
    exitProgram = False

    # Main Loop
    while mainLoopRun:
        clock.tick(60)

        # Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                mainLoopRun = False
                exitProgram = True

        # Quick exit for ESC key
        if pygame.key.get_pressed()[pygame.K_ESCAPE]:
            mainLoopRun = False
            exitProgram = True

        # Delay between collisions (and line clears) and the next piece getting loaded
        if collision:
            if lineClearCounter >= lineClearDelay:
                lineClearCounter = 0
                collision = False
                gameOver = board.addTetramino(tetramino.name)
                tetramino = Tetramino(Pieces.getRandomName(), previewPositionLocal, 20)
                piecePreview.fill(backgroundColor)  # erase it before getting the next one
                tetramino.draw(piecePreview)
            else:
                lineClearCounter += 1

        # Move things based on current state
        if not gameOver and not collision:
            # Hard Drop
            if pygame.key.get_pressed()[pygame.K_SPACE]:
                board.hardDrop()
                collision = True
            else:
                keyHandler.handleKeys(pygame.key.get_pressed(), board)
                collision = board.drop()

        # Close game if it ended after a period of time
        if cooldownCounter >= cooldownMax:
            mainLoopRun = False

        if gameOver:
            cooldownCounter += 1

        # Draw everything
        scoreSurface = scoreFont.render(str(board.score), 1, (25, 25, 25))
        levelSurface = scoreFont.render(str(board.blockSpeed), 1, (25, 25, 25))
        background.blit(scoreEraser, scorePosition)
        background.blit(scoreSurface, scorePosition)
        background.blit(levelEraser, levelPosition)
        background.blit(levelSurface, levelPosition)
        background.blit(piecePreview, previewPositionGlobal)
        screen.blit(background, (0, 0))
        board.draw(screen)
        pygame.display.flip()

    # Game over
    endGameSurface = pygame.Surface(screenSize, pygame.SRCALPHA)
    endGameSurface.fill((125, 125, 125, 100))
    gameOverText = headerFont.render('GAME OVER', 1, (0, 0, 0))
    endGameSurface.blit(gameOverText, (100, 175))
    screen.blit(endGameSurface, (0, 0))
    pygame.display.flip()

    # Wait for user to exit the program
    while not exitProgram:
        for event in pygame.event.get():
            if event.type == QUIT:
                exitProgram = True
        if pygame.key.get_pressed()[pygame.K_ESCAPE]:
            exitProgram = True
    pygame.quit()
Example #12
0
from terrain.Terrain import *

from Utils import *
"""
Testing Assets:

"""

pygame.init()
screen = pygame.display.set_mode((600, 600), RESIZABLE)
pygame.display.set_caption("Game")

player = Player(0, 0, 0)

interactionHandler = InteractionHandler(player)
keyHandler = KeyHandler(player)

entityHandler = EntityHandler(player)
entityHandler.add_entity(Rock(100, 100, 0))
entityHandler.add_entity(LittleRock(100, 200, 0))
entityHandler.add_entity(Rick(100, 0, 0))

tileHandler = TileHandler()
chunkHandler = ChunkHandler()


def tick():
    # interaction handler for player interaction
    # chunk handler for terrain collision
    entityHandler.update(interactionHandler, chunkHandler)
Example #13
0
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',
                    level=logging.INFO)

# Some global switches for debugging use only
isDebug = False

itchat.auto_login(True, enableCmdQR=2)

settingPlugin = BotSetting()  # 机器人设置
privateChatPlugin = PrivateChat()  # 私聊调用 tuling
sysReminderPlugin = SysReminder()  # 红包 新成员 撤回
historyPlugin = HistoryRecorder()  # 记录消息
plugins = [
    #PaiDuiHook(),
    KeyHandler(),
    GroupTagCloud(),
    ActivityInfo(),
    QAPlugin(),
    LastSpeakTime(),
    MemberDistribution(),
    Tuling(),
    MsDuilian(),
    BingText2Speech(),
    ChengYuJieLong(),
    LrcCreator(),
    EasterEgg(),
    # VSGame(),
    MicoIce(),
    #GroupMessageForwarder([ '二群', '三群' ], [ 'AI二群测试中', 'AI三群测试' ])
]