Example #1
0
class Caller:
    """
		Clase de llamada para los algoritmos de encriptacion
	"""
    def __init__(self):
        self.aes = AESEncryptor()
        self.bf = BlowfishEncryptor()
        self.log = Logger()

    def encrypt(self, key, algorithm, path, extraction=None):
        #Comenzamos a tomar el tiempo
        i = self.log.executionTime.getTime()

        if path[0] is "folder":
            if algorithm == "AES256":

                self.aes.setKey(key)
                self.aes.encryptAllInPath(path[1], algorithm, extraction)
            else:
                self.bf.setKey(key)
                self.bf.encryptAllInPath(path[1], algorithm, extraction)
        else:
            if algorithm == "AES256":

                self.aes.setKey(key)
                self.aes.encryptThisFiles(path[1], algorithm, extraction)
            else:
                self.bf.setKey(key)
                self.bf.encryptThisFiles(path[1], algorithm, extraction)
        self.log.openLog()
        self.log.logThis(
            " Tiempo de Encriptacion -> ",
            self.log.executionTime.diff(i, self.log.executionTime.getTime()),
            " milisegundos.")
        self.log.logThis("------------------------------------------")
        self.log.closeLog()

    def decrypt(self, key, algorithm, path, extraction=None):
        #Comenzamos a tomar el tiempo
        i = self.log.executionTime.getTime()

        if path[0] is "folder":
            if algorithm == "AES256":

                self.aes.setKey(key)
                self.aes.decryptAllInPath(path[1], algorithm, extraction)
            else:
                self.bf.setKey(key)
                self.bf.decryptAllInPath(path[1], algorithm, extraction)
        else:
            if algorithm == "AES256":

                self.aes.setKey(key)
                self.aes.decryptThisFiles(path[1], algorithm, extraction)
            else:
                self.bf.setKey(key)
                self.bf.decryptThisFiles(path[1], algorithm, extraction)

        self.log.openLog()
        self.log.logThis(
            " Tiempo de Desencriptacion -> ",
            self.log.executionTime.diff(i, self.log.executionTime.getTime()),
            " milisegundos.")
        self.log.logThis("------------------------------------------")
        self.log.closeLog()
Example #2
0
class BaseEncryptor(object):
    def __init__(self):
        self.key = None
        self.log = Logger()

    def getAllFiles(self, dir_path):
        dirs = []
        for dirName, subdirList, fileList in os.walk(dir_path):
            for fname in fileList:
                dirs.append(os.path.join(dirName, fname))

        return dirs

    def buildPathsFromTree(self, tree, string, arreglo):
        """
			tree hace referencia al arbol TDA
			string debe ser la direccion donde se va extraer
			Arreglo se va a poblar con cada string

			string genera una direccion por cada archivo en el arbol
			root -> nodo1 -> nodo2 -> archivo
			Por cada archivo /root/nodo1/nodo2/archivo
			string/root/nodo1/nodo2/archivo
			llenar el arreglo asi:
			string /home/estudiante/algoritmos/root/nodo1/nodo2/archivo
		"""

        #Busca archivos en el arbol recursivamente
        #Suponiendo que el root es el currentNode
        node = tree.currentNode.value.branches.first
        while node:
            if node.type() == "Carpeta":
                st = os.path.join(string, node.getName())
                tree.currentNode = node
                self.buildPathsFromTree(tree, st, arreglo)
                tree.currentNode = node
            else:
                st = os.path.join(string, node.getName())
                arreglo.append(st)
            node = node.next

    def encryptAllInPath(self, path, algorithm, extractionPath=None):
        self.log.openLog()
        self.log.logThis("Encriptando con ", algorithm, takeTime=True)
        self.log.logThis("Path: ", path, "\n")

        # ExtractionPath es un arreglo distribuido asi:
        # 	[0]  es una ruta especifca existente en el hdd
        #	[1]  es un arbol
        #  Si hay una ruta de extraccion
        if extractionPath:
            # Saco todos los archivos por cada path recibido
            dirs = [x for o in path for x in self.getAllFiles(o)]
            # Replicar misma logica en decrypt
            array = []
            self.buildPathsFromTree(extractionPath[1], extractionPath[0],
                                    array)
            for file in array:
                if os.path.exists(os.path.dirname(file)):
                    continue
                else:
                    os.makedirs(os.path.dirname(file))
            [[self.log.logThis("Encriptando: ", f),
              self.encrypt(f, file)] for file in array for f in dirs
             if os.path.basename(file) == os.path.basename(f)]
        else:
            for p in path:
                dirs = self.getAllFiles(p)
                if len(dirs) > 0:
                    for file in dirs:
                        self.log.logThis("Encriptando: ", file)
                        self.encrypt(file, extractionPath)
                else:
                    self.log.logThis("Esta vacio")
        self.log.closeLog()

    def decryptAllInPath(self, path, algorithm, extractionPath=None):
        self.log.openLog()
        self.log.logThis("\t Desencriptando con ", algorithm, takeTime=True)
        self.log.logThis("Path: ", path, "\n")

        # if extractionPath:
        # 	dirs= [x for o in path for x in self.getAllFiles(o)]
        # 	array= []
        # 	self.buildPathsFromTree(extractionPath[1], extractionPath[0],array)
        # 	for file in array:
        # 		if os.path.exists(os.path.dirname(file)):
        # 			continue
        # 		else:
        # 			os.makedirs(os.path.dirname(file))
        # 	[[self.log.logThis("Desencriptando: ", f),self.decrypt(f,file)] for file in array for f in dirs if os.path.basename(file) == os.path.basename(f) if f[-4:] == '.enc']

        for p in path:
            dirs = self.getAllFiles(p)
            if len(dirs) > 0:
                for file in dirs:
                    if file[-4:] == '.enc':
                        self.log.logThis("Desencriptando: ", file)
                        self.decrypt(file, extractionPath)
            else:
                self.log.logThis("Esta vacio")
        self.log.closeLog()

    def encryptThisFiles(self, path, algorithm, extractionPath=None):
        self.log.openLog()
        self.log.logThis("Encriptando con ", algorithm, takeTime=True)
        self.log.logThis("Path: ", path, "\n")

        for p in path:
            self.log.logThis("Encriptando: ", p)
            if extractionPath:
                self.encrypt(p, extractionPath[0], True)
            else:
                self.encrypt(p)
        self.log.closeLog()

    def decryptThisFiles(self, path, algorithm, extractionPath=None):
        self.log.openLog()
        self.log.logThis("\t Desencriptando con ", algorithm, takeTime=True)
        self.log.logThis("Path: ", path, "\n")

        for p in path:
            self.log.logThis("Desencriptando: ", p)
            if extractionPath:
                self.decrypt(p, extractionPath)
            else:
                self.decrypt(p)
        self.log.closeLog()

    def readFileBytes(self, filename):
        foo = open(filename, 'rb')
        data = foo.read()
        foo.close()
        return data

    def writeFileBytes(self, filename, bufferedData):
        foo = open(filename, 'wb+')
        foo.write(bufferedData)
        foo.close()