Пример #1
0
        public static void shareFile(string filepath, string targetUser)
        {
            BinaryFormatter formatter         = new BinaryFormatter();
            FileStream      streamOfLocalFile = new FileStream(filepath, FileMode.Open, FileAccess.Read);

            EncryptedFile file = (EncryptedFile)formatter.Deserialize(streamOfLocalFile);

            streamOfLocalFile.Close();
            byte[] decryptedData = Decrypt.decryptLocalFile(file);

            //find users certificate
            X509Certificate2 targetCertificate = LogIn.getUsersCertificateByName(targetUser);
            EncryptedFile    outputFile        = Encrypt.encryptDataForSharedFile(decryptedData, targetCertificate);

            try
            {
                string     filename   = Path.GetFileName(filepath);
                FileStream fileStream = File.Create(Application.Current.Properties["sharedFolderLocation"].ToString() + "\\" + filename);

                BinaryFormatter binFormat = new BinaryFormatter();
                binFormat.Serialize(fileStream, outputFile);
                fileStream.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("File already exists");
                return;
            }
        }
        public async Task SaveContentAsync(EncryptedFile fileInfo, IFormFile formFile)
        {
            if (fileInfo == null)
            {
                return;
            }

            var blobParts     = fileInfo.BlobName.Split(ContainerNameSeparator);
            var containerName = blobParts[0];
            var blobName      = blobParts[1];

            var contain = _cloudBlobClient.GetContainerReference(containerName);

            contain.CreateIfNotExists();

            var rsa = await _cloudResolver.ResolveKeyAsync(
                _fileStorageKey,
                CancellationToken.None);

            var policy = new BlobEncryptionPolicy(rsa, null);

            var options = new BlobRequestOptions {
                EncryptionPolicy = policy
            };

            var blob = contain.GetBlockBlobReference(blobName);

            using (var stream = formFile.OpenReadStream())
            {
                // Options object is containing all information about the
                await blob.UploadFromStreamAsync(stream, stream.Length, null, options, null);
            }
        }
        public void DecryptData(EncryptedFile encryptedFile, RSAEncryption rsaEncryption, DigitalSignature signature)
        {
            var decryptedSessionKey = rsaEncryption.DecryptData(encryptedFile.EncryptedSessionKey);

            using (var hmac = new HMACSHA256(decryptedSessionKey))
            {
                var hmacToCheck = hmac.ComputeHash(encryptedFile.EncryptedData);

                if (!Compare(encryptedFile.Hmac, hmacToCheck))
                {
                    throw new CryptographicException("HMAC for decryption does not match encrypted packet.");
                }

                if (!signature.VerifySignature(encryptedFile.Hmac, encryptedFile.Signature))
                {
                    throw new CryptographicException("Digital Signature can not be verified.");
                }
            }

            byte[] fileInBytes = _aes.Decrypt(encryptedFile.EncryptedData, decryptedSessionKey, encryptedFile.Iv);


            if (!Directory.Exists($"storage/{encryptedFile.ReceiverEmail}/files"))
            {
                Directory.CreateDirectory($"storage/{encryptedFile.ReceiverEmail}/files");
            }

            using (var fs = new FileStream($"storage/{encryptedFile.ReceiverEmail}/files/{encryptedFile.FileName}", FileMode.Create, FileAccess.Write))
            {
                fs.Write(fileInBytes, 0, fileInBytes.Length);
            }
        }
        public void TestDeserialize()
        {
            const string filePath = "BinarySerializerTest.sfs";

            var objToSerialize = new EncryptedFile
            {
                Data          = new byte[] { 1, 2 },
                FileExtension = new byte[] { 3, 4 },
                Hmac          = new byte[] { 5, 6 },
                Iv            = new byte[] { 7, 8 },
                SessionKey    = new byte[] { 9, 10 }
            };

            BinarySerializer.Serialize(filePath, objToSerialize);
            Assert.IsTrue(File.Exists(filePath));

            var deserializedObj = BinarySerializer.Deserialize <EncryptedFile>(filePath);

            Assert.IsTrue(deserializedObj.Data[0] == objToSerialize.Data[0]);
            Assert.IsTrue(deserializedObj.Data[1] == objToSerialize.Data[1]);
            Assert.IsTrue(deserializedObj.FileExtension[0] == objToSerialize.FileExtension[0]);
            Assert.IsTrue(deserializedObj.FileExtension[1] == objToSerialize.FileExtension[1]);
            Assert.IsTrue(deserializedObj.Hmac[0] == objToSerialize.Hmac[0]);
            Assert.IsTrue(deserializedObj.Hmac[1] == objToSerialize.Hmac[1]);
            Assert.IsTrue(deserializedObj.Iv[0] == objToSerialize.Iv[0]);
            Assert.IsTrue(deserializedObj.Iv[1] == objToSerialize.Iv[1]);
            Assert.IsTrue(deserializedObj.SessionKey[0] == objToSerialize.SessionKey[0]);
            Assert.IsTrue(deserializedObj.SessionKey[1] == objToSerialize.SessionKey[1]);

            //clean up file system
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }
        public void EncryptFile(IFormFile fileform, EncryptedMessage encryptedMessage, RSAEncryption rsaEncryption, DigitalSignature signature)
        {
            var sessionKey = _aes.GenerateRandomNumber(32);

            var encryptedPacket = new EncryptedFile
            {
                Iv                 = _aes.GenerateRandomNumber(16),
                SenderEmail        = encryptedMessage.SenderEmail,
                ReceiverEmail      = encryptedMessage.ReceiverEmail,
                EncryptedMessageId = encryptedMessage.EncryptedMessageId,
                FileName           = fileform.FileName,
            };

            byte[] fileInBytes;

            using (var stream = new MemoryStream())
            {
                fileform.CopyToAsync(stream);
                fileInBytes = stream.ToArray();
            }

            encryptedPacket.EncryptedData       = _aes.Encrypt(fileInBytes, sessionKey, encryptedPacket.Iv);
            encryptedPacket.EncryptedSessionKey = rsaEncryption.EncryptData(sessionKey);

            using (var hmac = new HMACSHA256(sessionKey))
            {
                encryptedPacket.Hmac = hmac.ComputeHash(encryptedPacket.EncryptedData);
            }

            encryptedPacket.Signature = signature.SignData(encryptedPacket.Hmac);

            _dbContext.EncryptedFiles.Add(encryptedPacket);
            _dbContext.SaveChanges();
        }
Пример #6
0
        /// <summary>
        /// Opens users encrypted file. File is first decrypted and stored as a temporary file in a <em>temporary folder</em> after which is opened in a default app for that file set on the computer.
        /// </summary>
        /// <param name="pathOnEfs">The name of the encrypted file including files path and encrypted name with .at extension.</param>
        /// <param name="ownerPublicKey">Public RSA key from the file owner used to check files signature.</param>
        public void OpenFile(string pathOnEfs, RSAParameters ownerPublicKey)
        {
            var encryptedFile = new EncryptedFile(pathOnEfs.Substring(pathOnEfs.LastIndexOf('\\') + 1).Split('.')[0]);
            var originalFile  = encryptedFile.Decrypt(File.ReadAllBytes(pathOnEfs), currentUser.Id, currentUser.PrivateKey, ownerPublicKey);

            var tempFilePath = Path.GetTempPath() + "Enigma-" + Guid.NewGuid().ToString() + "." + originalFile.FileExtension;

            if (CanItBeStored(originalFile.FileContent.Length, tempFilePath.Substring(0, 2)))
            {
                // create a temporary file
                CreateFile(originalFile.FileContent, tempFilePath);

                // override existing encrypted file
                var encryptedFileUpdated = encryptedFile.Flush();
                if (CanItBeStored(encryptedFileUpdated.Length, pathOnEfs.Substring(0, 2)))
                {
                    CreateFile(encryptedFileUpdated, pathOnEfs);
                }

                var startInfo = new ProcessStartInfo(tempFilePath);
                Process.Start(startInfo);
            }
            else
            {
                throw new Exception("Insufficient storage available. File can't be read.");
            }
        }
Пример #7
0
        internal void ValidatePreparedOriginAndFileName(EncryptedFile data)
        {
            var preparedName = PrepareContainerName(data.Origin);

            if (string.IsNullOrEmpty(preparedName) || preparedName.Length < 3)
            {
                throw new ArgumentException("Origin, when prepared, must not be less then 3 characters in length",
                                            nameof(data.Origin));
            }

            if (preparedName.Length > 63)
            {
                throw new ArgumentException("Origin, when prepared, must not be more then 63 characters in length",
                                            nameof(data.Origin));
            }

            //We can validate with and empty guid, cause we just need GUID chars
            preparedName = PrepareBlobName(data.FileName, Guid.Empty);

            if (preparedName.Length > 1024)
            {
                throw new ArgumentException("File name, when prepared, must not be more then 1024 characters in length",
                                            nameof(data.FileName));
            }
        }
        private static QueueItemStatus?GetItemStatus(
            StorageFile localFile,
            StorageFile remoteFile,
            EncryptedFile encryptedFile)
        {
            if (localFile == null)
            {
                // file does not existis on local storage, need to download
                return(QueueItemStatus.WaitingForDownload);
            }

            if (remoteFile == null)
            {
                // file does not existis on remote storage, need to upload
                return(QueueItemStatus.WaitingForUpload);
            }

            if (localFile.Modified > encryptedFile.Modified)
            {
                // local file is newer than in db
                return(QueueItemStatus.WaitingForUpload);
            }

            if (localFile.Modified < encryptedFile.Modified)
            {
                // remote file is newer than in db
                return(QueueItemStatus.WaitingForDownload);
            }

            // todo check hashes
            return(null);
        }
Пример #9
0
        public static void downloadFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                Stream         myStream;
                if (saveFileDialog.ShowDialog() == true)
                {
                    if ((myStream = saveFileDialog.OpenFile()) != null)
                    {
                        BinaryFormatter formatter         = new BinaryFormatter();
                        FileStream      streamOfLocalFile = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        //decrypt file and put its stream

                        EncryptedFile file = (EncryptedFile)formatter.Deserialize(streamOfLocalFile);

                        //decrypt content
                        byte[] outputBytes = Decrypt.decryptLocalFile(file);

                        myStream.Write(outputBytes);
                        myStream.Flush();
                        myStream.Close();
                    }
                }
            }
        }
Пример #10
0
        public static void editFile(string existingFilePath)
        {
            BinaryFormatter formatter         = new BinaryFormatter();
            FileStream      streamOfLocalFile = new FileStream(existingFilePath, FileMode.Open, FileAccess.Read);

            EncryptedFile file = (EncryptedFile)formatter.Deserialize(streamOfLocalFile);

            streamOfLocalFile.Close();
            byte[] decryptedData = Decrypt.decryptLocalFile(file);

            NewFileWindow newFileWindow = new NewFileWindow();

            newFileWindow.Title.Text      = Path.GetFileName(existingFilePath);
            newFileWindow.Title.IsEnabled = false;

            newFileWindow.Content.Text = Encoding.UTF8.GetString(decryptedData);
            newFileWindow.ShowDialog();

            byte[] newFileData = Encoding.UTF8.GetBytes(newFileWindow.Content.Text);

            newFileWindow.Close();
            var outFile = Encrypt.encryptDataForLocalFile(newFileData);

            File.Delete(existingFilePath);

            FileStream fileStream = File.Create(existingFilePath);

            BinaryFormatter binFormat = new BinaryFormatter();

            binFormat.Serialize(fileStream, outFile);
            fileStream.Close();

            return;
        }
Пример #11
0
        public async Task AddPostAsync(AddRequestDto addRequest)
        {
            var filePath = string.Empty;
            var fileSnapshotImagePath = string.Empty;

            // todo dodaj && addRequest.UserNickname != null jak bedzie logowanie
            if (addRequest.EncodedFile != null && addRequest.FileName != null)
            {
                var encryptedFile = new EncryptedFile(addRequest);
                await encryptedFile.DecryptAndSaveFile();

                encryptedFile.GenerateAndSaveSnapshot();
                filePath = encryptedFile.FilePath;
                fileSnapshotImagePath = encryptedFile.SnapshotImagePath;
            }

            var post = new Post(
                addRequest.Title.ToLower().RemoveDiacritics(),
                addRequest.Description.ToLower().RemoveDiacritics(),
                addRequest.School,
                addRequest.MaterialType,
                fileSnapshotImagePath,
                filePath,
                addRequest.UserNickname);

            await this.postRepository.AddAsync(post);
        }
Пример #12
0
        /// <summary>
        /// Updates selected encrypted file with a specified unencrypted file.
        /// </summary>
        /// <param name="pathOnEfs">The name of the file to update.</param>
        /// <param name="updateFile">Updated, unencrypted file.</param>
        public void Update(string pathOnEfs, OriginalFile updateFile)
        {
            CertificateCheck("You cannot update files.");

            if (updateFile.FileSize > 2_000_000_000)
            {
                throw new Exception("File can't be larger than 2 GB.");
            }

            if (!CanItBeStored(updateFile.FileSize))
            {
                throw new Exception("Insufficient storage available. File can't be uploaded.");
            }

            var encryptedFile           = new EncryptedFile(pathOnEfs.Substring(pathOnEfs.LastIndexOf('\\') + 1).Split('.')[0]);
            var updatedEncryptedFileRaw = encryptedFile.Update(updateFile, File.ReadAllBytes(pathOnEfs), currentUser.Id, currentUser.PrivateKey);

            // Name update is always necessary because file's IV has been changed and possibly a new file has a different name.
            encryptedFile.NameEncryption(updateFile.GetOriginalFileFullName(),
                                         new AesAlgorithm(((SecurityDescriptor)encryptedFile.Headers[1]).GetKey((int)currentUser.Id, currentUser.PrivateKey),
                                                          ((SecurityDescriptor)encryptedFile.Headers[1]).IV, "OFB"));

            // delete the old encrypted file
            DeleteFile(pathOnEfs);

            if (CanItBeStored(updatedEncryptedFileRaw.Length))
            {
                CreateFile(updatedEncryptedFileRaw, pathOnEfs.Substring(0, pathOnEfs.LastIndexOf('\\')) + "\\" + encryptedFile.GetEncryptedFileFullName());
            }
            else
            {
                throw new Exception("Insufficient storage available. File can't be updated.");
            }
        }
Пример #13
0
        /// <summary>
        /// Uploads selected file. File is first encrypted after which is stored on the specified path on encrypted file system.
        /// </summary>
        /// <param name="originalFile">Original, unencrypted file.</param>
        /// <param name="pathOnEfs">Path on the encrypted file system where the file will be stored.</param>
        /// <param name="algorithmNameSignature">Name of the algorithm used for file encryption.</param>
        /// <param name="hashAlgorithmName">Name of the hashing algorithm used to create a file signature.</param>
        /// <returns>Encrypted name of the file.</returns>
        public string Upload(OriginalFile originalFile, string pathOnEfs, string algorithmNameSignature, string hashAlgorithmName)
        {
            CertificateCheck("You cannot import any new files.");

            string encryptedName;

            if (originalFile.FileSize > 1_900_000_000)
            {
                throw new Exception("File can't be larger than 2 GB.");
            }

            if (CanItBeStored(originalFile.FileSize))
            {
                var encryptedFile    = new EncryptedFile(originalFile.GetOriginalFileFullName(), (uint)currentUser.Id, algorithmNameSignature, hashAlgorithmName, currentUser.PublicKey, currentUser.PrivateKey);
                var encryptedFileRaw = encryptedFile.Encrypt(originalFile, currentUser.Id, currentUser.PrivateKey);
                encryptedName = encryptedFile.EncryptedName;

                // var userPrivateKey = currentUser.GetPrivateKey(privateKeyPath, password);

                if (CanItBeStored(encryptedFileRaw.Length))
                {
                    CreateFile(encryptedFileRaw, pathOnEfs + "\\" + encryptedFile.GetEncryptedFileFullName());
                }
                else
                {
                    throw new Exception("Insufficient storage available. File can't be uploaded.");
                }
            }
            else
            {
                throw new Exception("Insufficient storage available. File can't be uploaded.");
            }

            return(encryptedName);
        }
Пример #14
0
        public void TestTwofishFileDecryption()
        {
            byte[] data = new byte[10000];
            new Random().NextBytes(data); // fill random data

            using (var senderRsa = new RSACryptoServiceProvider())
            {
                var senderPrivateKey = senderRsa.ExportParameters(true);

                using (var receiverRsa = new RSACryptoServiceProvider())
                {
                    var receiverPrivateKey = receiverRsa.ExportParameters(true);
                    var receiverPublicKey  = receiverRsa.ExportParameters(false);

                    CryptCombo   combo             = new CryptCombo(MD5.Create(), new TwofishMachine());
                    MemoryStream cryptedFileStream = new MemoryStream();

                    OriginalFile originFile = new OriginalFile(new MemoryStream(data), ".java");
                    FileCryptor  cryptor    = new FileCryptor(senderPrivateKey, receiverPublicKey);
                    cryptor.Encrypt(originFile, cryptedFileStream, combo);

                    MemoryStream  decryptedStream = new MemoryStream();
                    EncryptedFile newCryptedFile  = EncryptedFileChecker.Parse(cryptedFileStream);
                    FileDecryptor decryptor       = new FileDecryptor(receiverPrivateKey);
                    decryptor.Decrypt(newCryptedFile, decryptedStream);

                    Assert.IsTrue(decryptedStream.ToArray().SequenceEqual(data));
                }
            }
        }
Пример #15
0
        public static void openFile(string filePath)
        {
            try
            {
                BinaryFormatter formatter         = new BinaryFormatter();
                FileStream      streamOfLocalFile = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                //decrypt file and put its stream

                EncryptedFile file = (EncryptedFile)formatter.Deserialize(streamOfLocalFile);
                byte[]        decryptedFileContent = Decrypt.decryptLocalFile(file);

                string newTempFileName = System.IO.Path.GetTempFileName() + Guid.NewGuid().ToString() + Path.GetExtension(filePath);

                File.WriteAllBytes(newTempFileName, decryptedFileContent);

                Process fileopener = new Process();
                fileopener.StartInfo.FileName  = "explorer";
                fileopener.StartInfo.Arguments = "\"" + newTempFileName + "\"";
                fileopener.Start();
                streamOfLocalFile.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("File corrupted");
            }
        }
        public async Task <Stream> GetContentAsync(EncryptedFile fileInfo)
        {
            if (fileInfo.BlobName == null)
            {
                return(null);
            }

            var blobParts     = fileInfo.BlobName.Split(ContainerNameSeparator);
            var containerName = blobParts[0];
            var blobName      = blobParts[1];

            var contain = _cloudBlobClient.GetContainerReference(containerName);

            contain.CreateIfNotExists();

            var policy  = new BlobEncryptionPolicy(null, _cloudResolver);
            var options = new BlobRequestOptions {
                EncryptionPolicy = policy
            };

            var blob = contain.GetBlockBlobReference(blobName);

            // Options object is containing all information about the
            return(await blob.OpenReadAsync(null, options, null));
        }
Пример #17
0
 public override void Read(BinaryReader reader)
 {
     this.random_id = reader.ReadInt64();
     this.chat_id   = reader.ReadInt32();
     this.date      = reader.ReadInt32();
     this.bytes     = Serializers.Bytes.read(reader);
     this.file      = Tl.Parse <EncryptedFile>(reader);
 }
Пример #18
0
        public List <int> GetSharedUsersId(int loggedInUserId, string pathOnEfs)
        {
            var encryptedFile = new EncryptedFile(pathOnEfs.Substring(pathOnEfs.LastIndexOf('\\') + 1).Split('.')[0]);

            encryptedFile.ParseEncryptedFile(File.ReadAllBytes(pathOnEfs));

            return(encryptedFile.GetSharedUsersId(loggedInUserId));
        }
Пример #19
0
 public EncryptedMessageConstructor(long random_id, int chat_id, int date, byte[] bytes, EncryptedFile file)
 {
     this.random_id = random_id;
     this.chat_id   = chat_id;
     this.date      = date;
     this.bytes     = bytes;
     this.file      = file;
 }
 public MessageModelEncryptedDelivered(int fromId, int toId, int date, bool output, bool unread, DecryptedMessage message, EncryptedFile file) {
     this.fromId = fromId;
     this.toId = toId;
     this.date = date;
     this.output = output;
     this.unread = unread;
     this.message = message;
     this.file = file;
 }
 private void Read(BinaryReader reader) {
     fromId = reader.ReadInt32();
     toId = reader.ReadInt32();
     date = reader.ReadInt32();
     output = reader.ReadBoolean();
     unread = reader.ReadBoolean();
     message = TL.Parse<DecryptedMessage>(reader);
     file = TL.Parse<EncryptedFile>(reader);
 }
Пример #22
0
        private async void AddFile_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker Picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.ComputerFolder,
                ViewMode = PickerViewMode.Thumbnail
            };

            Picker.FileTypeFilter.Add("*");

            IReadOnlyList <StorageFile> FileList = await Picker.PickMultipleFilesAsync();

            ActivateLoading(true, true);

            Cancellation = new CancellationTokenSource();

            try
            {
                foreach (StorageFile File in FileList)
                {
                    if ((await File.EncryptAsync(SecureFolder, FileEncryptionAesKey, AESKeySize, Cancellation.Token).ConfigureAwait(true)) is StorageFile EncryptedFile)
                    {
                        var Size = await EncryptedFile.GetSizeRawDataAsync().ConfigureAwait(true);

                        var Thumbnail    = new BitmapImage(new Uri("ms-appx:///Assets/LockFile.png"));
                        var ModifiedTime = await EncryptedFile.GetModifiedTimeAsync().ConfigureAwait(true);

                        SecureCollection.Add(new FileSystemStorageItemBase(EncryptedFile, Size, Thumbnail, ModifiedTime));
                    }
                    else
                    {
                        QueueContentDialog Dialog = new QueueContentDialog
                        {
                            Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                            Content         = Globalization.GetString("QueueDialog_EncryptError_Content"),
                            CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                        };
                        _ = await Dialog.ShowAsync().ConfigureAwait(true);

                        break;
                    }
                }
            }
            catch (TaskCanceledException)
            {
            }
            finally
            {
                Cancellation.Dispose();
                Cancellation = null;
            }

            await Task.Delay(1500).ConfigureAwait(true);

            ActivateLoading(false);
        }
Пример #23
0
 public MessageModelEncryptedDelivered(int fromId, int toId, int date, bool output, bool unread, DecryptedMessage message, EncryptedFile file)
 {
     this.fromId  = fromId;
     this.toId    = toId;
     this.date    = date;
     this.output  = output;
     this.unread  = unread;
     this.message = message;
     this.file    = file;
 }
Пример #24
0
 private void Read(BinaryReader reader)
 {
     fromId  = reader.ReadInt32();
     toId    = reader.ReadInt32();
     date    = reader.ReadInt32();
     output  = reader.ReadBoolean();
     unread  = reader.ReadBoolean();
     message = TL.Parse <DecryptedMessage>(reader);
     file    = TL.Parse <EncryptedFile>(reader);
 }
        public async Task <Guid> CreateFileInfoAsync(EncryptedFile data)
        {
            using (var context = _contextFactory.CreateDataContext())
            {
                context.EncryptedFiles.Add(data);

                await context.SaveChangesAsync();

                return(data.FileId);
            }
        }
Пример #26
0
        private static void EncryptDataForUser()
        {
            Terminal.Message("You may now encrypt some data.");
            var data = Terminal.Prompt("What data would you like to encrypt?");

            SecurityLayer.EncryptData(data);
            Terminal.Message("Printing your encrypted data");
            Terminal.Message(EncryptedFile.Read(UserDataFilename));

            SecurityLayer.DecryptData();
        }
Пример #27
0
        public static bool CheckPassword(string password)
        {
            if (!File.Exists(Program.ConfigurationFilename))
            {
                SetPassword(password);
                return(true);
            }

            var currentPassword = EncryptedFile.Decrypt(Program.ConfigurationFilename, ApplicationKey).AsHash();

            return(currentPassword.Compare(password));
        }
        public async Task UploadFilePathToDatabase(string fileName, string path, string fullPath)
        {
            var encryptedFile = new EncryptedFile
            {
                FileName = fileName,
                Path     = path,
                FullPath = fullPath
            };
            await _context.AddAsync(encryptedFile);

            await _context.SaveChangesAsync();
        }
Пример #29
0
        /// <summary>
        /// Attempts to copy back any changes from the temporary file, and clean up
        /// </summary>
        /// <param name="sender">Unused</param>
        /// <param name="e">Unused</param>
        public void CleanUp(object sender, EventArgs e)
        {
            this.Watcher.Dispose();
            this.Watcher = null;

            while (this.IsLocked())
            {
                System.Threading.Thread.Sleep(100);
            }

            this.UpdateOriginal();
            EncryptedFile.Delete(this.TempFilePath, new Random());
        }
Пример #30
0
        public async Task OneRemoteFileSync()
        {
            var encryptedFile = new EncryptedFile
            {
                Name          = "someFile.txt",
                EncryptedName = "encryptFileName",
                Created       = DateTime.UtcNow,
                Folder        = this.rootFolder
            };

            this.dbContext.Files.Add(encryptedFile);

            this.localStorageMock.Setup(x => x.GetFolderChilds(RootFolder))
            .Returns(Task.FromResult(new List <StorageItem>()));

            await this.dbContext.SaveChangesAsync();

            var remoteStorageFile = new StorageFile
            {
                Name     = encryptedFile.EncryptedName,
                Modified = DateTime.UtcNow,
                FullPath = $"{this.rootFolder.EncryptedName}/{encryptedFile.EncryptedName}",
                Size     = 10
            };

            this.remoteStorageMock.Setup(x => x.GetFolderChilds(this.rootFolder.EncryptedName))
            .Returns(Task.FromResult(new List <StorageItem> {
                remoteStorageFile
            }));

            var reader = new SyncFoldersReader(
                this.dbContext,
                this.remoteStorageMock.Object,
                DeviceName,
                this.storageFactoryMock.Object);

            var queue = new SyncConcurrentQueue();

            await reader.Sync(queue, CancellationToken.None);

            Assert.IsFalse(queue.IsEmpty);
            Assert.AreEqual(1, queue.Count);
            var queueItem = queue.TryDequeue();

            Assert.IsNotNull(queueItem);
            Assert.IsNotNull(queueItem.EncryptedFile);
            Assert.AreEqual(encryptedFile.Id, queueItem.EncryptedFile.Id);
            Assert.AreEqual($@"{RootFolder}\{encryptedFile.Name}", queueItem.LocalPath);
            Assert.AreEqual($"{this.rootFolder.EncryptedName}/{encryptedFile.EncryptedName}", queueItem.RemotePath);
            Assert.AreEqual(QueueItemStatus.WaitingForDownload, queueItem.Status);
        }
Пример #31
0
        public static void createNewTextFile(string content, string fileName, string targetDirectoryPath)
        {
            EncryptedFile outFile = Encrypt.encryptDataForLocalFile(Encoding.UTF8.GetBytes(content));

            //encrypt content

            if (!File.Exists(Path.Combine(targetDirectoryPath, fileName)))
            {
                FileStream file = File.Create((Path.Combine(targetDirectoryPath, fileName)));

                BinaryFormatter binFormat = new BinaryFormatter();
                binFormat.Serialize(file, outFile);
                file.Close();
            }
        }
Пример #32
0
        public static void uploadFile(string filePath, string targetDirectoryPath)
        {
            byte[]        content = File.ReadAllBytes(filePath);
            EncryptedFile outFile = Encrypt.encryptDataForLocalFile(content);


            if (!File.Exists(Path.Combine(targetDirectoryPath, Path.GetFileName(filePath))))
            {
                FileStream file = File.Create((Path.Combine(targetDirectoryPath, Path.GetFileName(filePath))));

                BinaryFormatter binFormat = new BinaryFormatter();
                binFormat.Serialize(file, outFile);
                file.Close();
            }
        }