Пример #1
0
    def generateMACModel(self, path):
        print("Generating Model MAC...")
        init_time = time.time()
        digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
        os.chdir(path)
        for root, dirs, files in os.walk(path):
            for name in dirs:
                path1 = os.path.join(path, name)
                for root1, dirs1, files1 in os.walk(path1):
                    for file in files1:

                        with open(os.path.join(path1, file), 'rb') as myfile:
                            data = myfile.read()
                            digest.update(data)
                os.chdir(path)

        hashed = digest.finalize()
        f = Fernet(self.key)
        token = f.encrypt(hashed)

        f = open(os.path.join(path, 'modelsignature.txt'), 'w')
        f.write(token)
        f.close()
        final_time = time.time() - init_time
        print("Finished MAC generation in " + "{0:.4f}".format(final_time) +
              " seconds")
Пример #2
0
def enclip(filename):
    salt = b'd8fben47chfbdng6'  # currently using a fixed salt
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()  # other backends are depreciated
    )
    key = base64.urlsafe_b64encode(kdf.derive(encodedPass))

    # output key to file - need to clear key file before every new file :(
    # do an error catch and loop through all keys until either one works or none work
    keyFile = open("keys.txt", 'a')
    keyFile.write(key.decode())
    keyFile.write('\n')
    keyFile.close()

    enclipFile = open(filename, 'rb')
    fileContents = enclipFile.read()
    enclipFile.close()

    f = Fernet(key)
    encrypted = f.encrypt(fileContents)
    # print(encrypted)

    # writing to file

    enclipFileName = filename + ".enclip"
    f = open(enclipFileName, 'wb')
    f.write(encrypted)
    f.close()
    print(key)
    print("File enclipted: " + enclipFileName)
Пример #3
0
def encrypt_write(data, file):
    data = bytes(data, 'utf-8')
    key = load_key()
    f = Fernet(key)
    encrypteddata = f.encrypt(data)
    f = open(file, "wb")
    f.write(encrypteddata)
    f.close()
Пример #4
0
    def encrypt(self, path, ouput_path, include_imports=False, key_length=10):
        if (not path.endswith(".py") and not path.endswith(".pyw")):
            raise Exception("{} is no .py or .pyw File!".format(path))
        imports = ""
        imports += "# FileEncryptor 0.1.6 \n"
        imports += "# https://pypi.org/project/FileEncryption/ \n"
        data = ""
        key = Fernet.generate_key()
        try:
            f = open(path, "r+")
            lines = f.readlines()
            f.close()
        except Exception as e:
            raise Exception(e)
        for line in lines:
            if (line.startswith("import")
                    or line.startswith("from")) and not include_imports:
                imports += line
            else:
                if not line.startswith("#") and not line.startswith("\n"):
                    data += line

        randomname = self.randomstring(key_length)
        randomname1 = self.randomstring(key_length)
        randomname2 = self.randomstring(key_length)
        randomname3 = self.randomstring(key_length)

        imports += "\n"
        imports += "from base64 import b64decode as {}\n".format(randomname)
        imports += "from cryptography.fernet import Fernet as {}\n".format(
            randomname1)
        imports += "{} = {}\n".format(randomname3, key)
        imports += "{} = {}({})\n".format(randomname2, randomname1,
                                          randomname3)
        filedata = imports

        f = Fernet(key)

        filedata += 'exec({}.decrypt({}({})))'.format(
            randomname2, randomname,
            base64.b64encode(f.encrypt(data.encode())))

        f = open(ouput_path, "w")
        f.write(filedata)
        f.close()
Пример #5
0
    def generateMACInput(self, path):
        print("Generating Input MAC...")
        init_time = time.time()
        digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
        with open(os.path.join(path, 'input.npy'), 'rb') as myfile:
            data = myfile.read()
        digest.update(data)

        hashed = digest.finalize()

        f = Fernet(self.key)
        token = f.encrypt(hashed)
        f = open(os.path.join(path, 'signature.txt'), 'w')
        f.write(token)
        f.close()
        final_time = time.time() - init_time
        print("Finished MAC generation in " + "{0:.4f}".format(final_time) +
              " seconds")
Пример #6
0
def declip(filename):
    declipFile = open(filename, 'rb')
    fileContents = declipFile.read()
    declipFile.close()

    # start copy
    salt = b'd8fben47chfbdng6'  # currently using a fixed salt
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()  # other backends are depreciated
    )
    key = base64.urlsafe_b64encode(kdf.derive(encodedPass))
    # end copy
    print(key)

    keyExists = False

    keyFile = open("keys.txt", 'r')
    for x in keyFile:
        if x.strip() == key:
            keyExists = True

    if (not (keyExists)):
        keyFile.close()
        sys.exit("This password is wrong. F**k you! :)")

    keyFile.close()

    f = Fernet(key)
    decrypted = f.decrypt(fileContents)
    #print(decrypted)

    # writing to file
    filename = "declip_" + filename
    declipFileName = filename.replace(".enclip", "", 1)
    f = open(declipFileName, 'wb')
    newContents = decrypted
    f.write(newContents)
    f.close()
    # implement remove .enclip file
    print("File declipted: " + declipFileName)
Пример #7
0
def declip(filename):
    declipFile = open(filename, 'rb')
    fileContents = declipFile.read()
    declipFile.close()

    keyFile = open("keys.txt", 'r')
    key = keyFile.read()
    key = key.encode()
    keyFile.close()

    f = Fernet(key)
    decrypted = f.decrypt(fileContents)
    #print(decrypted)

    # writing to file
    filename = "declip_" + filename
    declipFileName = filename.replace(".enclip", "", 1)
    f = open(declipFileName, 'wb') # does this need to be in byte mode?
    newContents = decrypted #.decode()
    f.write(newContents)
    f.close()
    # remove file
    print("File declipted: " + declipFileName)
Пример #8
0
    with open(filepath, 'rb') as f:
        data = f.read()
        f.close()
    os.remove(filepath)
    f = Fernet(key)
    encrypted = f.encrypt(data)
    with open('vault_encrypted', 'wb') as f:
        f.write(encrypted)
if func == 'u':
    filepath = input('Input encrypted vault filepath: ').encode(
        'unicode-escape').decode().replace('////', '//')
    password_prov = getpass()
    password = password_prov.encode()
    salt = b'nG\xc8\xb0\x84q\x00\x9a\xb8\xa9CT\x915\xa4\xa1'
    kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                     length=32,
                     salt=salt,
                     iterations=100000,
                     backend=default_backend())
    key = base64.urlsafe_b64encode(kdf.derive(password))
    with open(filepath, 'rb') as f:
        data = f.read()
        f.close()
    f = Fernet(key)
    try:
        decrypted = f.decrypt(data)
        vault = decrypted.decode()
        print(vault)
    except:
        print('Wrong password! Vault could not be decrypted!')
Пример #9
0
f = open(keyfile, 'w')
f.write(key.decode('ASCII'))
f.close()

f = Fernet(key)
token = f.encrypt(password.encode('ASCII'))
user = f.encrypt(uname.encode('ASCII'))

root = etree.Element("data")
etree.SubElement(root, "username").text = uname
etree.SubElement(root, "user").text = user
etree.SubElement(root, "password").text = token
xmloutput = etree.tostring(root, pretty_print=True)
f = open(xmlfile, 'w')
f.write(xmloutput.decode('ASCII'))
f.close()
"""
# Read the data again

f = open(keyfile, 'r')
k2=f.readline()
f.close()
key2=k2.encode('ASCII')

tree = etree.parse(xmlfile)
u2=(tree.find("user")).text
p2=(tree.find("password")).text

f = Fernet(key2)
u3 = f.decrypt(u2.encode('ASCII')).decode('ASCII')
p3 = f.decrypt(p2.encode('ASCII')).decode('ASCII')
def proceed():
    h = hashlib.md5(password.encode())
    h2 = h.hexdigest()  # print("Hash value is\n",h2,"\n\n")

    # HASH PART 1
    # print("First half of hashing is\n",hash1,"\n\n")
    hash1 = h2[0:len(h2) // 2]

    # HASH PART 2
    # print("Second half of hashing is\n",hash2,"\n\n")
    hash2 = h2[len(h2) // 2 if len(h2) % 2 == 0 else ((len(h2) // 2) + 1):]

    # HASH PART 1 TO BINARY
    binary = bin(int(hash1, 16))
    binary = binary[2:]  # print("Printing the binary\n",binary,"\n\n")
    binary = binary[2:]

    # TO DO Padding
    n = 4
    splits = [(binary[i:i + n]) for i in range(0, len(binary), n)]
    pos = [
        "2", "3", "1", "3", "2", "3", "1", "3", "2", "2", "3", "2", "1", "3",
        "2", "0"
    ]  # static for now,It will be dynamic for each user
    final_bin = ""
    for i in range(0, len(splits)):
        temp1 = int(pos[i])
        temp2 = str(splits[i])
        f = temp2[temp1]
        final_bin = final_bin + f
    if len(final_bin) != 16:
        final_bin = final_bin + "0"

    # PART 2 AES ENCRYPTION(ENCRYPTING HASH 2 USING HASH1 AS KEY)
    passw = bytes(hash1, encoding='utf-8')  # b"password"   hash1 is the key
    salt = os.urandom(16)
    kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                     length=32,
                     salt=salt,
                     iterations=100000,
                     backend=default_backend())
    key = base64.urlsafe_b64encode(kdf.derive(passw))
    f = Fernet(key)
    # hash2 is the input to be encoded
    token = f.encrypt(bytes(hash2, encoding='utf-8'))
    temporary = token.decode()

    # CODE TO WRITE AES VALUE OF USER TO A TEXT FILE
    os.chdir(username)
    filename1 = "encrypt.txt"
    f = open(filename1, "w")
    f.write(token.decode())  # BYTES TO STRING
    f.close()
    fills = open("key.txt", "w")
    fills.write(key.decode())  # BYTES TO STRING
    fills.close()

    # PART 3
    ip = int(final_bin, 2)  # binary to hexa
    mt = []
    for i in range(0, 65536):
        mt.append(i)
    mt.remove(ip)
    n = 128
    a = [mt[i * n:(i + 1) * n] for i in range((len(mt) + n - 1))]
    patterns = []
    dt = []
    dt.append(0)
    dt.append(65535)
    count = 0
    for i in range(0, 512):
        print("\niteration--> ", count)
        count = count + 1
        patterns.extend(qm(a[i], dt))

    filename2 = "pattern.txt"
    with open(filename2, 'w') as f:
        for item in patterns:
            f.write("%s\n" % item)
            print("\nwriting file\n")
            print(os.getcwd())

    location = os.getcwd()

    # MYSQL CODE
    import string
    import mysql
    import mysql.connector
    config = {
        'user': '******',
        'password': '',
        'host': 'localhost',
        'database': 'semester-8',
        'raise_on_warnings': True,
    }

    link = mysql.connector.connect(**config)
    mycursor = link.cursor(buffered=True)
    sql = "INSERT INTO manage_users(username,encrypted_string,path)VALUES(%s,%s,%s)"
    val = (username, temporary, location)
    mycursor.execute(sql, val)
    print(mycursor.rowcount, "record inserted")
    mycursor.execute("SELECT * FROM manage_users ")
    name = mycursor.fetchall()
    print(name, end="\n\n")
    mycursor.execute("SELECT * FROM manage_users")
    name2 = mycursor.fetchall()
    for i in range(len(name2)):
        print(name2[i], end="\n\n")
    link.commit()