Exemplo n.º 1
0
def cred(tower, context):
    try:
        file_csv = open('./text.csv', 'r')
        user = "******"
        password = "******"
        flag = 0
        for line in file_csv:
            row = line.split("::!::")
            if ((str(tower).lower()) == row[2]):
                row[3] = row[3].replace("\n", "")
                data = row[3].split(",")
                #print(data)
                if (row[3] == "*"):
                    user = encryption.decrypt("AutoFact", row[0])
                    password = encryption.decrypt("AutoFact", row[1])
                for i in data:
                    if (str(i) == str(context)):
                        #print(i)
                        user = encryption.decrypt("AutoFact", row[0])
                        password = encryption.decrypt("AutoFact", row[1])
                        flag = 1
                        break
                if (flag == 1):
                    break

        op_data = [user, password]
        return op_data

    except Exception as e:
        LogGenModule.Exception(
            "Issue while fetching the data for given context and tower")
        LogGenModule.Exception(e)
def downloadFile(request, fileName=None):
    if get_or_none(uploadedFile, name=fileName):
        # list the files in input directory
        fileObjects= uploadedFile.objects.filter(name=fileName)
        if (fileName == 'null'):
            request.session['msgNote'] = ['fileView',{'sign':'error','msg':'Invalid file specified!'}]
            return fileView(request)
            # return a file object if file exist
        key = ''
        for fileObj in fileObjects:
            if fileObj.share_to.filter(pk=request.user.pk) or fileObj.owner.get().pk == request.user.pk:
                key = fileObj.key
                fileuid = os.path.join(inputDir + '/encrypted/' ,fileObj.uid)
            else:
                key = None

        if not key == None:
            dfilename = os.path.join(inputDir + '/decrypted/',fileName)
            decrypt(fileuid, dfilename, key, 32)
            wrapper = FileWrapper(file(dfilename))
            response = HttpResponse(wrapper, content_type='text/plain')
            response['Content-Length'] = os.path.getsize(dfilename)
            response['Content-Disposition'] = 'attachment; filename=%s' % fileName
            os.remove(dfilename)
            return response
        else:
            return HttpResponseRedirect(reverse('fileView'))

    else:
        request.session['msgNote'] = ['fileView',{'sign':'error','msg':'Invalid file specified!'}]
        return HttpResponseRedirect(reverse(fileView))
Exemplo n.º 3
0
def pass_download(message):
    user_id_hash = get_hash(message.from_user.id)
    id_of_file = user_data[user_id_hash]
    with db_session:
        password = File[id_of_file].password
    if get_hash(message.text) == password:
        bot.delete_message(message.chat.id, message.message_id)
        bot.send_message(message.chat.id, 'Расшифровываю, подожди секунду')
        with db_session:
            path = File[id_of_file].path
        path_to_open = os.getcwd() + '/files/' + user_id_hash + '/' + path
        encryption.decrypt(path, path_to_open, str(message.from_user.id),
                           message.text)
        markup = types.InlineKeyboardMarkup()
        btn_my_site = types.InlineKeyboardButton(
            text='Delete\U0001F5D1', callback_data='_deleteMessage_0')
        markup.add(btn_my_site)
        bot.send_document(chat_id=message.chat.id,
                          data=open(path, 'rb'),
                          reply_markup=markup)
        os.remove(path)

        bot.send_message(
            message.chat.id,
            'Не забудь удалить сообщение от меня, расшифрованного файла я не '
            'сохранил.')
    else:
        bot.send_message(
            message.chat.id,
            'Упс, пароль неверный, выбери файл заново и попробуй ещё раз')
Exemplo n.º 4
0
def getServicesOffline():
    '''
    Get an array of services for a user
    '''

    global name

    dir_path = os.path.expanduser("~/.passman")
    file_path = os.path.expanduser("~/.passman/{}.json".format(name))

    if not os.path.isfile(file_path) or \
            not os.path.isdir(dir_path):
        print("No local file found - exiting")
        quit()

    with open(file_path) as data_file:
        data = data_file.read()
    data = ast.literal_eval(data)['data']

    for service in data:
        service['service'] = decrypt(service['service'], key)
        service['serviceUserName'] = decrypt(service['serviceUserName'], key)
        service['servicePassword'] = decrypt(service['servicePassword'], key)
        service['serviceUrl'] = decrypt(service['serviceUrl'], key)

    return data
Exemplo n.º 5
0
    def process_request(self, request):
        http_service = request[0]
        tgt = request[1]
        authenticator = request[2]
        nonce = request[3]

        # check http service validity
        tgt = decrypt(tgt, self.database.key, self.database.tgt_nonce)

        authenticator = decrypt(authenticator, self.database.tgs_session_key,
                                nonce)
        # check authenticator validity
        if authenticator[0] != tgt[0]:
            raise Exception("Invalid authenticator")
        # check lifetime validity
        t1 = datetime.fromisoformat(tgt[3].decode())
        t2 = datetime.fromisoformat(authenticator[1].decode())
        if (t2 - t1).total_seconds() > 30 * 5:
            raise Exception("Ticket has expired")

        self.database.http_session_key = create_random_16_bytes()
        http_ticket = [
            http_service, tgt[0], tgt[1],
            datetime.now(), tgt[2], self.database.http_session_key
        ]

        self.database.http_nonce = create_random_16_bytes()
        enc_ticket = encrypt(http_ticket, self.database.http_key,
                             self.database.http_nonce)

        enc_session_key = encrypt(self.database.http_session_key,
                                  self.database.tgs_session_key,
                                  self.database.http_nonce)
        return [enc_ticket, enc_session_key, self.database.http_nonce]
Exemplo n.º 6
0
def compute(gt, hashes, final_hashes, start_label):
    """Performs BFS over given garbled NFA and returns a tuple implying if the string is accepted in the NFA or not.
	Takes input the garbled NFA (The garbled tables: gt, hashes of the final states: final_hashes, label for the start state: start_label)
	returns a tuple (a,b) s.t. if input string is accepting in the NFA then a=True and b=(label of the final state reached) else a=False and b=None"""

    # create frontier 0 using gt_0 and start_label
    current_frontier = [start_label]
    while (True):
        flag = False
        keys = [(label) for label in current_frontier]
        for k in keys:
            for e in gt[0]:
                (success, ans) = decrypt(e, k, hashes[0])
                if (success and (ans not in current_frontier)):
                    current_frontier.append(ans)
                    flag = True

        if (not flag):
            break

    # now interatively given the current frontier and gt_i find the next_frontier
    for i in range(1, len(gt)):
        next_frontier = []
        keys = [(label) for label in current_frontier]

        for k in keys:
            for e in gt[i]:
                (success, ans) = decrypt(e, k, hashes[i])
                if (success and (ans not in next_frontier)):
                    next_frontier.append(ans)

        # we have the direct labels in next_frontier, now take epsilon closure
        while True:
            flag = False
            keys = [(label) for label in next_frontier]
            for k in keys:
                for e in gt[i]:
                    (success, ans) = decrypt(e, k, hashes[i])
                    if (success and (ans not in next_frontier)):
                        next_frontier.append(ans)
                        flag = True
            if (not flag):
                break

        current_frontier = next_frontier

    # after all loops we have the final frontier
    obtained_hashes = [hash_func(label) for label in current_frontier]
    for i in range(len(obtained_hashes)):
        for h in final_hashes:
            if obtained_hashes[i] == h:
                return (True, current_frontier[i])

    return (False, None)
Exemplo n.º 7
0
def send_email(email, key):

    print(email)

    with open('./data.json') as json_file:  #open the json file
        data = json.load(json_file)

    # ask the user for it's email address and use regex to check that the email address is in correct format
    #######   -> still have to figure out how to pass this to tkinter   ######
    """
    email_correct = False
    while email_correct==False:
        email=input("Please type your email address ")
        if re.match('^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$', email):
            email_correct = True
        else:
            print("This is not a valid email address, please type in a valid address")
    """

    code = str(random.randint(
        10000, 99999))  #create the code with which the user can log in

    timestamp = str(datetime.datetime.now())  #timestamp of the code

    for entry in data:
        print(encryption.decrypt(data[entry]["email"], key))
        if encryption.decrypt(data[entry]["email"], key) == email:
            data[entry]["code"] = encryption.encrypt(code, key)
            data[entry]["code_timestamp"] = encryption.encrypt(timestamp, key)
            name = encryption.decrypt(data[entry]["first_name"], key)
            surname = encryption.decrypt(data[entry]["family_name"], key)

            #send the email

            sender = "*****@*****.**"
            recipient = email
            password = "******"  # Your SMTP password for Gmail
            subject = "Bypass code"
            text = "Dear %s %s, \n you have recently requested a code to pass our security system. \n If you haven't requested this code, please" \
                   "ignore this code. Otherwise, the code is:  %s " % (name, surname, code)

            smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
            smtp_server.login(sender, password)
            message = "Subject: {}\n\n{}".format(subject, text)
            smtp_server.sendmail(sender, recipient, message)
            smtp_server.close()

    with open('./data.json', 'w') as outfile:
        json.dump(data, outfile)
Exemplo n.º 8
0
def login():
    #Creates function called login.
    usernames_passwords = {}
    #username and password dictionary is created.
    with open("file.txt") as checkInfo:
        for line in checkInfo:
            #loops through each line in the text file.
            information = line.split()
            #splits the username and password in each line into 2 seperate variables and stores it in the information array.
            user = decrypt(information[0])
            passw = decrypt(information[1])
            #the username and password in the text file are decrypted using the decrypting function and then assigned to their respective variables.
            key, val = user, passw
            usernames_passwords[key] = val
            #stores the username and password in a dictionary where the username is the key and password is the value.

    username_input = input("enter your username: \n")

    try:
        corr_password = usernames_passwords[username_input]
        #if the user enters a valid username the correct password for that username is stored in this variable.
    except KeyError:
        #if the username is not valid this prevents an error from being thrown.
        print("This is not a valid username \n")
        print("If you do not have an account you can create one")
        create_account()
        #calls the create account function if the username is not valid so the user can create an account.
        return
        #once the new account is created this function ends due to this return.

    password_input = input("enter your password: \n")

    if password_input == corr_password:
        print("you have been successfully logged in \n")
        #checks if the password inputted is correct for that username.

    else:
        print("this password is incorrect. You have 3 more tries")
        for i in range(0, 3):
            password_input = input("enter your password: \n")
            if password_input == corr_password:
                print("You have successfully been logged in \n")
                break
            else:
                print("This password is incorrect. You have", 2 - i,
                      "more tries")
        #gives the user 3 more tries to enter the password.

        sys.exit()
Exemplo n.º 9
0
def start():
    TERMINAL_SIZE = gts.get_terminal_size()[0]
    pwd = input_dialog(title='LOGIN',
                       text='Please enter the password for the mail-client:',
                       password=True)
    working = False
    if not pwd or len(pwd) <= 1:
        sys.exit()
    while not working:
        try:
            encryption.decrypt(pwd)
            working = True
        except:
            pwd = input_dialog(
                title='LOGIN',
                text='Your password was incorrect! Please try again:',
                password=True)
            working = False
            if not pwd or len(pwd) <= 1:
                sys.exit()
    os.system('clear')
    functions.makeMenu(TERMINAL_SIZE=TERMINAL_SIZE)
    select = input("> ")
    while select not in "qQ":
        if select in "sS":
            sendTUI(pwd=pwd)
            os.system('clear')
        elif select in "lL":
            showMails(pwd=pwd)
            os.system('clear')
        elif select in "uU":
            updateCredentials(pwd)
            os.system('clear')
        elif select in "rR":
            rainbow.main()
            os.system('clear')
        elif select in "aA":
            addressBookTUI()
            os.system('clear')
        else:
            functions.printInRed("I can't understand this")
        TERMINAL_SIZE = gts.get_terminal_size()[0]
        functions.makeMenu(TERMINAL_SIZE=TERMINAL_SIZE)
        select = input("> ")
    os.system('clear')
    functions.printInBlue("#" * TERMINAL_SIZE)
    functions.printInBlue("#{0:^{1}}#".format("Goodbye!", TERMINAL_SIZE - 2))
    functions.printInBlue("#" * TERMINAL_SIZE)
Exemplo n.º 10
0
 def view_logins(self, key, username):
     app = self.keyhandle(key)
     self.log(app, " Looked up login history for user: "******"SELECT * FROM logins")
     cursor = cnx.cursor()
     cursor.execute(sel)
     usernames = []
     timestamps = []
     IDs = []
     apps = []
     for data in cursor:
         if ec.decrypt(data[0], self.decryption_key) == username:
             usernames.append(username)
             timestamps.append(data[1])
             IDs.append(data[2])
             apps.append(data[3])
     cursor.close()
     translated = []
     for item in IDs:
         sels = ("SELECT * FROM clients WHERE ID='" + item + "'")
         cursor = cnx.cursor()
         cursor.execute(sels)
         for dat in cursor:
             tmp = dat[0]
         translated.append(tmp)
     complete = [usernames, timestamps, translated, apps]
     cursor.close()
     return complete
def display_decrypted(txt,ent):
	print ("Decrypted Message")
	txt.configure(state='normal')
	txt.delete(1.0, TK.END )
	txt.update()
	txt.insert(TK.CURRENT , encryption.decrypt(ent.get()))
	txt.configure(state='disabled')
Exemplo n.º 12
0
    def decode(image, password):
        try:
            im = Image.open(image)
        except:
            print("No such image", image)
            exit()
        px = im.load()
        info = ''
        x = 0
        line = 0
        lineWidth = im.size[0]
        while x == 0 or 31 < int(code, 2) < 127:
            try:
                auxList1 = [bin(v)[-1] for v in px[x, line]]
                auxList2 = [bin(v)[-1] for v in px[x + 1, line]]
                auxList = auxList1 + auxList2
                code = ''.join(auxList)
                x += 2
                if x >= lineWidth - 1:
                    line += 1
                    x = 0
            except Exception as e:
                print(e)
                break

            info += chr(int(code, 2))

        if password:
            return crypto.decrypt(info[:-1], password)
        return info[:-1]
Exemplo n.º 13
0
def udp_service():
    global IP
    global UDP_PORT
    global TCP_PORT
    global NETWORK_ENCRYPTION

    sock = socket.socket(
        socket.AF_INET,  # Internet
        socket.SOCK_DGRAM)  # UDP
    sock.bind((IP, UDP_PORT))

    print "UDP Service"
    while True:
        data, addr = sock.recvfrom(4096)
        if len(data) < 3:
            continue
        print "UDP" + str(addr)
        message = struct.unpack("c" + str(len(data) - 1) + "s", data)
        pkt_type = ord(message[0])
        if pkt_type != 1:
            continue
        decrypted = encryption.decrypt(bytearray(message[1]),
                                       NETWORK_ENCRYPTION)
        print "INIT MESSAGE: " + decrypted
        reply = encryption.encrypt("ACK:" + decrypted, NETWORK_ENCRYPTION)
        formating = "<cH" + str(len(reply) + 1) + "s"
        message = struct.pack(formating, b'\x02', TCP_PORT, str(reply) + " ")
        sock.sendto(message, addr)
 def decrypt_with_metadata(self, path, data):
     metafilepath = self._metadata_file(path)
     metafile = open(metafilepath, 'r')
     metadata = metafile.read()
     data = metadata[:self.metadata_header_length] + data + metadata[self.metadata_header_length:]
     metafile.close()
     return decrypt(data, self.encryption_key, self.signing_key)
Exemplo n.º 15
0
    def parseMultipart(j):
        print "\nparseMultipart\n"

        ret = ""
        _continue = True

        while _continue:
            
            reply2, _addr = sUDP.recvfrom(200)

            uncoded = struct.unpack("!??HH64s", reply2)


            uncrypted_question = uncoded[4].strip('\x00')

            decrypted = encryption.decrypt(uncrypted_question, key_list[j])
            
            print "\ndecrypted"
            print decrypted

            ret = ret + decrypted
            print "\nret"
            print ret
            j = j + 1
            if uncoded[3] == 0:
                _continue = False

        if uncoded[0] == False:
            
            #print "EOM is false"
            return (ret, _addr, False)

        else:
            #print "EOM is true"
            return (ret, _addr, True)
Exemplo n.º 16
0
def process_echo2Device(topic, mqttclient_send):
    """
    echo with device
    note: .exit is to quit echo with device
    """
    global GotMsgContext
    process_sendCmd(mqttclient_send, "uname -a", topic)

    while True:
        if GotMsgContext != "":
            # show cmd exec result
            gotMsgContext_decrypt = encryption.decrypt(11, GotMsgContext)
            reportdict = json.loads(gotMsgContext_decrypt)
            curuser = reportdict["curuser"]
            curmac = reportdict["curmac"]
            curpath = reportdict["curpath"]
            report = reportdict["report"]
            print(report)

            # send cmd to device
            cmd = input("echo@" + curuser + "@" + curmac + "@" + curpath +
                        "@: ")
            if cmd == ".exit":
                break
            cmd_reform = cmdCheck(cmd, curuser)
            process_sendCmd(mqttclient_send, cmd_reform, topic)
            GotMsgContext = ""
Exemplo n.º 17
0
def main():
    config = receiveConfig()

    if config.encrypt:
        encrypt(config.encrypt)
    elif config.decrypt:
        handle_ouput(decrypt(config.decrypt), config.output)
Exemplo n.º 18
0
 def _decrypt_and_verify(self, value):
     if self.isEncrypted() or self.isSigned():
         #decrypt also verifies unencrypted, signed data
         plain, self._signature_data = encryption.decrypt(value)
         return plain
     else:
         return value
Exemplo n.º 19
0
    def parseMultipart(j):
        print "\nparseMultipart\n"

        ret = ""
        _continue = True

        while _continue:

            reply2, _addr = sUDP.recvfrom(200)

            uncoded = struct.unpack("!??HH64s", reply2)

            uncrypted_question = uncoded[4].strip('\x00')

            decrypted = encryption.decrypt(uncrypted_question, key_list[j])

            print "\ndecrypted"
            print decrypted

            ret = ret + decrypted
            print "\nret"
            print ret
            j = j + 1
            if uncoded[3] == 0:
                _continue = False

        if uncoded[0] == False:

            #print "EOM is false"
            return (ret, _addr, False)

        else:
            #print "EOM is true"
            return (ret, _addr, True)
Exemplo n.º 20
0
def recv(server):
    '''recv msg from server'''

    while True:
        state = server.recv(size=4)

        if state == '1010':
            continue

        if state == '1100':
            server.store(state)
            continue

        if state == '1000':
            # key recv
            server.store(state)
            key = server.recv(encoding=False)

            server.store(key)

        else:
            if state == '1111':
                encrypted = server.recv(encoding=False)

                decrypted = decrypt(encrypted)
                write(decrypted)

            else:
                server.store(state)
Exemplo n.º 21
0
def getServiceData(name, data):
    '''
    Get a specific subset of data from a service 
    (i.e. just the username, password, etc.)
    '''
    global key
    service = getServiceByName(name)
    return decrypt(service[data], key)
Exemplo n.º 22
0
def resolve_pairs():
    if (DAY_OF_RESOLVE <= date.today().day and MONTH_OF_RESOLVE <= date.today().month) or \
            date.today().year > YEAR_OF_RESOLVE:
        pairs = (decrypt(read_data_as_bytes(Path("pairs.txt")))).decode()
        write_data(pairs, Path("pairs.txt"))
        return pairs
    else:
        return "Too early wait until release date!"
Exemplo n.º 23
0
def handleGetToken(arguments):
    if not 'lookup' in arguments or not 'md5' in arguments:
        return show404()

    import encryption

    key = arguments['key'].value
    lookup = encryption.decrypt(arguments['lookup'].value)
    md5 = encryption.decrypt(arguments['md5'].value)

    cnx = mysql.connector.connect(user=USER,
                                  password=PASSWORD,
                                  database=DATABASE)
    cursor = cnx.cursor()
    try:
        query = (
            'SELECT token FROM oauth WHERE lookup = %s AND md5 = %s AND oauth.timestamp < NOW() - INTERVAL 5 MINUTE'
        )

        cursor.execute(query, (lookup, md5))
        token = None
        for token in cursor:
            break

        if token: token = token[0]

        print "Content-Type: application/json"
        print
        if token == None:
            print encryption.encrypt(json.dumps({'status': 'error'}), key)
        elif token:
            print encryption.encrypt(
                json.dumps({
                    'status': 'ready',
                    'token': token
                }), key)
            query = ("DELETE FROM " + DATABASE +
                     ".oauth WHERE oauth.lookup = %s")
            cursor.execute(query, (lookup, ))
            _clearStaleEntries(cursor)
        else:
            print encryption.encrypt(json.dumps({'status': 'waiting'}), key)

    finally:
        cursor.close()
        cnx.close()
Exemplo n.º 24
0
 def __init__(self, fields, decryptionKey):
     
     Account.__init__(self, fields)
     
     self.server = fields['strServer']
     self.port = fields['intPort']
     self.username = fields['strUsername']
     self.password = encryption.decrypt(decryptionKey, str(fields['strPassword']))
Exemplo n.º 25
0
def login():
    uname = raw_input(bcolors.OKBLUE+"Enter username : "******"Enter Password : "******"{'cmd':'login','uname':'%s','passwd':'%s'}"%(uname,passwd)
        cipher = encryption.encrypt(data_to_send,"serverkey.pem",publickey=None)
        signature = encryption.signature(data_to_send,"keypriv")
        outp = "{'cipher':'%s','signature':'%s'}"%(cipher,signature)
        sock.sendall(outp)
    except Exception as e:
        print(bcolors.FAIL+"An error occured :("+bcolors.ENDC)
        print(e)
        return 0
    
    try:
        data = sock.recv(1024)
    except:
        print(bcolors.FAIL+"No response received from the server :("+bcolors.ENDC)
        return 0
        
    data = ast.literal_eval(data.encode("utf-8"))
    cipher = data["cipher"]
    signature = data["signature"]
    resp=""
    resp_type=""
    
    hex_decode = codecs.getdecoder("hex")
    cipher = hex_decode(cipher)[0]
    signature = hex_decode(signature)[0]
    
    
    f = open("serverkey.pem","r")
    publickey = f.read()
    f.close()
    #check authenticity now
    resp = encryption.decrypt(cipher,"keypriv.pem")
    authenticated = encryption.check_authenticity(resp,signature,publickey)
    
    if(authenticated==1):
        #authentication successful
        pass
    elif(authenticated==0):
        print(bcolors.FAIL+"Authenticity of the message can't be verified!"+bcolors.ENDC)
        return 0
    
    resp = ast.literal_eval(resp.encode())
    resp_type = resp["resp_type"]

    if resp_type=="SUCC":
        clear_screen()
        global username
        username = uname
        print(bcolors.OKGREEN+"Logged in as "+bcolors.BOLD+username+bcolors.ENDC)
        return 1
    
    elif resp_type=="FAIL":
        print(bcolors.FAIL+"Can't log in!"+bcolors.ENDC)
        return 0
Exemplo n.º 26
0
def recv(ip):
    private_key = encryption.get_key()
    u = upnp_handler.new_upnp()
    upnp_handler.forward_port(u, 25565)

    s = socket.socket()

    s.connect((ip, 25565))

    public_key = encryption.get_public_key()

    s.send(public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    ))

    encryptedmetajson = s.recv(1024)
    metajson = encryption.decrypt(private_key, encryptedmetajson).decode('utf-8')
    metadata = json.loads(metajson)
    filename = metadata['filename']
    size = metadata['size']
    checksum = metadata['checksum']
    fernet_key = metadata['fernet_key'].encode('utf-8')


    if (input("Recieve " + filename + ", a " + filesize.size(
        size, system = filesize.alternative) + "byte file? [Y/n] \n").upper() in
        ['N', 'NO']):
        
        print('Abort.')
        s.send("nosend".encode('utf-8'))
        upnp_handler.close_port(u, 25565)
        sys.exit()



    s.send("send it".encode('utf-8'))

    encryptedtoken = b""

    while True:
        data = s.recv(1024)
        if (len(data)):
            encryptedtoken += data
        else:
            break

            s.close()
            upnp_handler.close_port(u, 25565)

    with open(filename, 'w+b') as f:
        f.truncate(0)
        f.write(encryption.decrypt_fernet(fernet_key, encryptedtoken))

    f = open(filename, 'rb')
    if (sha256(f.read()).hexdigest() != checksum):
        print("WARNING! Something happened to the file! Checksums do not match!")
        print(sha256(repr(f.read).encode('utf-8')).hexdigest())
Exemplo n.º 27
0
def GetKeys(twitter_keys_path):
    consumer_key = ''
    consumer_secret = ''
    access_token = ''
    access_secret = ''
    PATH = 'twitter_keys/'
    l_files = [
        'consumer_key', 'consumer_secret', 'access_token', 'access_secret'
    ]

    for k in l_files:
        f = open(PATH + k, 'rb')
        key = f.read()
        if (k == 'consumer_key'):
            consumer_key = decrypt(key)
        if (k == 'consumer_secret'):
            consumer_secret = decrypt(key)
        if (k == 'access_token'):
            access_token = decrypt(key)
        if (k == 'access_secret'):
            access_secret = decrypt(key)
        f.close()
    """
    for k in keys:
        try:
            values = k.split('\n')[0].split('=')[1].strip()
            if(k.split('\n')[0].split('=')[0].strip() == 'consumer_key'):
                consumer_key = decrypt(values)
            elif(k.split('\n')[0].split('=')[0].strip() == 'consumer_secret'):
                consumer_secret = decrypt(values)
            elif(k.split('\n')[0].split('=')[0].strip() == 'access_token'):
                access_token = decrypt(values)
            elif(k.split('\n')[0].split('=')[0].strip() == 'access_secret'):
                access_secret = decrypt(values)
        except IndexError:
            # Maybe there are a '\n' between keys
            continue

    """
    return {
        'consumer_key': consumer_key,
        'consumer_secret': consumer_secret,
        'access_token': access_token,
        'access_secret': access_secret
    }
Exemplo n.º 28
0
def authenticate(username, password):
    '''Authenticates user by taking a username and password as parameters'''
    user = user_collection.find_one({'username': username})
    if user:
        decrypted_password = enc.decrypt(user['password']).decode()
        if password == decrypted_password:
            return user

    return False
Exemplo n.º 29
0
def parseCredentials(pwd, file="secret_credentials.json"):
    jsondec = JSONDecoder()

    text = encryption.decrypt(password=pwd) or "{}"
    data = jsondec.decode(text)
    print("Opening credential file...")

    return data.get("SERVER", "example.com"), data.get("PORT", "0"), data.get(
        "USER", "*****@*****.**"), data.get("PASSWORD", "admin")
Exemplo n.º 30
0
def process_execCmd(client, cur_toolaccount):
    """
    recv cmd and exec and return result
    """
    # get basic info
    cur_os = getInfo.get_curOs()
    cur_user = getInfo.get_curUser(cur_os)
    cur_path = getInfo.get_curPath()
    cur_mac = getInfo.get_curMac(cur_os)

    # read cmd
    reportMsg = ""
    msgContext_decrypt = encryption.decrypt(11, GotMsgContext)
    msgdict = json.loads(msgContext_decrypt)
    cmd = msgdict["cmd"]

    # excute cmd
    if cmd == "pwd":
        reportMsg = os.getcwd()
    elif cmd.find("cd ") == 0:
        leng = len(cmd)
        cmd = cmd[3:leng]
        #print(cmd)
        try:
            os.chdir(cmd)
        except:
            reportMsg = "Error: execute " + cmd + "err!"
    else:
        try:
            proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except:
            reportMsg = "Error: subprocess.Popen " + cmd + "err!"
    
        for line in proc.stdout.readlines():
            reportMsg = reportMsg + line.decode("UTF-8")

        for line in proc.stderr.readlines():
            reportMsg = reportMsg + line.decode("UTF-8")

    # send out msg
    resultdict = {}
    resultdict.update({"msgType": "exec_return"})
    resultdict.update({"curuser": cur_user})
    resultdict.update({"curtoolaccount": cur_toolaccount})
    resultdict.update({"curmac": cur_mac})
    resultdict.update({"curpath": cur_path})
    resultdict.update({"report": reportMsg})
    resultMsg_json = json.dumps(resultdict)
    resultMsg_json_encrypt = encryption.encrypt(11, resultMsg_json)

    topic = "topic_dev2ser/exec_result/" + cur_mac
    client.publish(topic, payload=resultMsg_json_encrypt)

    print("[x] Sent msg out to topic: ", topic)
    print("sent out msg: " + resultMsg_json)
    print("sent out msg(encrypt): " + resultMsg_json_encrypt)
def get_dccinfo(master_password, signing_password):
    with open(join(getcwd(), '.dcc'), 'r') as dcc_file:
        dcc_file = dcc_file.read()
        salt_1, salt_2, encrypted_data = (dcc_file[:8], dcc_file[8:16],
                                          dcc_file[16:])
        data = pickle.loads(
            decrypt(encrypted_data,
                    PBKDF2(master_password, salt_1).read(32),
                    PBKDF2(signing_password, salt_2).read(32)))
        return (b64decode(data['cn'])[6:], data['cn'], data['dbtk'])
Exemplo n.º 32
0
    def process_client_request(self, client_request):
        """ Verifies that the client request is valid. Extracts https session key"""
        client_nonce = client_request[-1]
        http_ticket = decrypt(client_request[1], self.secret_key, self.nonce)

        self.session_key = http_ticket[-1]
        client_authenticator = decrypt(client_request[0], self.session_key,
                                       client_nonce)

        if (client_authenticator[0] not in self.past_authenticators):
            # add to past authenticators
            if (self.verify_ticket(client_authenticator, http_ticket)):
                self.create_authenticator()
                nonce = create_random_16_bytes()
                enc_auth = encrypt(self.current_authenticator,
                                   self.session_key, nonce)
                return [enc_auth, nonce]

        return None
Exemplo n.º 33
0
 def decrypt(self):
     password = settings.read('api', 'password')
     key = encryption.get_key(password, get_salt())
     message_decoded = encryption.decrypt(key, self.data.ciphertext)
     push_data = json.loads(message_decoded.decode(settings.read('general', 'encoding')))
     for i, value in enumerate(self.pushData):
         if value in push_data:
             setattr(self.data, value, push_data[value])
         else:
             setattr(self.data, value, '')
Exemplo n.º 34
0
def combine(shards, judo_file):
    """combine

    this class is passed the
    """
    # Recombine the shards to create the kek
    combined_shares = Shamir.combine(shards)
    combined_shares_string = "{}".format(combined_shares)

    # decrypt the dek uysing the recombined kek
    decrypted_dek = decrypt(judo_file['wrappedKey'],
                            unhexlify(combined_shares_string))

    # decrypt the data using the dek
    decrypted_data = decrypt(judo_file['data'], unhexlify(decrypted_dek))

    decrypted_text = unhexlify(decrypted_data)

    return (decrypted_data, decrypted_text)
Exemplo n.º 35
0
 def receive(self):
     """
     Receives a string message from a client and decrypts it.
     :return string of message received from a client
     """
     import encryption
     bytes_received = self._socket.recvfrom(self.bufferSize)
     if self._encryption:
         return [encryption.decrypt(bytes_received[0]), bytes_received[1]]
     return bytes_received
Exemplo n.º 36
0
 def authenticate(self, username=None, password=None):
     try:
         spuser = Specifyuser.objects.get(name=username)
     except Specifyuser.DoesNotExist:
         return None
     decrypted = decrypt(spuser.password, password)
     if decrypted != password:
         return None
     else:
         return spuser
Exemplo n.º 37
0
def recvCommand(packet):
   global flag
   global Results
   if packet.haslayer(IP):
    if packet[IP].src == configfile.ip:
        dataReceived = helpers.parsePacket(packet)
        Results += (dataReceived)
        if packet.haslayer(Raw):
            if packet[Raw].load == configfile.password:
                flag = True
                decryptedData = encryption.decrypt(Results, configfile.masterkey)
                print decryptedData
                Results = ""
Exemplo n.º 38
0
def handleGetToken(arguments):
	if not 'lookup' in arguments or not 'md5' in arguments:
		return show404()
	
	import encryption
	
	key = arguments['key'].value
	lookup = encryption.decrypt(arguments['lookup'].value)
	md5 = encryption.decrypt(arguments['md5'].value)
 
	cnx = mysql.connector.connect(user=USER, password=PASSWORD, database=DATABASE)
	cursor = cnx.cursor()
	try:
		query = ('SELECT token FROM oauth WHERE lookup = %s AND md5 = %s AND oauth.timestamp < NOW() - INTERVAL 5 MINUTE')
		
		cursor.execute(query, (lookup, md5))
		token = None
		for token in cursor:
			break
		
		if token: token = token[0]
		
		print "Content-Type: application/json"
		print
		if token == None:
			print encryption.encrypt(json.dumps({'status':'error'}),key)
		elif token:
			print encryption.encrypt(json.dumps({'status':'ready','token':token}),key)
			query = ("DELETE FROM "+DATABASE+".oauth WHERE oauth.lookup = %s")
			cursor.execute(query, (lookup,))
			_clearStaleEntries(cursor)
		else:
			print encryption.encrypt(json.dumps({'status':'waiting'}),key)
			
	finally:
		cursor.close()
		cnx.close()
def get_file(*args, **kwargs):
    if len(args) == 0 or '--help' in ''.join(args):
        map(print, [
            'About: This command retrieves a file from the virtual file system if it exists.',
            '',
            'Usage: $ dcc get <virtual path> (<local path>)',
            '',
            'By default this will output the contents of the file to standard output unless the `<local path>` is specified.',
            'The `<local path>` can optionally include the filename otherwise the name of the file when uploaded will be used.'
        ])
        return 1
    encryption_key, signing_key, api_token, human_container_name, container_name = prompt_userinfo()
    vfs = load_vfs(api_token, container_name, encryption_key, signing_key)
    vfs_exists, data = vfs.get_file_data(args[0])
    if not vfs_exists:
        print('Error: The path `%s` does not exist.' % args[0])
        return 1
    if len(args) >= 2: # if we have virtual path and local path
        local_path = normpath(join(getcwd(), args[1].strip()))
        if len(local_path) > 0:
            local_filename = basename(local_path)
            if len(local_filename) > 0 and '.' not in local_filename:
                local_filename = ''
            if len(local_filename) > 0:
                local_path = local_path[:-len(local_filename)]
            else:
                local_filename = data[0]
            if not exists(local_path):
                makedirs(local_path)
            with open(join(local_path, local_filename), 'w+') as output_file:
                content = download_file(api_token, container_name, data[2])
                output_file.write(decrypt(content, encryption_key, signing_key))
                return 0
    # else we do not have the local path, we need to output to standard out
    content = download_file(api_token, container_name, data[2])
    print(decrypt(content, encryption_key, signing_key))
    return 0
Exemplo n.º 40
0
def recvFile(packet):
    flag = False
    global resultsForFiles
    if packet.haslayer(IP):
        if packet[IP].src == configfile.ip:
            dataReceived = helpers.parsePacket(packet)
            resultsForFiles += (dataReceived)
            if packet.haslayer(Raw):
                if packet[Raw].load == configfile.password:
                    flag = True
                    decryptedData = encryption.decrypt(resultsForFiles, configfile.masterkey)
                    fileName, fileData = decryptedData.split("\0", 1)
                    fileDescriptor = open(fileName, 'wb')
                    fileDescriptor.write(fileData)
                    resultsForFiles = ""
Exemplo n.º 41
0
 def __init__(self, db, fields):
     """
         Initializes a new Email using a dictionary
         of database fields.
     """
     fields['strMessageType'] = 'imap'
     
     Message.__init__(self, db, fields)
     
     encryptionKey = settings.settings['userDataEncryptionSalt'] + message._password
     
     self.remoteId = fields['intEmailRemoteId']
     
     self.subject = fields['strEmailSubject']
     
     self.bodyPlain = fields['strEmailBodyPlainText']
     self.bodyPlain = encryption.decrypt(encryptionKey, self.bodyPlain)
     
     self.bodyHtml = fields['strEmailBodyHtml']
     self.bodyHtml = encryption.decrypt(encryptionKey, self.bodyHtml)
     
     if 'strRaw' in fields:
         self.raw = fields['strRaw']
         self.raw = encryption.decrypt(encryptionKey, self.raw)
def sync_files(*args, **kwargs):
    encryption_key, signing_key, api_token, human_container_name, container_name = prompt_userinfo()
    vfs = load_vfs(api_token, container_name, encryption_key, signing_key)
    for _, (file_name, path, file_uuid) in vfs.files.iteritems():
        path = path[:-len(basename(path))]
        print('Attempting to write `%s` ~> `%s`' % (file_name, path))
        if not exists(path):
            makedirs(path)
            print(' [OK] Created Path `%s`' % path)
        decrypted_file = decrypt(download_file(api_token, container_name, file_uuid), encryption_key, signing_key)
        print(' [OK] Downloaded and decrypted `%s`' % file_uuid)
        with open(join(path, file_name), 'w+') as output_file:
            output_file.write(decrypted_file)
            print(' [OK] Wrote file `%s`' % file_name)
    return 0
Exemplo n.º 43
0
def confirm_trans_decrypt(hold_id, data=None):
  """ Confirm a pending sale (update both tbTransactions and tbHolds)

  Args:
    hold_id(int): hold id (tbHolds)
  Returns:
    boolean
  """
  try:
    engine = create_engine(DB, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    hold = session.query(Hold).filter(Hold.id == hold_id).one()
    if not hold.is_pending:
      raise Exception('not a pending transactions.')

    buyer = hold.last_trans.buyer
    if not data:
      enc_data = hold.enc_data
    else:
      enc_data = binascii.unhexlify(data)
    (r1, r2) = encryption.decrypt(buyer, enc_data)
    if r1 != buyer.uniqid.encode():
      print(r1, buyer.uniqid.encode())
      raise Exception('unmatched buyer id')
    if r2 != hold.last_trans.secret:
      print(r2, hold.last_trans.secret)
      raise Exception('unmatched secret')
    # Add transaction
    hold.last_trans.state = TransState.CONFIRMED
    hold.last_trans.last_update = datetime.datetime.now()
    hold.holder_id = hold.last_trans.buyer_id
    hold.is_pending = False
    session.commit()
    return {'result':True}
  except Exception as e:
    print('exeption:{0}'.format(e))
    raise e
  finally:
    session.close()
    engine.dispose()
Exemplo n.º 44
0
def parseCommand(packet):
    if packet.haslayer(IP) and packet.haslayer(Raw):
        if packet[IP].src != clientIP:
            return
        encryptedData = packet['Raw'].load
        data = encryption.decrypt(encryptedData, configfile.masterkey)
        if data.startswith(configfile.password):
            data = data[len(configfile.password):]
            commandType, commandString = data.split(' ', 1)
            if commandType == 'shell':
                shellCommand(packet, commandString)
            elif commandType == 'watchAdd':
                fileProcess = Process(target=watchAdd, args=(commandString, packet[IP].src))
                fileProcess.daemon = True
                fileProcess.start()
                print "file process started"
            elif commandType == 'watchRemove':
                watchRemove()
            elif commandType == 'screenshot':
                screenshot(packet, commandString)
            elif commandType == 'exit':
                exit()
            else:
                print "Unknown command"
Exemplo n.º 45
0
def test_decrypt_works_with_negative_offsets():
    assert_equal(decrypt('RFC OSGAI ZPMUL DMV HSKNQ MTCP RFC JYXW BME', -2),  cleartext)
    assert_equal(decrypt('IWT FJXRZ QGDLC UDM YJBEH DKTG IWT APON SDV', -11), cleartext)
    assert_equal(decrypt('PDA MQEYG XNKSJ BKT FQILO KRAN PDA HWVU ZKC', -4),  cleartext)
Exemplo n.º 46
0
def test_decrypt_raises_ValueError_if_called_with_empty_string():
    with assert_raises(ValueError) as e:
        decrypt('', offset)
    assert_equal(e.exception.message, 'can not encrypt empty string')
Exemplo n.º 47
0
 def decrypt(self,pkt):
     if pkt.data != "":
         decrypt(pkt.data)
Exemplo n.º 48
0
 def decrypt_data(self, data, metadata):
     data = metadata['digest'] + metadata['iv'] + data + metadata['padding']
     return decrypt(data, self.encryption_key, self.signing_key)
Exemplo n.º 49
0
def test_decrypt_returns_a_string():
    assert_is_instance(decrypt(cleartext, offset), str)
Exemplo n.º 50
0
            print "Enter plaintext message (enter a newline to stop):"
            plaintext = read_until_empty_line("> ")

            marshaled = marshal(plaintext)
            ciphertext = encrypt(marshaled, key.key)
            print
            print "Encrypted message:"
            print ciphertext

        elif cmd == "2":
            print "Enter ciphertext message (enter a newline to stop):"
            try:
                ciphertext = read_until_empty_line("> ")
                print
                print "Decrypted message:"

                marshaled = decrypt(ciphertext, key.key)
                print "Marshaled:", marshaled

                plaintext = unmarshal(marshaled)
                print "Decrypted:", plaintext

            except InvalidCiphertext as e:
                print e

        elif cmd == "e":
            break

        else:
            print "Invalid command, try again"
Exemplo n.º 51
0
def test_decrypt_returns_the_decrypted_string():
    assert_equal(decrypt('WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ', 3),  cleartext)
    assert_equal(decrypt('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT', 13), cleartext)
    assert_equal(decrypt('YMJ VZNHP GWTBS KTC OZRUX TAJW YMJ QFED ITL', 5),  cleartext)
Exemplo n.º 52
0
def test_decrypt_raises_ValueError_if_called_with_zero_offset():
    with assert_raises(ValueError) as e:
        decrypt(cleartext, 0)
    assert_equal(e.exception.message, 'offset must not be zero')
def get_dccinfo(master_password, signing_password):
    with open(join(getcwd(), '.dcc'), 'r') as dcc_file:
        dcc_file = dcc_file.read()
        salt_1, salt_2, encrypted_data = ( dcc_file[:8], dcc_file[8:16], dcc_file[16:] )
        data = pickle.loads(decrypt(encrypted_data, PBKDF2(master_password, salt_1).read(32), PBKDF2(signing_password, salt_2).read(32)))
        return ( b64decode(data['cn'])[6:], data['cn'], data['dbtk'] )