Exemplo n.º 1
0
def get_titlekey(remote, rightsId, keygeneration, files_list=None):
    if files_list == None:
        files_list = get_files_from_head(remote, remote.name)
    hasticket = False
    for i in range(len(files_list)):
        if (files_list[i][0]).endswith('.tik'):
            off1 = files_list[i][1]
            off2 = files_list[i][2]
            sz = files_list[i][3]
            trights = ((files_list[i][0])[:-4]).upper()
            if str(trights).upper() == str(rightsId).upper():
                hasticket = True
                break
    if hasticket == False:
        return False
    remote.rewind()
    remote.seek(off1, sz)
    buf = int(sz)
    try:
        data = remote.read(buf)
        tk = str(hx(data[0x180:0x190]))
        tk = tk[2:-1]
        encKey = bytes.fromhex(tk)
        titleKeyDec = Keys.decryptTitleKey(
            encKey, Keys.getMasterKeyIndex(keygeneration))
        return titleKeyDec
    except IOError as e:
        print(e, file=sys.stderr)
        return False
Exemplo n.º 2
0
def getEvents():
    courseNums = Keys.getCourses()
    API_URL, API_KEY = Keys.getAPIinfo()

    canvas = Canvas(API_URL, API_KEY)

    events = canvas.get_upcoming_events()
    assignments = []
    for event in events:
        try:
            due_date = datetime.datetime.strptime(
                event['assignment']['due_at'],
                "%Y-%m-%dT%H:%M:%SZ") - datetime.timedelta(hours=5)
        except KeyError:
            print("error adding:", event)
        else:
            # if due_date.hour > 18:
            #     due_date.replace(hour=18)

            try:
                label = courseNums[str(event['assignment']['course_id'])]
            except KeyError:
                label = str(event['assignment']['course_id'])

            assignment = [label, event['title'], due_date]
            assignments.append(assignment)

    return assignments
Exemplo n.º 3
0
def decode(ciph_data, keypath, password):
    private = Keys.read_key(keypath)
    private = Keys.decipher_key(password, private)
    k = private[6]
    clear_data = decipher_data(ciph_data, private)
    file_data = Conversions.int_list2bytes(clear_data, k >> 3)
    return file_data
Exemplo n.º 4
0
def encode_with_key(file_data, keypath):
    formatted_pb = Keys.read_key(keypath)
    public = Keys.deformat_key(formatted_pb)
    k = public[6]
    clear_data = Conversions.bytes2int_list(file_data, k >> 3)
    ciph_data = cipher_data(clear_data, public)
    return ciph_data
Exemplo n.º 5
0
def createAUser():
    groups = dict()
    N = 6
    username = request.form.get(
        'username')  #get the username that the user gave
    groupCode = ''.join(
        random.choices(string.ascii_uppercase + string.digits,
                       k=N))  #generate a random string for the room id
    private_key = Keys.genRSAKey()  # Generate a private key
    Keys.store_privKey(private_key)  # Store the private key locally
    public_key = private_key.public_key()  # Create a public key
    pKey = Keys.store_pubKey(public_key)  #Get the public key
    groups = {groupCode: [username]}
    users = {username: pKey}
    with open("users.json", "r") as read_file:
        usersFile = json.load(read_file)
        usersFile[username] = pKey
    with open("users.json", "w") as write_file:
        json.dump(usersFile, write_file)
    with open("groups.json", "r") as read_file:
        groupsFile = json.load(read_file)
        groupsFile[groupCode] = [username]
    with open("groups.json", "w") as write_file:
        json.dump(groupsFile, write_file)
    return render_template('creator.html',
                           groupCode=groupCode,
                           username=username)
Exemplo n.º 6
0
    def verify(self):
        ncaHeader = NcaHeader()
        ncaHeader.open(
            MemoryFile(self.ncaHeader, Type.Crypto.XTS,
                       uhx(Keys.get('header_key'))))

        id = ncaHeader.rightsId[0:16].decode().upper()
        if str(self.titleId) != id:
            raise IndexError('Title IDs do not match!  ' + str(self.titleId) +
                             ' != ' + id)

        decKey = Keys.decryptTitleKey(uhx(self.titleKey), ncaHeader.masterKey)

        pfs0 = Fs.Pfs0(self.sectionHeaderBlock)
        '''
		print('encKey = ' + str(self.titleKey))
		print('decKey = ' + str(hx(decKey)))
		print('master key = ' + str(ncaHeader.masterKey))
		print('ctr = ' + str(hx(pfs0.cryptoCounter)))
		print('offset = ' + str(self.pfs0Offset))
		'''

        mem = MemoryFile(self.pfs0Header,
                         Type.Crypto.CTR,
                         decKey,
                         pfs0.cryptoCounter,
                         offset=self.pfs0Offset)
        magic = mem.read()[0:4]
        if magic != b'PFS0':
            raise LookupError('Title Key is incorrect!')

        return True
Exemplo n.º 7
0
def renew_connection():
    print("getting new TOR connection")

    with Controller.from_port(port=Keys.tor_port()) as controller:
        controller.authenticate(password=Keys.tor_pass())
        controller.signal(Signal.NEWNYM)
        print("New TOR connection")
        print(session.get("http://httpbin.org/ip").text)
Exemplo n.º 8
0
def file_hash(remote, target, files_list=None):
    if files_list == None:
        files_list = get_files_from_head(remote, remote.name)
    else:
        files_list = files_list
    target2 = target[:-1] + 'z'
    indent = 1
    gamecard = False
    tabs = '\t' * indent
    sha = False
    sizef = False
    for i in range(len(files_list)):
        if str(files_list[i][0]).lower() == str(target).lower() or str(
                files_list[i][0]).lower() == str(target2).lower():
            nca_name = files_list[i][0]
            off1 = files_list[i][1]
            off2 = files_list[i][2]
            sz = files_list[i][3]
            break
    hblock = remote.read_at(off1, 0x200)
    sha = sha256(hblock).hexdigest()
    if nca_name.endswith('.ncz') or nca_name.endswith('.nca'):
        ncaHeader = NcaHeader()
        ncaHeader.open(
            MemoryFile(remote.read_at(off1, 0x400), Type.Crypto.XTS,
                       uhx(Keys.get('header_key'))))
    if nca_name.endswith('.ncz'):
        sizef = ncaHeader.size
    else:
        sizef = sz
    if nca_name.endswith('.ncz'):
        if ncaHeader.getgamecard() == 1:
            gamecard = True
        else:
            nca_id = ncaHeader.titleId
            if nca_id.endswith('000') or nca_id.endswith('800'):
                if str(ncaHeader.contentType) == 'Content.PROGRAM':
                    docheck = True
            else:
                if str(ncaHeader.contentType) == 'Content.DATA':
                    docheck = True
            if docheck == True:
                crypto1 = ncaHeader.getCryptoType()
                crypto2 = ncaHeader.getCryptoType2()
                if crypto2 > crypto1:
                    masterKeyRev = crypto2
                if crypto2 <= crypto1:
                    masterKeyRev = crypto1
                crypto = aes128.AESECB(
                    Keys.keyAreaKey(Keys.getMasterKeyIndex(masterKeyRev),
                                    ncaHeader.keyIndex))
                KB1L = ncaHeader.getKB1L()
                KB1L = crypto.decrypt(KB1L)
                if sum(KB1L) == 0:
                    gamecard = True
    return sha, sizef, gamecard
Exemplo n.º 9
0
 def removeTitleRightsnca(self, masterKeyRev, titleKeyDec):
     Print.info('titleKeyDec =\t' + str(hx(titleKeyDec)))
     Print.info('masterKeyRev =\t' + hex(masterKeyRev))
     Print.info('writing masterKeyRev for %s, %d' %
                (str(self._path), masterKeyRev))
     crypto = aes128.AESECB(
         Keys.keyAreaKey(Keys.getMasterKeyIndex(masterKeyRev),
                         self.header.keyIndex))
     encKeyBlock = crypto.encrypt(titleKeyDec * 4)
     self.header.setRightsId(0)
     self.header.setKeyBlock(encKeyBlock)
     Hex.dump(encKeyBlock)
Exemplo n.º 10
0
    def verify(self):
        ncaHeader = NcaHeader()
        ncaHeader.open(
            MemoryFile(self.ncaHeader, Type.Crypto.XTS,
                       uhx(Keys.get('header_key'))))

        id = ncaHeader.rightsId[0:16].decode().upper()
        if str(self.titleId) != id:
            raise IndexError('Title IDs do not match!  ' + str(self.titleId) +
                             ' != ' + id)

        decKey = Keys.decryptTitleKey(uhx(self.titleKey), ncaHeader.masterKey)

        pfs0 = Fs.Pfs0(self.sectionHeaderBlock)
        '''
		print('encKey = ' + str(self.titleKey))
		print('decKey = ' + str(hx(decKey)))
		print('master key = ' + str(ncaHeader.masterKey))
		print('ctr = ' + str(hx(pfs0.cryptoCounter)))
		print('offset = ' + str(self.pfs0Offset))
		'''

        if self.sectionHeaderBlock[8:12] == b'IVFC':
            #Hex.dump(self.sectionHeaderBlock)
            #Print.info(hx(self.sectionHeaderBlock[0xc8:0xc8+0x20]).decode('utf-8'))
            mem = MemoryFile(self.pfs0Header,
                             Type.Crypto.CTR,
                             decKey,
                             pfs0.cryptoCounter,
                             offset=self.pfs0Offset)
            data = mem.read()
            #Hex.dump(data)
            #print('hash = %s' % str(_sha256(data)))
            if hx(self.sectionHeaderBlock[0xc8:0xc8 +
                                          0x20]).decode('utf-8') == str(
                                              _sha256(data)):
                return True
            else:
                return False
        else:
            mem = MemoryFile(self.pfs0Header,
                             Type.Crypto.CTR,
                             decKey,
                             pfs0.cryptoCounter,
                             offset=self.pfs0Offset)
            magic = mem.read()[0:4]
            if magic != b'PFS0':
                raise LookupError('Title Key is incorrect!')

        return True
Exemplo n.º 11
0
    def do_safe(self, ser):
        if self.keys is None:
            self.keys = Keys.KeyPress(ser)

        try:
            if self.alive:
                self.do()
        except:
            if self.keys is None:
                self.keys = Keys.KeyPress(ser)
            print('interuppt')
            import traceback
            traceback.print_exc()
            self.keys.end()
            self.alive = False
Exemplo n.º 12
0
def main():
    global TRADE, POLONIEX, BITTREX, DATE, _MARGIN

    period = 1
    MARGIN = 6
    ICR = 1

    TIMES = 10

    # Opening File
    FILE = open("TEST1.txt", "a", 1)
    FILE.write(str(DATE) + '\t For ' + str(TIMES) + ' times \n\n')

    while TIMES > 0:
        ask_Poloniex, bid_Poloniex = poloniex()
        ask_Bittrex, bid_Bittrex = bittrex()
        client = Client(Keys.publicKey(), Keys.privateKey())
        tickers = client.get_orderbook_tickers()
        for i in tickers:
            if i['symbol'] == 'XLMBTC':
                print(i['askPrice'] + " " + i['bidPrice'])
                break
        for i in range(MARGIN, MARGIN * 3, ICR):
            I = i * _MARGIN
            BUY_ON_POLONIEX = ask_Poloniex - bid_Bittrex + I
            BUY_ON_BITTREX = ask_Bittrex - bid_Poloniex + I

            if BUY_ON_BITTREX < 0 or BUY_ON_POLONIEX < 0:
                print('POLONIEX : ' + FORMAT.format(BUY_ON_POLONIEX) +
                      ' with : ' + FORMAT.format(I))
                print('BITTREX : ' + FORMAT.format(BUY_ON_BITTREX) +
                      ' with : ' + FORMAT.format(I))

            if BUY_ON_POLONIEX < 0:
                print("TRY POLONIEX")
                _buy(FILE, ask_Poloniex, bid_Bittrex, I, POLONIEX)
            elif BUY_ON_BITTREX < 0:
                print("TRY BITTREX")
                _buy(FILE, ask_Bittrex, bid_Poloniex, I, BITTREX)

        if BUY_ON_BITTREX < 0 or BUY_ON_POLONIEX < 0:
            FILE.write("\n")
        print("TIME : " + str(TIMES))
        TIMES -= 1
        time.sleep(period)

    duration(FILE, DATE)
    FILE.close()
Exemplo n.º 13
0
def main():
    unique = Service.unique()
    if not unique: return

    settings = Keys.settings()
    with closing(NotificationIcon(settings)):
        Gtk.main()
Exemplo n.º 14
0
 def play_one_ball(self, ball_start_direction, show=False):
     game = gm.Game()
     if show == True:
         game.setup_pygame()
     game.ball.vel.x = game.ball.max_vel.x * ball_start_direction
     game.ball.vel.y = uniform(-game.ball.max_vel.y, game.ball.max_vel.y)
     while game.ball.vel.y < 0.1 and game.ball.vel.y > -0.1:
         game.ball.vel.y = uniform(-game.ball.max_vel.y,
                                   game.ball.max_vel.y)
     fail_alarm = 0
     play = True
     while play == True:
         game.convert_outputs(self.population_one[self.index_one].feedforward(game.get_inputs()), \
             self.population_two[self.index_two].feedforward(game.get_inputs()))
         game.update()
         collisions = game.collision()
         if collisions == True:
             self.population_one[self.index_one].fitness += 1
             break
         elif collisions == False:
             self.population_two[self.index_two].fitness += 1
             break
         if show == True:
             keys = ks.keys()
             self.index_one += keys[0]
             self.index_two += keys[1]
             print(self.index_one, self.index_two)
             game.clear()
             game.draw()
             game.flip()
             sleep(0.025)
         fail_alarm += 1
         if fail_alarm > 3000:
             print("fail alarm")
             break
Exemplo n.º 15
0
def main():
    # Argument parsing
    parser = argparse.ArgumentParser()
    parser.add_argument('--confdir',
                        action="store",
                        help="Customized certificates directory",
                        default=utils.get_basedir_default())
    parser.add_argument('--debug',
                        action="store_true",
                        help="Enable debugging")
    parser.add_argument('--list', action="store_true", help="List keys")
    parser.add_argument('--id',
                        action="store_true",
                        help="Get the key ID instead of the armored key")
    ns = parser.parse_args()

    if ns.debug:
        logging.basicConfig(level=logging.DEBUG)

    # Key manager
    keys = Keys.Manager(ns.confdir)

    # Print list
    if ns.list:
        print_keys(keys)
        raise SystemExit

    if ns.id:
        print keys.get_gpg_public_keyid()
        raise SystemExit

    # Public key bundle
    li = LinkInfo.LinkInfo()
    print li.get_uplink_info(ns.confdir)
Exemplo n.º 16
0
def main():
    # Argument parsing
    parser = argparse.ArgumentParser()
    parser.add_argument ('ID',        action="store",      help="ID of the link to ping")
    parser.add_argument ('--confdir', action="store",      help="Customized certificates directory", default=utils.get_basedir_default())
    parser.add_argument ('--debug',   action="store_true", help="Enable debugging")
    ns = parser.parse_args()

    if ns.debug:
        logging.basicConfig (level = logging.DEBUG)

    # Config
    config = Config.Config (ns.confdir)

    # Key manager
    keys = Keys.Manager (ns.confdir)

    # Client
    ping = Client.Ping (config, keys, ns.ID)

    n = 5
    while n > 0:
        ping.execute()
        time.sleep(1)
        n -= 1
Exemplo n.º 17
0
def get_sd_card_nca_key_source():
    try:
        key = Keys.get('sd_card_nca_key_source')
        key = bytes.fromhex(key)
        return key
    except:
        return False
def threefish_chiffrement(file_data_list, mode, key_len, passwd_user, file_key):
    key, keyuser = keygen(key_len)
    tab_key = keygenturn(key)
    # cipher the key using the password given by the user
    cipher_key = Keys.cipher_key(passwd_user, key)
    # writing cipher key in the specific file
    IO.write_2D_list(file_key, cipher_key, 8)

    Keys.print_key(key_len, keyuser)

    padded_file = Util.ajout_padding(file_data_list, key_len, 64)

    if mode == 1:
        return ecb_threefish_cipher(padded_file, tab_key)
    else:
        return cbc_threefish_cipher(padded_file, tab_key, key_len)
Exemplo n.º 19
0
def get_SD_SEED():
    try:
        key = Keys.get('sd_seed')
        key = bytes.fromhex(key)
        return key
    except:
        return False
Exemplo n.º 20
0
    def printInfo(self, maxDepth=3, indent=0):
        tabs = '\t' * indent

        rightsId = format(self.getRightsId(), 'X').zfill(32)
        titleId = rightsId[0:16]
        titleKey = format(self.getTitleKeyBlock(), 'X').zfill(32)

        Print.info('\n%sTicket\n' % (tabs))
        super(Ticket, self).printInfo(maxDepth, indent)
        Print.info(tabs + 'signatureType = ' + str(self.signatureType))
        Print.info(tabs + 'keyType = ' + str(self.keyType))
        Print.info(tabs + 'masterKeyRev = ' + str(self.masterKeyRevision))
        Print.info(tabs + 'ticketId = ' + str(self.ticketId))
        Print.info(tabs + 'deviceId = ' + str(self.deviceId))
        Print.info(tabs + 'rightsId = ' + rightsId)
        Print.info(tabs + 'accountId = ' + str(self.accountId))
        Print.info(tabs + 'titleId = ' + titleId)
        Print.info(tabs + 'titleKey = ' + titleKey)
        Print.info(tabs + 'titleKeyDec = ' + str(
            hx(
                Keys.decryptTitleKey(
                    (self.getTitleKey()), self.masterKeyRevision))))

        try:
            if blockchain.verifyKey(titleId, titleKey):
                tkeyStatus = 'VERIFIED'
            else:
                tkeyStatus = 'BAD KEY'
        except BaseException as e:
            tkeyStatus = 'UNKNOWN - ' + str(e)
            raise

        Print.info(tabs + 'titleKeyStatus = ' + tkeyStatus)
Exemplo n.º 21
0
    def keyPressEvent(self, event):
        if event.modifiers() & QtCore.Qt.ControlModifier and event.key() == QtCore.Qt.Key_Control:
            if self.ctrlActivated:
                self.lblCTRL.setPixmap(QtGui.QPixmap(_fromUtf8(":/images/ctrl_inactive.png")))
                self.ctrlActivated = False
            else:
                self.lblCTRL.setPixmap(QtGui.QPixmap(_fromUtf8(":/images/ctrl_active.png")))
                self.ctrlActivated = True

        if event.modifiers() & QtCore.Qt.AltModifier and event.key() == QtCore.Qt.Key_Alt:
            if self.altActivated:
                self.lblAlt.setPixmap(QtGui.QPixmap(_fromUtf8(":/images/alt_inactive.png")))
                self.altActivated = False
            else:
                self.lblAlt.setPixmap(QtGui.QPixmap(_fromUtf8(":/images/alt_active.png")))
                self.altActivated = True

        if event.modifiers() & QtCore.Qt.ShiftModifier and event.key() == QtCore.Qt.Key_Shift:
            if self.shiftActivated:
                self.lblShift.setPixmap(QtGui.QPixmap(_fromUtf8(":/images/shift_inactive.png")))
                self.shiftActivated = False
            else:
                self.lblShift.setPixmap(QtGui.QPixmap(_fromUtf8(":/images/shift_active.png")))        
                self.shiftActivated = True

        try:
            key = Keys.getKey(event.key())
            if key is not None and re.match('^[A-Z0-9]+$', key) is not None:
                self.lblKey.setText(key)
                self.hotkey = key
        except UnicodeEncodeError:
            pass
Exemplo n.º 22
0
 def printInfo(self, indent=0):
     tabs = '\t' * indent
     Print.info('\n%sTicket\n' % (tabs))
     super(Ticket, self).printInfo(indent)
     Print.info(tabs + 'signatureType = ' + str(self.signatureType))
     Print.info(tabs + 'keyType = ' + str(self.keyType))
     Print.info(tabs + 'masterKeyRev = ' + str(self.getMasterKeyRevision()))
     Print.info(tabs + 'ticketId = ' + str(self.ticketId))
     Print.info(tabs + 'deviceId = ' + str(self.deviceId))
     Print.info(tabs + 'rightsId = ' + hex(self.getRightsId()))
     Print.info(tabs + 'accountId = ' + str(self.accountId))
     Print.info(tabs + 'titleKey = ' + hex(self.getTitleKeyBlock()))
     Print.info(tabs + 'titleKeyDec = ' + str(
         hx(
             Keys.decryptTitleKey((self.getTitleKey()), (
                 Keys.getMasterKeyIndex(self.masterKeyRevision))))))
Exemplo n.º 23
0
Arquivo: main.py Projeto: MrVi/crypto
def newCryptosystem(m, t, n, field_polynom, goppa_roots, e):
    key_generation_time = 0
    encryption_time = 0
    decryption_time = 0
    """Field Creation"""
    nf = FieldClass.FieldG(m, t, field_polynom)
    nf.printAboutField()
    nf.createAllElements()
    nf.printAllElem()
    """Goppa polynom creation"""
    gm = GoppaClass.GoppaPoly(nf)
    gm.chooseRoots(nf, goppa_roots)
    #gm.printGoppa()
    """key generation """
    start_t = datetime.now()
    key = Keys.Key(nf, n)
    key.generateKeys(nf, gm)
    finish_t = datetime.now()
    key.printAll()
    key_generation_time = finish_t - start_t
    """encryption"""
    """decryption"""

    print('Work time for keys generation: ', key_generation_time)
    print('Work time for encryption: ', encryption_time)
    print('Work time for decryption: ', decryption_time)
Exemplo n.º 24
0
    def link_add(self, cert_filename, id_name):
        # Read key
        uplink_info = self.__read_cert(cert_filename)

        # Add key to keyring
        keys = Keys.Manager(self.conf_basedir)
        import_result = keys.add_gpg_key(uplink_info['key'])

        fingerprint = import_result.fingerprints[0]
        key = keys.get_gpg_key_by_fingerprint(fingerprint)

        # Add the entry
        dup = False
        for l in self.config.get('links', []):
            if l['id'] == id_name or \
               l['keyid'] == key['keyid']:
                dup = True
                break

        if not dup:
            entry = {
                'keyid': key['keyid'],
                'id': id_name,
            }

            url = uplink_info.get('public_url')
            if url:
                entry['url'] = url

            links = self.config.get('links', [])
            links.append(entry)
            self.config['links'] = links
Exemplo n.º 25
0
def get_tor_session():
    global session, count
    count += 1

    session = requests.session()
    session.proxies = {'http': Keys.tor_proxy(), 'https': Keys.tor_proxy()}
    if count == 1:
        print("Connected to TOR proxy")
        print("Getting IP")
        ip = json.loads(session.get("http://httpbin.org/ip").text)
        print(ip["origin"])
        print("Getting location")
        location_url = "https://ipapi.co/" + ip["origin"] + "/json/"
        location = json.loads(requests.get(location_url).text)
        print(location["country_name"])
        count += 1
    return session
Exemplo n.º 26
0
def joinAGroup():
    roomID = request.form.get('roomID')
    username = request.form.get('username')
    private_key = Keys.genRSAKey()
    Keys.store_privKey(private_key)
    public_key = private_key.public_key()
    pKey = Keys.store_pubKey(public_key)
    with open("groups.json") as read_file:
        groupsFile = json.load(read_file)
        groupsFile[roomID].append(username)
    with open("groups.json", "w") as write_file:
        json.dump(groupsFile, write_file)
    with open("users.json", "r") as read_file:
        usersFile = json.load(read_file)
        usersFile[username] = pKey
    with open("users.json", "w") as write_file:
        json.dump(usersFile, write_file)
Exemplo n.º 27
0
 def __init__(self,title):
     goodreads = Keys.GoodReads()
     self.title = title
     self.url1 = "https://www.goodreads.com/book/title/?format=xml&key="
     self.url2 = "&title="
     self.finalurl = self.url1+goodreads.key()+self.url2+self.title
     page = urllib2.urlopen(self.finalurl)
     soup = BeautifulSoup(page)
     self.author_name = soup.find("name")
     self.average_rating = soup.average_rating
Exemplo n.º 28
0
    def get_uplink_info(self, confdir):
        # Get certificate
        keys = Keys.Manager(confdir)
        cert = str(keys.get_gpg_public_key())

        # Get the rest of the relevant information
        config = Config.Config(confdir)
        info = config.get_uplink_info()
        info['key'] = cert

        # JSON'ify
        return json.dumps(info)
Exemplo n.º 29
0
def get_new_cryptoblock(ncaHeader, newMasterKeyRev,encKeyBlock,t):
	indent = 1
	tabs = '\t' * indent
	indent2 = 2
	tabs2 = '\t' * indent2
	
	masterKeyRev = ncaHeader.getCryptoType2()	

	if type(ncaHeader) == NcaHeader():
		if ncaHeader.getCryptoType2() != newMasterKeyRev:
			t.write(tabs + '-----------------------------------')
			t.write(tabs + 'Changing keygeneration from %d to %s' % ( ncaHeader.getCryptoType2(), str(newMasterKeyRev)))
			t.write(tabs + '-----------------------------------')
			if sum(encKeyBlock) != 0:
				key = Keys.keyAreaKey(Keys.getMasterKeyIndex(masterKeyRev),ncaHeader.keyIndex)
				t.write(tabs2 + '+ decrypting with %s (%d, %d)' % (str(hx(key)), Keys.getMasterKeyIndex(masterKeyRev), ncaHeader.keyIndex))
				crypto = aes128.AESECB(key)
				decKeyBlock = crypto.decrypt(encKeyBlock)
				key = Keys.keyAreaKey(Keys.getMasterKeyIndex(newMasterKeyRev),ncaHeader.keyIndex)
				t.write(tabs2 + '+ encrypting with %s (%d, %d)' % (str(hx(key)), Keys.getMasterKeyIndex(newMasterKeyRev), ncaHeader.keyIndex))
				crypto = aes128.AESECB(key)
				reEncKeyBlock = crypto.encrypt(decKeyBlock)
				encKeyBlock = reEncKeyBlock
			if newMasterKeyRev >= 3:
				crypto1=2
				crypto2=newMasterKeyRev
			if newMasterKeyRev == 2:
				crypto1=2
				crypto2=0				
			if newMasterKeyRev < 2:
				crypto1=newMasterKeyRev
				crypto2=0							
			return encKeyBlock,crypto1,crypto2
	return encKeyBlock,ncaHeader.getCryptoType(),ncaHeader.getCryptoType2()			
Exemplo n.º 30
0
	def removeTitleRights(self):
		if not Titles.contains(self.titleId):
			raise IOError('No title key found in database! ' + self.titleId)

		ticket = self.ticket()
		masterKeyRev = ticket.getMasterKeyRevision()
		titleKeyDec = Keys.decryptTitleKey(ticket.getTitleKeyBlock().to_bytes(16, byteorder='big'), Keys.getMasterKeyIndex(masterKeyRev))
		rightsId = ticket.getRightsId()

		Print.info('rightsId =\t' + hex(rightsId))
		Print.info('titleKeyDec =\t' + str(hx(titleKeyDec)))
		Print.info('masterKeyRev =\t' + hex(masterKeyRev))



		for nca in self:
			if type(nca) == Nca:
				if nca.header.getRightsId() != 0:
					if nca.header.masterKeyRev != masterKeyRev:
						print('WARNING!!! Mismatched masterKeyRevs!')
						print(f"{str(nca._path)} - {nca.header.masterKeyRev}")	
						print(f"{str(ticket._path)} - {masterKeyRev}")

		ticket.setRightsId(0)

		for nca in self:
			if type(nca) == Nca:
				if nca.header.getRightsId() == 0:
					continue

				kek = Keys.keyAreaKey(Keys.getMasterKeyIndex(masterKeyRev), nca.header.keyIndex)
				Print.info('writing masterKeyRev for %s, %d' % (str(nca._path),  masterKeyRev))
				Print.info('kek =\t' + hx(kek).decode())
				crypto = aes128.AESECB(kek)

				encKeyBlock = crypto.encrypt(titleKeyDec * 4)
				nca.header.setRightsId(0)
				nca.header.setKeyBlock(encKeyBlock)
				Hex.dump(encKeyBlock)
Exemplo n.º 31
0
    def run(self):
        if PROFILING:
            iter = 0
        while not self.quit:
            self.ticks += 1
            self.time = time.clock()
            
            self.read_game.render()
            self.frame.BeginPaint()
            Keys.render()
            self.tracker.render()
            
            self.weapon_names.render()
            self.rage.render()
            self.status.render()
            self.esp.render()
            self.radar.render()
            self.bigradar.render()
            self.crosshair.render()
            self.bot.render()
            self.ammo_counter.render()
            self.autostab.render()
            self.c4.render()
            self.cooking.render()
            self.killstreak.render()
            self.visual_mouse.render()
            self.sprites.render()
            #
            self.webstats.render()
            self.inspector.render()
            # now run scheduled coroutines
            self.sched.mainloop_1()
            #
            self.frame.EndPaint()

            time.sleep(self.sleep_interval)                                   # avoid eating up all CPU
            if PROFILING:
                iter += 1
                if iter > 5000 :return      # 1 iteration only
Exemplo n.º 32
0
    def __init__(self):

        # Counter
        self.counter = 0

        # Random
        self.random = 0

        # Errorlog
        self.error_active = True
        self.errorlog = Functions.Functions(None, True)

        # Keys
        self.key = Keys.Keys()

        # Top menu
        self.topProsieben = "TopProsieben.png"
        self.topSixx = "TopSixx.png"
        self.topHerz = "TopHerz.png"
        self.topHome = "TopHome.png"
        # Top active
        self.topHomeActive = "TopHomeActive.png"
        self.topProsiebenActive = "TopProsiebenActive.png"
        self.topSateinsActive = "TopSateinsActive.png"
        self.topKabelActive = "TopKabelActive.png"
        self.topSixxActive = "TopSixxActive.png"
        self.topMaxxActive = "TopMaxxActive.png"
        self.topGoldActive = "TopGoldActive.png"
        self.topHerzActive = "TopHerzActive.png"
        self.topSettingsActive = "TopSettingsActive.png"
        # Top selected Fett
        self.topHomeSelected1 = "TopHomeSelected.png"
        self.topProsiebenSelected1 = "TopProsiebenSelected.png"
        self.topSateinsSelected1 = "TopSateinsSelected.png"
        self.topKabelSelected1 = "TopKabelSelected.png"
        self.topSixxSelected1 = "TopSixxSelected.png"
        self.topMaxxSelected1 = "TopMaxxSelected.png"
        self.topGoldSelected1 = "TopGoldSelected.png"
        self.topHerzSelected1 = "TopHerzSelected.png"
        self.topSettingsSelected1 = "TopSettingsSelected.png"
        # Top selected not Fett
        self.topHomeSelected2 = "TopHomeSelected2.png"
        self.topProsiebenSelected2 = "TopProsiebenSelected2.png"
        self.topSateinsSelected2 = "TopSateinsSelected2.png"
        self.topKabelSelected2 = "TopKabelSelected2.png"
        self.topSixxSelected2 = "TopSixxSelected2.png"
        self.topMaxxSelected2 = "TopMaxxSelected2.png"
        self.topGoldSelected2 = "TopGoldSelected2.png"
        self.topHerzSelected2 = "TopHerzSelected2.png"
        self.topSettingsSelected2 = "TopSettingsSelected2.png"
Exemplo n.º 33
0
 def test_search_key(self):
     with self.assertRaises(pubsublogger.exceptions.NoChannelError):
         Keys.search_key(self.paste)
Exemplo n.º 34
0
from rauth import OAuth2Service
import Keys
import requests
import json

accessToken = Keys.getValue("access_token")

def jsonify(url):
    data = requests.get(url)

    content = data.content

    j = json.loads(content)

    return j

def getID(artist):
    url = "https://api.genius.com/search?access_token=" + accessToken + "&q=" + artist

    j = jsonify(url)

    artist_id = json.dumps(j["response"]["hits"][0]["result"]["primary_artist"]["id"], sort_keys=True, indent=4)

    return artist_id


def getPopularSongs(artistID):
    songList = []
    url = "https://api.genius.com/artists/" + str(artistID) + "/songs?access_token=" + accessToken + "&sort=popularity&per_page=20"

    j = jsonify(url)
Exemplo n.º 35
0
 def test_search_key(self):
     with self.assertRaises(NameError):
         publisher.port = 6380
         publisher.channel = 'Script'
         Keys.search_key(self.paste)