66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"StoreBackEnd/pkg/utils/crypto"
|
||
|
"math/rand"
|
||
|
"os"
|
||
|
"strconv"
|
||
|
)
|
||
|
|
||
|
func DeleteFile(filePath string, secureLevel int) bool {
|
||
|
|
||
|
for i := 0; i < secureLevel; i++ {
|
||
|
if !writeRandomFile(filePath) {
|
||
|
return false
|
||
|
}
|
||
|
}
|
||
|
|
||
|
errRemoveFile := os.Remove(filePath)
|
||
|
return errRemoveFile == nil
|
||
|
}
|
||
|
|
||
|
func writeRandomFile(filePath string) bool {
|
||
|
file, errOpen := os.OpenFile(filePath, os.O_RDWR, 0660)
|
||
|
if errOpen != nil {
|
||
|
return false
|
||
|
}
|
||
|
// Fermeture du fichier anticipée (ici afin de le fermer même si copy commet une erreur)
|
||
|
defer file.Close()
|
||
|
//Vérifier que la taille du fichier est plus petite ou plus grande que 1024
|
||
|
//Si plus petite, le buffer prend la taille du fichier
|
||
|
//Sinon le buffer a une taille de 1024
|
||
|
var buffer []byte
|
||
|
fileStat, errStat := file.Stat()
|
||
|
if errStat != nil {
|
||
|
return false
|
||
|
}
|
||
|
if fileStat.Size() < 1024 {
|
||
|
buffer = make([]byte, fileStat.Size())
|
||
|
} else {
|
||
|
buffer = make([]byte, 1024)
|
||
|
}
|
||
|
currentSize := int64(0)
|
||
|
|
||
|
// Copy file
|
||
|
return copyRandomFile(currentSize, fileStat.Size(), buffer, file)
|
||
|
}
|
||
|
|
||
|
func copyRandomFile(currentSize int64, fileSize int64, buffer []byte, file *os.File) bool {
|
||
|
// Retrieving file
|
||
|
src := crypto.NewCryptoSource()
|
||
|
for currentSize < fileSize {
|
||
|
random := rand.New(src)
|
||
|
buffer = []byte(strconv.FormatInt(int64(random.Uint64()), 10))
|
||
|
length, err := file.WriteAt(buffer, currentSize)
|
||
|
if err != nil {
|
||
|
return false
|
||
|
}
|
||
|
currentSize += int64(length)
|
||
|
check := fileSize - currentSize
|
||
|
if 1024 > check && check > 0 {
|
||
|
buffer = make([]byte, check)
|
||
|
}
|
||
|
}
|
||
|
return true
|
||
|
}
|