Пример #1
0
 def _downloadEmail(self, db, id, server):
     """
         Downloads the email with the given remote ID and stores
         it in the database.
     """
     
     email = server.getMailFromId(id)
     
     bodyPlain = email['bodyPlainText']
     bodyHtml = email['bodyHtml']
     raw = email['raw']
         
     if self.encryptionKey:
         bodyPlain = encryption.encrypt(self.encryptionKey, bodyPlain)
         bodyHtml = encryption.encrypt(self.encryptionKey, bodyHtml)
         raw = encryption.encrypt(self.encryptionKey, raw)
                     
     alias, address = email['from']
     senderId = contact.addEmptyContact(db, 'email', address, alias)
     
     recipientIds = [contact.addEmptyContact(db, 'email', address, alias) for alias, address in email['to']]
     
     messageId = message.store(db, self.account.id, email['date'], senderId, email['subject'], recipientIds, 'imap')
     
     emailMessage.store(db, messageId, id, email['subject'], bodyPlain, bodyHtml, raw)
Пример #2
0
def addService(name, pw, serviceUrl="", serviceUserName=""):
    '''
    Add a service to the document for current user.

    Checks if service name already exists before adding.
    Prints an error message if service name already exists.
    '''

    found = checkIfServiceExists(name)
    if not found:
        global key
        result = collection.find_one_and_update({'name': userName}, {
            '$push': {
                'data': {
                    'service': encrypt(name, key),
                    'servicePassword': encrypt(pw, key),
                    'serviceUrl': encrypt(serviceUrl, key),
                    'serviceUserName': encrypt(serviceUserName, key)
                }
            }
        })

        return result

    else:
        print("\nERROR: Database already contains service " + name + "\n")
Пример #3
0
def main():
    # generate keys
    key_setup.keygen()
    # encrypt message
    encryption.encrypt()
    # decrypt message
    decryption.decrypt()
Пример #4
0
    def process_request(self, request):
        """
            Processes authentication request.
            If the request is valid, returns encrypted TGT and TGT session key
        """
        # check if a user is valid
        if request[0] not in self.database.users:
            raise KeyError("Invalid User")

        # client ID, client IP, ticket lifetime, time, TGS session key
        self.database.tgs_session_key = create_random_16_bytes()
        tgt = [
            request[0], request[1], request[2],
            datetime.now(), self.database.tgs_session_key
        ]

        self.database.tgt_nonce = create_random_16_bytes()

        enc_tgt = encrypt(tgt, self.database.key, self.database.tgt_nonce)
        enc_session_key = encrypt(self.database.tgs_session_key,
                                  self.database.users[request[0]],
                                  self.database.tgt_nonce)

        return (enc_tgt, enc_session_key, self.database.tgt_nonce
                )  # encrypt tgs session key with client secret
Пример #5
0
def handleGetLookup(arguments):
    if not 'source' in arguments:
        return show404()

    source = arguments['source'].value
    key = arguments['key'].value
    lookup = generateLookup()
    md5 = generateMD5()
    timestamp = getTimestamp()

    cnx = mysql.connector.connect(user=USER,
                                  password=PASSWORD,
                                  database=DATABASE)
    cursor = cnx.cursor()

    try:

        addTokenEntry = ("INSERT INTO oauth "
                         "(lookup, md5, token, source, timestamp) "
                         "VALUES (%s, %s, %s, %s, %s)")

        data = (lookup, md5, '', source, timestamp)

        cursor.execute(addTokenEntry, data)

        cnx.commit()
    finally:
        cursor.close()
        cnx.close()

    import encryption

    print "Content-Type: application/json"
    print
    print encryption.encrypt(json.dumps({'lookup': lookup, 'md5': md5}), key)
Пример #6
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]
def test_for_strict_avalanche():
    """
    Function to apply the SAC test defined in https://eprint.iacr.org/2010/564.pdf.
    """
    with open('key.txt', 'rb') as file:
        key = file.read()
    associated_data = generate_nonce(16).encode(encoding='utf-8')
    sample_size = 32768

    plaintext_bit_size = 64
    plaintext_byte_length = 8
    algorithms = [
        "ascon128.so", "ascon128a.so", "isap_a_128.so", "isap_k_128.so",
        "oribatida_128.so", "locus_64.so", "lotus_64.so", "spoc_64.so"
    ]
    print(algorithms)
    for alg in algorithms:
        print(alg)
        if "128" in alg:
            tagsize = 16
        else:
            tagsize = 8
        matrix = np.zeros(
            (plaintext_bit_size, plaintext_bit_size + (tagsize * 8)),
            dtype=int)
        for _ in range(0, sample_size):
            plaintext = random.getrandbits(plaintext_bit_size)
            nonce = generate_nonce(16).encode(encoding='utf-8')
            variant = "encryption_interfaces/" + alg
            original_cipher = encrypt(
                key, nonce, associated_data,
                plaintext.to_bytes(plaintext_byte_length, sys.byteorder),
                variant, tagsize)
            for bit_position in range(0, plaintext_bit_size):
                temp_plaintext = BitArray(
                    plaintext.to_bytes(plaintext_byte_length, sys.byteorder))
                temp_plaintext.invert(bit_position)
                nonce = generate_nonce(16).encode(encoding='utf-8')
                cipher = encrypt(key, nonce, associated_data,
                                 temp_plaintext.tobytes(), variant, tagsize)
                cipher_array = BitArray(cipher) ^ BitArray(original_cipher)
                for cipher_position in range(
                        0, plaintext_bit_size + (tagsize * 8)):
                    matrix[bit_position][cipher_position] += int(
                        cipher_array.bin[cipher_position])

        flip_probabilty = 0.5
        expected_count = sample_size * flip_probabilty
        with open('sac_results.txt', 'a') as f:
            f.write(variant + "\n")
            for row in range(0, (plaintext_bit_size)):
                for column in range(0, plaintext_bit_size + (tagsize * 8)):
                    statistics, pvalue = chisquare([
                        int(matrix[row][column]),
                        int(sample_size - matrix[row][column])
                    ], [expected_count, expected_count])
                    f.write(str(pvalue) + "\n")
                    print("Values Stat & P-Value")
                    print(statistics)
                    print(str(pvalue))
Пример #8
0
def handleGetLookup(arguments):
	if not 'source' in arguments:
		return show404()
		
	source = arguments['source'].value
	key = arguments['key'].value
	lookup = generateLookup()
	md5 = generateMD5()
	timestamp = getTimestamp()

	cnx = mysql.connector.connect(user=USER, password=PASSWORD, database=DATABASE)
	cursor = cnx.cursor()
	
	try:

		addTokenEntry = (	
							"INSERT INTO oauth "
							"(lookup, md5, token, source, timestamp) "
							"VALUES (%s, %s, %s, %s, %s)"
		)
		
		data = (lookup, md5, '', source, timestamp)
	
		cursor.execute(addTokenEntry, data)
		
		cnx.commit()
	finally:
		cursor.close()
		cnx.close()
	
	import encryption
	
	print "Content-Type: application/json"
	print
	print encryption.encrypt(json.dumps({'lookup':lookup,'md5':md5}),key)
Пример #9
0
def main():
    config = receiveConfig()

    if config.encrypt:
        encrypt(config.encrypt)
    elif config.decrypt:
        handle_ouput(decrypt(config.decrypt), config.output)
Пример #10
0
def test_encrypt_works_with_negative_offsets():
    assert_equal(encrypt(cleartext, -2),
                 'RFC OSGAI ZPMUL DMV HSKNQ MTCP RFC JYXW BME')
    assert_equal(encrypt(cleartext, -11),
                 'IWT FJXRZ QGDLC UDM YJBEH DKTG IWT APON SDV')
    assert_equal(encrypt(cleartext, -4),
                 'PDA MQEYG XNKSJ BKT FQILO KRAN PDA HWVU ZKC')
def encrypt_credit_card(encryption_key, entry):
    entry['name'] = encrypt(encryption_key, entry['name'])
    entry['number'] = encrypt(encryption_key, entry['number'])
    entry['expiration_date'] = encrypt(encryption_key, entry['expiration_date'])
    entry['cvv'] = encrypt(encryption_key, entry['cvv'])
    entry['cardholder_name'] = encrypt(encryption_key, entry['cardholder_name'])
    return entry
Пример #12
0
def test_encrypt_returns_the_encrypted_string_capitalized():
    assert_equal(encrypt(cleartext, 3),
                 'WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ')
    assert_equal(encrypt(cleartext, 13),
                 'GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT')
    assert_equal(encrypt(cleartext, 5),
                 'YMJ VZNHP GWTBS KTC OZRUX TAJW YMJ QFED ITL')
Пример #13
0
def upload(request):
    uploadedfile = upload_receive(request)
    if not uploadedfile == None:
        if 'encryptKey' in request.POST:

            encryptionKey = request.POST['encryptKey']
            fileName = uploadedfile.name

            file_dict = {
                'name' : fileName,
                'size' : uploadedfile.size
                # The assumption is that file_field is a FileField that saves to
                # the 'media' directory.
                #                 'url': inputDir + '/' + basename,
                #                 'thumbnailUrl': inputDir + '/' + basename,
            }
            if (uploadedFile.objects.filter(name=fileName).count() > 0):
                file_dict['error'] = 'Failed to upload file! (file with same name already exists)'
            else:
                save_file(uploadedfile)
                fileHash = hashlib.md5(open(os.path.join(inputDir,fileName),'rb').read()).hexdigest()

                if (uploadedFile.objects.filter(hash=fileHash).count() > 0):
                    file_dict['error'] = 'Failed to upload file! (file with same name already exists)'
                    os.remove(os.path.join(inputDir, fileName))
                elif(uploadedfile.size == 0):
                    file_dict['error'] = 'Failed to upload file! (file does not have any content)'
                else:
                    uid = fileHash[:8] + str(request.user.pk)
                    os.rename(os.path.join(inputDir,fileName), os.path.join(inputDir,uid))
                    instance = uploadedFile()
                    instance.uid = uid
                    instance.hash = fileHash
                    instance.key = encryptionKey
                    instance.filesize = uploadedfile.size
                    instance.name = fileName
                    instance.ownerInfo = request.user.first_name + " " + request.user.last_name
                    instance.uploadDT = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    instance.save()
                    request.user.owns.add(instance)
                    request.user.uploaded_fileSize = str(int(request.user.uploaded_fileSize) + int(uploadedfile.size))
                    request.user.save()
                    file_dict['deleteUrl'] = reverse('jfu_delete', kwargs = { 'pk': instance.uid })
                    file_dict['deleteType'] = 'POST'
                    # os.system("mpiexec.openmpi -np 3 -machinefile /home/pi/machine python -c \"execfile('/home/pi/onDemandEncrypt/src/file/encryption.py');encrypt('%s','%s','$s',$d)")%(os.path.join(inputDir,uid), inputDir + "/encrypted/" + uid,encryptionKey,32)
                    encrypt(os.path.join(inputDir,uid), inputDir + "/encrypted/" + uid,encryptionKey,32)



        else:
            file_dict = {
                'error':'Missing encryption key!'
            }
        return UploadResponse(request, file_dict)
    else:
        return HttpResponseRedirect(reverse('login'))
Пример #14
0
    def __init__(self, data):
        """__init__
        """

        self.kek = get_random_bytes(32)
        self.dek = get_random_bytes(32)
        self.data = data
        self.encryped_data = encrypt(self.data, self.dek)
        self.encryped_dek = encrypt(self.dek, self.kek)
        self.kekHex = b64encode(self.kek)
Пример #15
0
 def encrypt(self):
     parser = argparse.ArgumentParser(
         description='Encrypt the files listed in encrypted_files.txt')
     parser.add_argument('path')
     args = parser.parse_args(sys.argv[2:])
     print('Running dada encrypt, path=%s' % args.path)
     cleaned_path = args.path.replace('\\', '/')
     if not cleaned_path.endswith('/'):
         cleaned_path = f'{cleaned_path}/'
     encrypt(cleaned_path)
Пример #16
0
def file_write(file_dir, file_name,  password):
       password = getkey(password)
       filepath = dirpath + '\\' + filename
		curr.execute("INSERT INTO CREDENTIALS (FILENAME,KEY) \
		VALUES ( ?,?,? )",(file_dir, file_name, password,));
		conn.commit()
		conn.close()
		encrypt(password,file_dir, file_name)
		os.popen('attrib +h (encrypted)' + file_name)
		os.remove(file_name)
Пример #17
0
def insert_car(car):
    '''Inserts (encrypted) car data into the database'''
    
    # loop through values and encrypt them one by one.
    for attr, value in car.__dict__.items():
        car.__dict__[attr] = encrypt(str(value))
    
    # connect and insert
    conn = sqlite3.connect('cars.db')
    query = "INSERT INTO CARS (NUMBER, RELEASEYEAR, FUEL, FORBIDDEN, TIME_ENTERED, TIME_LEFT) VALUES (?, ?, ?, ?, ?, ?);"
    # insert empty value for TIME_LEFT because car is entering
    conn.execute(query, [car.number, car.year, car.fuel, car.forbidden, car.time, encrypt('0')])
    conn.commit()
    conn.close()
Пример #18
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)
Пример #19
0
def sendmessage(request):
    form = MessageForm(request.POST or None)
    title = 'SEND NEW Message'
    context = {'title': title, 'form': form}

    if form.is_valid():

        # POST has a hash as well. Raw data. Don't do this
        # print(request.POST['email'])

        instance = form.save(commit=False)
        instance.sender = Reporter.objects.get(user_name=request.user)
        if instance.is_private == True:

            #print("sender password: %s " % (instance.send_to.password))
            #print("sending content: %s" % (instance.content))
            instance.content = base64.b64encode(
                encrypt(instance.content, instance.send_to.password))

        # commit=True
        instance.save()
        # print(instance.timestamp)
        context = {
            'title': "Thank you!",
        }
        return redirect('secureshare.views.sent')

    return render(request, 'sendmessage.html', context)
Пример #20
0
def process_infoReport(client, cur_toolaccount):
    """
    when start up, report this device's basic info
    """
    # 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)
    cur_ip = getInfo.get_curIp(cur_os)
    cur_sn = getInfo.get_curSn(cur_os)
    cur_cpu = getInfo.get_curCpu(cur_os)
    cur_version = getInfo.get_curVersion()

    # send out msg
    resultdict = {}
    resultdict.update({"msgType": "info_report"})
    resultdict.update({"curtoolaccount": cur_toolaccount})
    resultdict.update({"curmac": cur_mac})
    resultdict.update({"curcpu": cur_cpu})
    resultdict.update({"curos": cur_os})
    resultdict.update({"curip": cur_ip})
    resultdict.update({"heartbeattime": time.strftime('%Y-%m-%d-%H', time.localtime(time.time())) })
    resultdict.update({"curversion": cur_version})
    resultdict.update({"curuser": cur_user})
    resultdict.update({"cursn": cur_sn})
    resultMsg_json = json.dumps(resultdict)
    resultMsg_json_encrypt = encryption.encrypt(11, resultMsg_json)

    topic = "topic_dev2ser/dev_info/" + 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)
Пример #21
0
 def addapp(self, key, username):  ## Add an app to the allowed apps
     app = self.keyhandle(key)  #Run self.keycheck
     rtn = SecureUse.lookup("username", username, key)
     rtn_ec = SecureUse.lookup("username_enc", username, key)
     username = rtn_ec[0]
     password = rtn_ec[1]
     Firstname = rtn_ec[2]
     Lastname = rtn_ec[3]
     email = rtn_ec[4]
     apps = rtn[5] + "," + app
     apps = ec.encrypt(apps, self.decryption_key)
     dels = ("DELETE FROM userdb WHERE username='******'")
     cursor = cnx.cursor()
     cursor.execute(dels)
     cnx.commit()
     cursor.close()
     time.sleep(1)
     upld = (
         "INSERT INTO userdb "
         "(username, password, Firstname, Lastname, email, apps)"
         "VALUES (%(username)s, %(password)s, %(Firstname)s, %(Lastname)s, %(email)s, %(apps)s)"
     )
     upld_dat = {
         'username': username,
         'password': password,
         'Firstname': Firstname,
         'Lastname': Lastname,
         'email': email,
         'apps': apps
     }
     cursor = cnx.cursor()
     cursor.execute(upld, upld_dat)
     cnx.commit()
     cursor.close()
     self.log(app, " Added app to account: " + str(rtn[0]))
Пример #22
0
 def delapp(self, key, username):  #Delete all apps registered with the user
     app = self.keyhandle(key)  #Run self.keycheck
     rtn = SecureUse.lookup("username", username, key)
     rtn_ec = SecureUse.lookup("username_enc", username, key)
     apps = ""
     apps = ec.encrypt(apps, self.decryption_key)
     #    print(rtn_ec[0])
     test = ("SELECT * FROM userdb WHERE username='******'")
     cursor = cnx.cursor()
     cursor.execute(test)
     x = 0
     for item in cursor:
         x = x + 1
     if x == 0:
         print("[ BACKEND ] : There are no users with that name")
         return "ERROR"
     dat = (apps, rtn_ec[0])
     addapp = ("""
            UPDATE userdb
            SET apps=%s
            WHERE username=%s
             """)
     cursor = cnx.cursor()
     cursor.execute(addapp, dat)
     cnx.commit()
     cursor.close()
     self.log(app, " Deleted apps on account: " + str(username))
Пример #23
0
def quitchat(rec_uname):
    global username
    data_to_send = "{'cmd':'quitchat','rec_uname':'%s','from_uname':'%s'}"%(rec_uname,username)
    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.send(outp)
Пример #24
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)
Пример #25
0
 def test_hackerrank_sample4(self):
     """Validate provided test.
     """
     result = encrypt('iffactsdontfittotheorychangethefacts')
     self.assertEquals(
         result,
         ['isieae', 'fdtonf', 'fotrga', 'anoyec', 'cttctt', 'tfhhhs'])
def add_file(*args, **kwargs):
    if len(args) == 0 or '--help' in ''.join(args):
        map(print, [
            'About: This command adds a file to Dropbox by encrypting and signing the file using your private key.',
            '',
            'Usage: $ dcc add <path,...>',
            '',
            'Specify one or more paths delimited by spaces. Paths to files can be absolute or relative but must',
            'point to a file. Paths can refer to files outside of this directory.',
        ])
        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)
    for arg in args:
        if len(arg) > 0:
            full_path = normpath(join(getcwd(), arg))
            if isfile(full_path):
                with open(full_path, 'r') as source_file:
                    file_uuid = vfs.add_file(full_path)
                    upload_file(
                        api_token, container_name,
                        encrypt(source_file.read(), encryption_key,
                                signing_key), file_uuid)
                    print('[DONE] `%s` ~> `%s`' % (full_path, file_uuid))
    save_vfs(api_token, container_name, vfs, encryption_key, signing_key)
    return 0
Пример #27
0
def create_user():
    if request.method == 'POST':
        if db.user_exists(request.form['username']):
            flash('User already exsits')

        elif request.form['password'] != request.form['password2']:
            flash('Passwords do not match')

        else:
            collection.insert_one({
                'first_name':
                request.form['first_name'],
                'last_name':
                request.form['last_name'],
                'username':
                request.form['username'],
                'password':
                enc.encrypt(request.form['password']),
                'date_created':
                int(time())
            })

            session['USERNAME'] = request.form['username']
            session['PASSWORD'] = request.form['password']

        return redirect(url_for('index'))

    else:
        return 'Please use a post request'
    def write(self, path, buf, offset, fh):
        fullpath = self._full_path(path)

        #compute the entire plaintext to be written to the file
        #currently does not support writing less than the entire file
        plaintext = buf
        try:
            f = open(fullpath, 'r')
            data = f.read()

            #prevent useless metadata files. should clean them on deletes / truncates
            if len(data) > 0:
                data = self.decrypt_with_metadata(path, data)
                plaintext = data[:offset] + buf + data[(offset + len(buf)):]
            f.close()
        except IOError:
            plaintext = buf
        
        #encrypt and write the metadata file
        filedata = encrypt(plaintext, self.encryption_key, self.signing_key)
        padlength = padding_length(len(plaintext))
        self.write_metadata_file(path, filedata, padlength)

        #write the actual file. The first 80 bytes of filedata are the 
        #hex digest + the iv. The last "padlength" bytes are block padding
        os.lseek(fh, 0, os.SEEK_SET)
        bytes_written = os.write(fh, filedata[self.metadata_header_length:(-1*padlength)])
        return min(len(buf), bytes_written)
Пример #29
0
def register():
    if request.method == "POST":
        result = db.execute("SELECT * FROM user WHERE username = :username",
                            username=request.form.get("username"))
        print("check")
        if result:
             flash("Username is already taken! Please try again.")
             return render_template("register.html")

        session["user_id"] = db.execute("INSERT INTO user(username, hash,status) VALUES (:username, :hash, :status)", username=request.form.get("username"),
                                        hash=generate_password_hash(request.form.get("password")), status=0)
        username=request.form.get("username")

        if not re.match(r"^[A-Za-z0-9._%+-][email protected]$", username):
            flash("Email Address must be a valid Harvard College email address")
            return render_template("register.html")

        password=request.form.get("password")
        if not re.match(r"^([^0-9]*|[^A-Z]*)$", password):
            flash("Password must contain at least 1 uppercase letter and 1 number")
            return render_template("register.html")

        token=encrypt(username)
        email=token
        print(token)
        confirm_url = url_for('confirm_email', token=token, _external=True)
        msg = Message('Confirmation', sender = '*****@*****.**', recipients = [username])
        msg.body = "Confirmation link: " + confirm_url
        mail.send(msg)
        print("Sent")
        return redirect(url_for("unconfirmed"))
    else:
        return render_template("register.html")
Пример #30
0
def exit_car(id, time):
    '''Updates TIME_LEFT of existing row where id=id'''
    conn = sqlite3.connect('cars.db')
    query = "UPDATE CARS SET TIME_LEFT=(?) WHERE ID={};".format(id)
    conn.execute(query, [encrypt(time)])
    conn.commit()
    conn.close()
Пример #31
0
def change_password():
	auth_status = auth()
	if not auth_status[0]:
		return redirect(url_for('index'))

	if request.method == 'GET':
		return redirect(url_for('settings.index'))

	if not authenticate(auth_status[1].username, request.form['currentPassword']):
		flash('Incorrect current password, your password has NOT changed')
		return redirect(url_for('settings.index'))

	if request.form['newPassword'] != request.form['newPassword2']:
		flash('Your passwords did not match')
		return redirect(url_for('settings.index'))

	collection.update_one(
		{'_id': auth_status[1].id},
		{ '$set': {
			'password': enc.encrypt(request.form['newPassword'])
		}}
	)

	session['PASSWORD'] = request.form['newPassword']
	flash('Password successfully changed, make sure to save it!')
	return redirect(url_for('settings.index'))
Пример #32
0
    def generate_special(self, key, app):
        import random
        self.keyhandle(key)
        selected = random.randint(1, 10)
        # print(selected)
        tmp = []
        prev_rand = 0
        x = 0
        rand = 0
        while x < 10:
            x = x + 1
            #print(str(selected)+":"+str(x))
            for i in range(4):
                rand = random.randint(1, 200000)
                prev_rand = prev_rand + rand
            final = ec.encrypt(str(prev_rand), self.decryption_key)
            if int(x) == int(selected):
                #print("Adding encrypted app dat")
                rtn = ec.encrypt(str(app), self.decryption_key)
                tmp.append(rtn)
            else:
                tmp.append(final)
        for item in tmp:
            print("[ BACKEND ] : Generated: " + str(item))
        for item in tmp:
            print("[ BACKEND ] : Decrypted: " +
                  ec.decrypt(item, self.decryption_key))

        executable = ("INSERT INTO authorizations "
                      "(app, line, code)"
                      "VALUES (%(app)s, %(line)s, %(code)s)")
        dat = {
            'app': str(ec.encrypt(app, self.decryption_key)),
            'line': str(ec.encrypt(str(selected), self.decryption_key)),
            'code': rtn
        }
        cursor = cnx.cursor()
        cursor.execute(executable, dat)
        cnx.commit()
        cursor.close()
        print("[ BACKEND ] : System has generated the application information")
        open("magic/" + app + ".zauth", "w+").write("")
        for item in tmp:
            open(app.decode() + ".zauth", "a").write(item + "\n")
        print("[ BACKEND ] : Special file has been generated: " +
              str(app + ".zauth"))
        self.log(app, "New Special file was generated!")
Пример #33
0
 def p_encryption_key_request(self, c):
     self.event.on_encryption_key_request.fire(server_id=c.server_id, public_key=c.public_key, verify_token=c.verify_token)
     if config.USE_ENCRYPTION:
         self.cipher = encryption.make_aes(self.factory.client_key, self.factory.client_key)
         self.decipher = encryption.make_aes(self.factory.client_key, self.factory.client_key)
         public_key = encryption.load_pubkey(c.public_key)
         enc_shared_sercet = encryption.encrypt(self.factory.client_key, public_key)
         enc_4bytes = encryption.encrypt(c.verify_token, public_key)
         if config.ONLINE_LOGIN:
             yield self.do_auth(c.server_id, c.public_key)
         self.send_packet("encryption key response",
                          {"shared_length": len(enc_shared_sercet),
                          "shared_secret": enc_shared_sercet,
                          "token_length": len(enc_4bytes),
                          "token_secret": enc_4bytes})
     else:
         self.send_packet("client statuses", {"status": 0})
Пример #34
0
def changeCredentials(server,
                      port,
                      user,
                      password,
                      pwd,
                      file="secret_credentials.json"):
    jsonenc = JSONEncoder()

    data = {"SERVER": server, "PORT": port, "USER": user, "PASSWORD": password}

    json = jsonenc.encode(data)

    print("Opening credential file...")
    encryption.encrypt(text=json, password=pwd)
    print("Saving...")

    return
Пример #35
0
def secure_wallet(full_wallet_material_name, paper_password):
    """Encrypt and encode the wallet.

    Pass path to wallet file, not directory. Compatible with openssl, use
    $ openssl enc -base64 -d -in ./wallet.aes.b64 -out ./wallet.aes | \
        openssl aes-256-cbc -d -in wallet.aes -out ./wallet.dec
    to decode / decrypt."""

    wallet_aes = full_wallet_material_name + '.aes'
    wallet_b64 = wallet_aes + ".b64"
    with open(full_wallet_material_name, 'rb') as fin, open(wallet_aes, 'wb') as fout:
        encrypt(fin, fout, paper_password, key_length=16)

    with open(wallet_aes, 'rb') as fin, open(wallet_b64, 'wb') as fout:
        base64.encode(fin, fout)
    
    # return full encrypted wallet material name
    return wallet_b64
def make_dccfile(master_password, signing_password):
    container_name = b64encode('%s%s' % (''.join([str(randint(1, 10)) for _ in xrange(0, 5)]), raw_input('Container Name: ').strip()[:50]))
    dropbox_token = raw_input('Dropbox API Token: ').strip()
    with open(join(getcwd(), '.dcc'), 'w+') as dcc_file:
        salt_1, salt_2 = urandom(8), urandom(8)
        encryption_key, signing_key = PBKDF2(master_password, salt_1).read(32), PBKDF2(signing_password, salt_2).read(32)
        encrypted_content = encrypt(pickle.dumps(dict(cn=container_name, dbtk=dropbox_token)), encryption_key, signing_key)
        dcc_file.write('%s%s%s' % ( salt_1, salt_2, encrypted_content ))
        return ( container_name, dropbox_token )
Пример #37
0
 def encrypt(self,pkt):
     data = encrypt()
     if data != "already encrypted":
         pkt.data = data
         pkt.length = len(data)
     else:
         pkt.data = "nope"
         pkt.length = 4
     
     self.enqueue(pkt)
Пример #38
0
 def p_encryption_key_request(self, c):
     if config.USE_ENCRYPTION:
         try:
             self.cipher = encryption.make_aes(self.factory.client_key, self.factory.client_key)
             self.decipher = encryption.make_aes(self.factory.client_key, self.factory.client_key)
             public_key = encryption.load_pubkey(c.public_key)
             enc_shared_sercet = encryption.encrypt(self.factory.client_key, public_key)
             enc_4bytes = encryption.encrypt(c.verify_token, public_key)
             if config.ONLINE_LOGIN:
                 yield self.do_auth(c.server_id, c.public_key)
             self.send_packet("encryption key response",
                              {"shared_length": len(enc_shared_sercet),
                              "shared_secret": enc_shared_sercet,
                              "token_length": len(enc_4bytes),
                              "token_secret": enc_4bytes})
         except ImportError:
             log.msg('PyCrypto not installed, skipping encryption.')
             self.send_packet("client statuses", {"status": 0})
     else:
         log.msg('USE_ENCRYPTION is False, skipping encryption.')
         self.send_packet("client statuses", {"status": 0})
Пример #39
0
 def login_view(self):
     message = ''
     if 'form.submitted' in self.request.params:
         username = self.request.params['login'].lower()
         password = self.request.params['password']
         try:
             r = select_from('user_info', 'username', username)
             if r[2] == encrypt(username, password) and username == r[1]:
                 temp = generate_random()
                 self.request.session['username'] = username
                 self.request.session['enpass'] = encrypt(password, temp)
                 res = HTTPFound(location='/school')
                 res.set_cookie('r', temp)
                 return res
             else:
                 message = 'Failed Login'
         except:
             message = 'Failed Login'
         message = 'Failed Login'
     re = {'page_title': LINKS['login']['title'], 'url' : self.request.application_url + '/login', 'message' : message }
     re.update(self.get_header())
     return re
Пример #40
0
 def p_encryption_key_request(self, c):
     if config.USE_ENCRYPTION:
         try:
             import encryption
             key16 = encryption.get_random_bytes()
             self.cipher = encryption.make_aes(key16, key16)
             self.decipher = encryption.make_aes(key16, key16)
             public_key = encryption.load_pubkey(c.public_key)
             enc_shared_sercet = encryption.encrypt(key16, public_key)
             enc_4bytes = encryption.encrypt(c.verify_token, public_key)
             self.send_packet(
                 "encryption key response",
                 {"shared_length": len(enc_shared_sercet),
                  "shared_secret": enc_shared_sercet,
                  "token_length": len(enc_4bytes),
                  "token_secret": enc_4bytes})
         except ImportError:
             log.msg('PyCrypto not installed, skipping encryption.')
             self.send_packet("client statuses", {"status": 0})
     else:
         log.msg('USE_ENCRYPTION is False, skipping encryption.')
         self.send_packet("client statuses", {"status": 0})
Пример #41
0
def main(filename):
    with open(filename) as text:
        intText = list(map(int, text.read().split(',')))
        chrText = list(map(chr, intText))
        frequencies = text_analyzer.text_analyzer(filename)

        print('\nCreating brute force encryption file...')
        brute_force.brute_force_encrypt(chrText, 97, 123)
        print('Please review the created file to obtain the password')

        password = input('\nWhat is the determined password: '******'\nThe sum of the encrypted message is %d' % sum(message))
Пример #42
0
 def _import(self, db, data, flags, encrypted=False):
     if type(data) is dict:
         if encrypted:
             for entry in data:
                 data[entry] = encryption.encrypt(data[entry])
         cpy = data.copy()
         for entry in data:
             if self.is_wrapped(entry) == "&":
                 cpy[cityhash.to_city_hash(self.unwrap(entry))] = data[entry]
                 del cpy[entry]
     elif type(data) is str:
         if encrypted:
             cpy = encryption.encrypt(data)
         else:
             cpy = data
     elif type(data) is list:
         if encrypted:
             lst = []
             for entry in data:
                 lst.append(encryption.encrypt(entry))
             cpy = lst
         else:
             cpy = data
     super(DynamicDefault, self)._import(db, cpy, flags)
Пример #43
0
def checkLogin(username, password):
    """
        Validates a login
    """
    
    return True
    
    encryptedPassword = encryption.encrypt(settings.settings['loginPasswordEncryptionKey'], password)
    
    sql = """
        SELECT 1 FROM pUser
        WHERE strUser = %s
            AND strPassword = %s"""
    
    return database.executeOneToDictionary(sql, (username, encryptedPassword)) != None
Пример #44
0
def brute_force_encrypt(chrText, firstChr, lastChr):
    output = open('bruteforceoutput.txt', 'w')

    for letter1 in range(firstChr, lastChr):
        for letter2 in range(firstChr, lastChr):
            for letter3 in range(firstChr, lastChr):
                password = str(chr(letter1) + chr(letter2) + chr(letter3))
                message = encryption.encrypt(chrText, password)
                output.write('\n')
                output.write('Password: %s' % password)
                output.write('\n')
                output.write('Decrypted Message')
                output.write('\n')
                output.write(''.join(chr(e) for e in message))

    output.close()
Пример #45
0
def watchAdd(path, ip):
    watch = observer.schedule(FileWatch(ip,configfile.protocol, configfile.password, configfile.masterkey), path)
    observer.start()
    message = "Watch added"
    time.sleep(1)
    encryptedMessage = encryption.encrypt(message, configfile.masterkey)
    helpers.sendMessage(encryptedMessage
                       , configfile. password
                       , configfile.protocol
                       , ip
                       , 8000)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
Пример #46
0
def shellCommand(packet, command):
    print "Running command " + command
    ip = packet[IP].src
    output = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output = output.stdout.read() + output.stderr.read()
    encryptedData = encryption.encrypt(output, configfile.masterkey)
    encryptedData = helpers.chunkString(2, encryptedData)
    lastIndex = len(encryptedData) - 1
    time.sleep(1)
    for index, chunk in enumerate(encryptedData):
        if len(chunk) == 2:
            pairs = list(chunk)
            packet = helpers.createPacketTwo(configfile.protocol, ip, pairs[0], pairs[1], 8000)
        elif len(chunk) == 1:
            packet = helpers.createPacketOne(configfile.protocol, ip, chunk, 8000)
        if index == lastIndex:
            packet = packet/Raw(load=configfile.password)
        send(packet, verbose=0)
        time.sleep(0.1)
def add_file(*args, **kwargs):
    if len(args) == 0 or '--help' in ''.join(args):
        map(print, [
            'About: This command adds a file to Dropbox by encrypting and signing the file using your private key.',
            '',
            'Usage: $ dcc add <path,...>',
            '',
            'Specify one or more paths delimited by spaces. Paths to files can be absolute or relative but must',
            'point to a file. Paths can refer to files outside of this directory.',
        ])
        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)
    for arg in args:
        if len(arg) > 0:
            full_path = normpath(join(getcwd(), arg))
            if isfile(full_path):
                with open(full_path, 'r') as source_file:
                    file_uuid = vfs.add_file(full_path)
                    upload_file(api_token, container_name, encrypt(source_file.read(), encryption_key, signing_key), file_uuid)
                    print('[DONE] `%s` ~> `%s`' % (full_path, file_uuid))
    save_vfs(api_token, container_name, vfs, encryption_key, signing_key)
    return 0
Пример #48
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()
Пример #49
0
 def _encrypt_sign(self, value, encrypt_key, sign_key=None):        
     self._statusByte = 0b00000100 | self._statusByte
     if sign_key:
         self._statusByte = 0b00000001 | self._statusByte
     
     return encryption.encrypt(value, encrypt_key, sign=sign_key, always_trust=True)
def test_encrypt_works_with_negative_offsets():
    assert_equal(encrypt(cleartext, -2), 'RFC OSGAI ZPMUL DMV HSKNQ MTCP RFC JYXW BME')
    assert_equal(encrypt(cleartext, -11), 'IWT FJXRZ QGDLC UDM YJBEH DKTG IWT APON SDV')
    assert_equal(encrypt(cleartext, -4), 'PDA MQEYG XNKSJ BKT FQILO KRAN PDA HWVU ZKC')
Пример #51
0
                size = sys.getsizeof(answers)

                #print "size"
                #print size

                temp2 = ""

                if size > 64:

                    for k in range(len(answers)):

                        temp2 = temp2 + answers[k]

                        if sys.getsizeof(temp2) == 64:

                            crypted_answ = encryption.encrypt(temp2, key_table[i+1])
                            data = struct.pack("!??HH64s", False, True, len(answ), 0, crypted_answ)
                            sUDP.sendto(data, ((host, port)))

                            temp2 = ""

                    crypted_answ = encryption.encrypt(temp2, key_table[i+1])
                    data = struct.pack("!??HH64s", False, True, len(answ), 0, crypted_answ)
                    sUDP.sendto(data, ((host, port)))


                    #crypted_answ = encryption.encrypt(answ, key_table[i+1])
                break
            else:

                answ = answer(question)
Пример #52
0
    def files_list_view(self):
        if not 'password' in self.request.POST and self.check():
            print self.request.POST
            return HTTPFound(location='/login')
        url = USB_LOCATION + get_url(self.request.matchdict['list'])
        url_parsed = '/'
        for i in range(len(url.split('/')) - 3):
            url_parsed += url.split('/')[i + 1] + '/'
        action = url.split('/')[-2]
        filename = str(url_parsed.split('/')[-2])
        if 'password' in self.request.POST:
            if self.request.POST['password'] != '':
                password = self.request.POST['password']
#                print password
                content = encrypt(self.request.POST['notecontent'], password)
                write('/'.join(url.split('/')[:-2]), content)
                return HTTPFound(location='/files' + url[:-1])
#                return Response()
        elif 'file' in self.request.POST:
            filename = self.request.POST['file'].filename
            print filename
            input_file = self.request.POST['file'].file
            upload(input_file, url, filename)
            print '/files' + url
            return HTTPFound(location='/files' + url)
        elif 'dir_name' in self.request.POST:
            dirname = self.request.POST['dir_name']
            make_dir(dirname, url)
            return HTTPFound(location='/files' + url)
        elif 'note_name' in self.request.POST:
            write(url + self.request.POST['note_name'], '')
            return HTTPFound(location='/files' + url)
        elif 'notecontent' in self.request.POST:
            content = encrypt(self.request.POST['notecontent'], decrypt(self.request.session['enpass'], self.request.cookies['r']))
            write('/'.join(url.split('/')[:-2]), content)
            return HTTPFound(location='/files' + url)
        elif action == 'edit':
            content = decrypt(read(url_parsed[:-1]), decrypt(self.request.session['enpass'], self.request.cookies['r']))
            re = { 'page_title' : 'Notes', 'edit' : True, 'contents' : content, 'url' : url }
            re.update(self.get_header())
            return re
        elif action == 'rename':
            # file_old = str(url_parsed.split('/')[-3])
            file_old = '/'.join(url_parsed.split('/')[:-2])
            if not is_file('/'.join(url_parsed.split('/')[:-2])) and not is_dir('/'.join(url_parsed.split('/')[:-2])):
                print 'not filename'
                return HTTPFound(location='/files')
            rename(file_old, filename)
            return HTTPFound('/files' + '/'.join(url.split('/')[:-4]))
        elif is_file(url_parsed[:-1]):
            if action == 'download':
                re = FileResponse(url_parsed[:-1])

                re.headers['Content-Disposition'] = 'attachment; filename="' + filename + '"'
                re.headers['Content-Type'] = 'application/force-download'
#                re.headers['filename'] = filename
                re.headers['Accept-Ranges'] = 'bytes'
                return re
            elif action == 'delete':
                delete(url_parsed[:-1])
                return HTTPFound(self.request.url[:-7-len(filename.replace(' ', '%20'))])
        elif is_dir(url[:-7]) and action == 'delete':
            delete(url[:-7])
            return HTTPFound(self.request.url[:-7-len(filename)])
        elif not is_dir(url) or len(url.split('/')) < 5:
            return HTTPFound(location='/files')
        temp = [str(part) for part in list_dir(url)]
        temp.sort(lambda x, y: cmp(x.lower(),y.lower()))
        item_list = [ { 'url' : '/files/' + url[1:] + part if is_dir(url + part) else '/files/' + url[1:] + part + '/download', 'url_ren' : '/files/' + url[1:] + part, 'url_del' : '/files/' + url[1:] + part + '/delete', 'name' : part, 'is_file' : is_file(url + part), 'size' : size(url + part) } for part in temp ]
        
        re = {'page_title': LINKS['files_list']['title'], 'list' : item_list, 'up_dir' : '/files/' + url_parsed[1:], 'url' : url, 'edit' : False }
        re.update(self.get_header())
        return re
def test_encrypt_returns_the_encrypted_string_capitalized():
    assert_equal(encrypt(cleartext, 3), 'WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ')
    assert_equal(encrypt(cleartext, 13), 'GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT')
    assert_equal(encrypt(cleartext, 5), 'YMJ VZNHP GWTBS KTC OZRUX TAJW YMJ QFED ITL')
def test_encrypt_accepts_lower_and_upper_case_letters():
    assert_equal(encrypt('The quiCk broWn fox JUMPS over the lazY dog', offset), 'WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ')
Пример #55
0
			else:
				inv_SBox[i][j] = 0
			SBox[i][j] = calc.bit_scrb(SBox[i][j],'encrypt')

	return (SBox, inv_SBox)

StateArray = []
choice = raw_input("1.Encrypt\n2.Decrypt\nEnter 1 or 2: ")
inpath = raw_input("Enter inpath: ")
outpath = raw_input("Enter outpath: ")
(inputText,cipherKey) = inPlainTextFile(inpath)	
cipherKeyArray = np.asarray(cipherKey).reshape(4,4).T
keyWord = []
keyWord = cipherKeyArray.T.tolist()
(S_box, inv_S_box) = genTables()
keys = keyExpansion_G(keyWord)
for i in range(len(inputText)/16):
	StateArray = np.asarray(inputText[16*i:16*(i+1)]).reshape(4,4).tolist()
	if choice == '1':
		StateArray = en.encrypt(StateArray,S_box,keys)
		npArray = np.array(StateArray).T.tolist()
		out = [value for rows in npArray for value in rows]
		outTextFile(out,outpath)
	else:
		StateArray = np.array(StateArray).T.tolist()
		StateArray = de.decrypt(StateArray,inv_S_box,keys)
		npArray = np.array(StateArray).tolist()
		out = [value for rows in npArray for value in rows]
		outTextFile(out,outpath)
	
def test_encrypt_raises_ValueError_if_called_with_empty_string():
    with assert_raises(ValueError) as e:
        encrypt('', offset)
    assert_equal(e.exception.message, 'can not encrypt empty string')
def test_encrypt_raises_ValueError_if_called_with_zero_offset():
    with assert_raises(ValueError) as e:
        encrypt(cleartext, 0)
    assert_equal(e.exception.message, 'offset must not be zero')
Пример #58
0
 def encrypt_data(self, data):
     enc_data = encrypt(data, self.encryption_key, self.signing_key)
     meta = self.get_metadata(data, enc_data)
     return (enc_data, meta)
def test_decrypt_returns_a_string():
    assert_is_instance(encrypt(cleartext, offset), str)