public void TestDecryptOfTooNewFileVersion()
        {
            DateTime creationTimeUtc   = new DateTime(2012, 1, 1, 1, 2, 3, DateTimeKind.Utc);
            DateTime lastAccessTimeUtc = creationTimeUtc + new TimeSpan(1, 0, 0);
            DateTime lastWriteTimeUtc  = creationTimeUtc + new TimeSpan(2, 0, 0);;

            using (Stream inputStream = FakeDataStore.ExpandableMemoryStream(Encoding.UTF8.GetBytes("AxCrypt is Great!")))
            {
                using (Stream outputStream = new MemoryStream())
                {
                    Passphrase passphrase = new Passphrase("a");
                    using (V1AxCryptDocument document = new V1AxCryptDocument(passphrase, 101))
                    {
                        document.FileName          = "MyFile.txt";
                        document.CreationTimeUtc   = creationTimeUtc;
                        document.LastAccessTimeUtc = lastAccessTimeUtc;
                        document.LastWriteTimeUtc  = lastWriteTimeUtc;
                        VersionHeaderBlock versionHeaderBlock = document.DocumentHeaders.VersionHeaderBlock;
                        versionHeaderBlock.FileVersionMajor = (byte)(versionHeaderBlock.FileVersionMajor + 1);
                        document.EncryptTo(inputStream, outputStream, AxCryptOptions.EncryptWithoutCompression);
                    }
                    outputStream.Position = 0;
                    using (V1AxCryptDocument document = new V1AxCryptDocument())
                    {
                        Assert.Throws <FileFormatException>(() => { document.Load(passphrase, new V1Aes128CryptoFactory().CryptoId, outputStream); });
                    }
                }
            }
        }
        public async Task TestWatchedFolders()
        {
            using (FileSystemState state = FileSystemState.Create(Resolve.WorkFolder.FileInfo.FileItemInfo("mystate.txt")))
            {
                Assert.That(state.WatchedFolders, Is.Not.Null, "There should be a Watched Folders instance.");
                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(0), "There should be no Watched folders.");

                FakeDataStore.AddFolder(_rootPath);
                await state.AddWatchedFolderAsync(new WatchedFolder(_rootPath, IdentityPublicTag.Empty));

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(1), "There should be one Watched Folder.");

                await state.AddWatchedFolderAsync(new WatchedFolder(_rootPath, IdentityPublicTag.Empty));

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(1), "There should still only be one Watched Folder.");

                await state.Save();
            }

            using (FileSystemState state = FileSystemState.Create(Resolve.WorkFolder.FileInfo.FileItemInfo("mystate.txt")))
            {
                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(1), "There should be one Watched Folder.");

                Assert.That(state.WatchedFolders.First().Matches(_rootPath), "The Watched Folder should be equal to this.");

                await state.RemoveAndDecryptWatchedFolder(Resolve.WorkFolder.FileInfo.FolderItemInfo("mystate.txt"));

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(1), "There should still be one Watched folders.");

                await state.RemoveAndDecryptWatchedFolder(New <IDataContainer>(_rootPath));

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(0), "There should be no Watched folders now.");
            }
        }
        public async Task TestHandleSessionEventLogOn(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            MockAxCryptFile mock        = new MockAxCryptFile();
            bool            called      = false;
            int             folderCount = -1;

            mock.EncryptFilesUniqueWithBackupAndWipeMockAsync = async(IEnumerable <IDataContainer> folderInfos, EncryptionParameters encryptionParameters, IProgressContext progress) =>
            {
                folderCount = folderInfos.Count();
                called      = true;
                await Task.Delay(0);
            };

            Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>();

            SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock, mockStatusChecker.Object);

            FakeDataStore.AddFolder(@"C:\WatchedFolder");
            LogOnIdentity key = new LogOnIdentity("passphrase");
            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\WatchedFolder", key.Tag));

            await handler.HandleNotificationAsync(new SessionNotification(SessionNotificationType.SignIn, key));

            Assert.That(called, Is.True);
            Assert.That(folderCount, Is.EqualTo(1), "There should be one folder passed for encryption as a result of the event.");
        }
        public async Task TestAddRemoveKnownWatchedFolder()
        {
            using (FileSystemState state = FileSystemState.Create(Resolve.WorkFolder.FileInfo.FileItemInfo("mystate.txt")))
            {
                KnownFolder knownFolder = New <IKnownFoldersDiscovery>().Discover().First();
                FakeDataStore.AddFolder(knownFolder.My.FullName);

                await state.AddWatchedFolderAsync(new WatchedFolder(knownFolder.My.FullName, IdentityPublicTag.Empty));

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(1));
                Assert.That(state.AllWatchedFolders.Count(), Is.EqualTo(1));

                await state.RemoveAndDecryptWatchedFolder(knownFolder.My);

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(0));
                Assert.That(state.AllWatchedFolders.Count(), Is.EqualTo(1));

                await state.AddWatchedFolderAsync(new WatchedFolder(knownFolder.My.FullName, IdentityPublicTag.Empty));

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(1));
                Assert.That(state.AllWatchedFolders.Count(), Is.EqualTo(1));

                await state.RemoveAndDecryptWatchedFolder(knownFolder.My);

                Assert.That(state.WatchedFolders.Count(), Is.EqualTo(0));
                Assert.That(state.AllWatchedFolders.Count(), Is.EqualTo(1));
            }
        }
예제 #5
0
        public async Task TestAlreadyKnownFoldersAndLoggingOn()
        {
            IDataContainer betterCloudInfo = New <IDataContainer>(@"C:\BetterCloud");
            IDataContainer fasterCloudInfo = New <IDataContainer>(@"C:\FasterCloud");
            KnownFolder    folder1         = new KnownFolder(betterCloudInfo, @"My AxCrypt", KnownFolderKind.OneDrive, null);
            KnownFolder    folder2         = new KnownFolder(fasterCloudInfo, @"My AxCrypt", KnownFolderKind.WindowsMyDocuments, null);

            FakeDataStore.AddFolder(folder1.My.FullName);
            FakeDataStore.AddFolder(folder2.My.FullName);

            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(folder1.My.FullName, new LogOnIdentity("PassPhrase").Tag));

            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(folder2.My.FullName, new LogOnIdentity(new Passphrase("aaa")).Tag));

            KnownIdentities       knownIdentities = new KnownIdentities(Resolve.FileSystemState, Resolve.SessionNotify);
            KnownFoldersViewModel vm = new KnownFoldersViewModel(Resolve.FileSystemState, Resolve.SessionNotify, knownIdentities);

            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(0));

            vm.KnownFolders = new KnownFolder[] { folder1, folder2 };
            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(2));
            Assert.That(vm.KnownFolders.First().Enabled, Is.False);
            Assert.That(vm.KnownFolders.Last().Enabled, Is.False);

            await knownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity("aaa"));

            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(2));
            Assert.That(vm.KnownFolders.First().Enabled, Is.False, "This folder should not be enabled, because it's not watched by the signed in identity.");
            Assert.That(vm.KnownFolders.Last().Enabled, Is.True, "This folder should be enabled, since it is watched by the signed in identity.");
        }
        public async Task TestHandleSessionEvents(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            MockAxCryptFile mock      = new MockAxCryptFile();
            int             callTimes = 0;

            mock.EncryptFilesUniqueWithBackupAndWipeMockAsync = async(IEnumerable <IDataContainer> folderInfos, EncryptionParameters encryptionParameters, IProgressContext progress) => { await Task.Delay(0); if (folderInfos.First().FullName == @"C:\My Documents\".NormalizeFilePath())
                                                                                                                                                                                           {
                                                                                                                                                                                               ++callTimes;
                                                                                                                                                                                           }
            };

            Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>();

            SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock, mockStatusChecker.Object);

            FakeDataStore.AddFolder(@"C:\My Documents");
            LogOnIdentity key = new LogOnIdentity("passphrase");
            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\My Documents", key.Tag));

            List <SessionNotification> sessionEvents = new List <SessionNotification>();

            sessionEvents.Add(new SessionNotification(SessionNotificationType.WatchedFolderAdded, new LogOnIdentity("passphrase1"), @"C:\My Documents\"));
            sessionEvents.Add(new SessionNotification(SessionNotificationType.WatchedFolderAdded, new LogOnIdentity("passphrase"), @"C:\My Documents\"));

            foreach (SessionNotification sessionEvent in sessionEvents)
            {
                await handler.HandleNotificationAsync(sessionEvent);
            }
            Assert.That(callTimes, Is.EqualTo(2));
        }
        public async Task TestHandleSessionEventLogOffWithWatchedFolders(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            MockAxCryptFile mock   = new MockAxCryptFile();
            bool            called = false;

            mock.EncryptFilesUniqueWithBackupAndWipeMockAsync = async(IEnumerable <IDataContainer> folderInfos, EncryptionParameters encryptionParameters, IProgressContext progress) => { await Task.Delay(0); called = true; };

            Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>();

            await Resolve.KnownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity("passphrase"));

            SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock, mockStatusChecker.Object);

            FakeDataStore.AddFolder(@"C:\WatchedFolder");
            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\WatchedFolder", Resolve.KnownIdentities.DefaultEncryptionIdentity.Tag));

            called = false;
            await handler.HandleNotificationAsync(new SessionNotification(SessionNotificationType.EncryptPendingFiles));

            await handler.HandleNotificationAsync(new SessionNotification(SessionNotificationType.SignOut, Resolve.KnownIdentities.DefaultEncryptionIdentity));

            Assert.That(called, Is.True, nameof(AxCryptFile.EncryptFoldersUniqueWithBackupAndWipeAsync) + " should be called when a signing out.");
        }
예제 #8
0
        public async Task TestCheckProcessExitedWhenExited()
        {
            DateTime utcNow = New <INow>().Utc;

            FakeDataStore.AddFile(_anAxxPath, utcNow, utcNow, utcNow, new MemoryStream(Resources.helloworld_key_a_txt));
            FakeDataStore.AddFile(_decryptedFile1, utcNow, utcNow, utcNow, Stream.Null);

            await New <KnownIdentities>().SetDefaultEncryptionIdentity(new LogOnIdentity(EmailAddress.Parse("*****@*****.**"), new Passphrase("test")));

            FakeLauncher fakeLauncher = new FakeLauncher();

            fakeLauncher.Launch(_decryptedFile1);
            ActiveFile activeFile = new ActiveFile(New <IDataStore>(_anAxxPath), New <IDataStore>(_decryptedFile1), new LogOnIdentity("passphrase"), ActiveFileStatus.NotDecrypted, new V1Aes128CryptoFactory().CryptoId);

            activeFile = new ActiveFile(activeFile, ActiveFileStatus.AssumedOpenAndDecrypted | ActiveFileStatus.NotShareable);
            Resolve.FileSystemState.Add(activeFile, fakeLauncher);

            ((FakeNow)New <INow>()).TimeFunction = (() => { return(utcNow.AddMinutes(1)); });
            bool changedWasRaised = false;

            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange;
                return(Constant.CompletedTask);
            });
            SetupAssembly.FakeRuntimeEnvironment.Platform = Platform.WindowsDesktop;
            fakeLauncher.HasExited = true;
            await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext());

            activeFile = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(_anAxxPath);
            Assert.That(changedWasRaised, Is.True, "A changed event should be raised because the process has exited.");
            Assert.That(activeFile.Status.HasMask(ActiveFileStatus.NotDecrypted), Is.True, "The ActiveFile plain text should be deleted after the checking of active files because the launcher is no longer active.");
            Assert.That(activeFile.Status.HasMask(ActiveFileStatus.NotShareable), Is.False, "The file should be shareable after checking of active files because the launcher is no longer active.");
        }
예제 #9
0
        public async Task TestPurgeActiveFilesWhenFileIsLocked()
        {
            DateTime utcNow = New <INow>().Utc;

            FakeDataStore.AddFile(_anAxxPath, utcNow, utcNow, utcNow, new MemoryStream(Resources.helloworld_key_a_txt));
            FakeDataStore.AddFile(_decryptedFile1, utcNow, utcNow, utcNow, Stream.Null);

            IDataStore encryptedFileInfo = New <IDataStore>(_anAxxPath);
            IDataStore decryptedFileInfo = New <IDataStore>(_decryptedFile1);
            ActiveFile activeFile        = new ActiveFile(encryptedFileInfo, decryptedFileInfo, new LogOnIdentity("passphrase"), ActiveFileStatus.AssumedOpenAndDecrypted, new V1Aes128CryptoFactory().CryptoId);

            Resolve.FileSystemState.Add(activeFile);

            bool changedWasRaised = false;

            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange;
                return(Constant.CompletedTask);
            });

            using (FileLock fileLock = New <FileLocker>().Acquire(decryptedFileInfo))
            {
                await Task.Run(() => New <ActiveFileAction>().PurgeActiveFiles(new ProgressContext()));
            }

            Assert.That(changedWasRaised, Is.False, "A changed event should not be raised because the decrypted file is locked.");
        }
예제 #10
0
        public async Task TestCheckActiveFilesNotDecryptedAndDoesNotExist()
        {
            DateTime utcNow = New <INow>().Utc;

            FakeDataStore.AddFile(_anAxxPath, utcNow, utcNow, utcNow, new MemoryStream(Resources.helloworld_key_a_txt));
            FakeDataStore.AddFile(_decryptedFile1, utcNow, utcNow, utcNow, Stream.Null);

            ActiveFile activeFile = new ActiveFile(New <IDataStore>(_anAxxPath), New <IDataStore>(_decryptedFile1), new LogOnIdentity("passphrase"), ActiveFileStatus.AssumedOpenAndDecrypted, new V1Aes128CryptoFactory().CryptoId);

            New <IDataStore>(_decryptedFile1).Delete();
            activeFile = new ActiveFile(activeFile, ActiveFileStatus.NotDecrypted);
            Resolve.FileSystemState.Add(activeFile);
            await Resolve.KnownIdentities.AddAsync(activeFile.Identity);

            bool changedWasRaised = false;

            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange;
                return(Constant.CompletedTask);
            });

            ((FakeNow)New <INow>()).TimeFunction = (() => { return(utcNow.AddMinutes(1)); });
            await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext());

            Assert.That(changedWasRaised, Is.False, "The ActiveFile should be not be modified because it's already deleted.");
        }
        public async Task TestNotificationEncryptPendingFilesInLoggedOnFolders(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            FakeDataStore.AddFolder(@"C:\My Documents\");
            Mock <AxCryptFile> mock = new Mock <AxCryptFile>();

            mock.Setup(acf => acf.EncryptFoldersUniqueWithBackupAndWipeAsync(It.IsAny <IEnumerable <IDataContainer> >(), It.IsAny <EncryptionParameters>(), It.IsAny <IProgressContext>()));

            Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>();

            SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock.Object, mockStatusChecker.Object);
            LogOnIdentity defaultKey           = new LogOnIdentity("default");
            await Resolve.KnownIdentities.SetDefaultEncryptionIdentity(defaultKey);

            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\My Documents\", defaultKey.Tag));

            List <SessionNotification> sessionEvents = new List <SessionNotification>();

            sessionEvents.Add(new SessionNotification(SessionNotificationType.EncryptPendingFiles));

            foreach (SessionNotification sessionEvent in sessionEvents)
            {
                await handler.HandleNotificationAsync(sessionEvent);
            }
            mock.Verify(acf => acf.EncryptFoldersUniqueWithBackupAndWipeAsync(It.Is <IEnumerable <IDataContainer> >(infos => infos.Any((i) => i.FullName == @"C:\My Documents\".NormalizeFolderPath())), It.IsAny <EncryptionParameters>(), It.IsAny <IProgressContext>()), Times.Exactly(1));
        }
예제 #12
0
        public async Task TestSettingKnownFoldersAndLoggingOnAndOff()
        {
            KnownIdentities       knownIdentities = new KnownIdentities(Resolve.FileSystemState, Resolve.SessionNotify);
            KnownFoldersViewModel vm = new KnownFoldersViewModel(Resolve.FileSystemState, Resolve.SessionNotify, knownIdentities);

            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(0));

            IDataContainer betterCloudInfo = New <IDataContainer>(@"C:\BetterCloud");
            IDataContainer fasterCloudInfo = New <IDataContainer>(@"C:\FasterCloud");
            KnownFolder    folder1         = new KnownFolder(betterCloudInfo, @"My AxCrypt", KnownFolderKind.WindowsMyDocuments, null);
            KnownFolder    folder2         = new KnownFolder(fasterCloudInfo, @"My AxCrypt", KnownFolderKind.Dropbox, null);

            FakeDataStore.AddFolder(folder1.My.FullName);
            FakeDataStore.AddFolder(folder2.My.FullName);

            vm.KnownFolders = new KnownFolder[] { folder1, folder2 };
            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(2));
            Assert.That(vm.KnownFolders.First().Enabled, Is.False, "We are not signed in so the folder should not be enabled");
            Assert.That(vm.KnownFolders.Last().Enabled, Is.False, "We are not signed in so the folder should not be enabled");

            await knownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity("aaa"));

            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(2));
            Assert.That(vm.KnownFolders.First().Enabled, Is.True, "We are signed in so the folder should be enabled");
            Assert.That(vm.KnownFolders.Last().Enabled, Is.True, "We are signed in so the folder should be enabled");

            await knownIdentities.SetDefaultEncryptionIdentity(LogOnIdentity.Empty);

            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(2));
            Assert.That(vm.KnownFolders.First().Enabled, Is.False, "We are no longer signed in so the folder should not be enabled");
            Assert.That(vm.KnownFolders.Last().Enabled, Is.False, "We are no longer signed in so the folder should not be enabled");
        }
예제 #13
0
        internal static void TestOneFile(string resourceName, string password, string sha256HashValue)
        {
            string source      = Path.Combine(_rootPath, "source.axx");
            string destination = Path.Combine(_rootPath, "destination.file");
            Stream stream      = Assembly.GetAssembly(typeof(TestV2RegressionCompleteFiles)).GetManifestResourceStream("Axantum.AxCrypt.Core.Test.resources." + resourceName);

            FakeDataStore.AddFile(source, FakeDataStore.TestDate1Utc, FakeDataStore.TestDate2Utc, FakeDataStore.TestDate3Utc, stream);

            LogOnIdentity passphrase = new LogOnIdentity(password);

            bool ok = new AxCryptFile().Decrypt(New <IDataStore>(source), New <IDataStore>(destination), passphrase, AxCryptOptions.SetFileTimes, new ProgressContext());

            Assert.That(ok, Is.True, "The Decrypt() method should return true for ok.");

            byte[]        hash;
            HashAlgorithm hashAlgorithm = SHA256.Create();
            Stream        plainStream   = New <IDataStore>(destination).OpenRead();

            using (Stream cryptoStream = new CryptoStream(plainStream, hashAlgorithm, CryptoStreamMode.Read))
            {
                plainStream = null;
                cryptoStream.CopyTo(Stream.Null);
            }
            hash = hashAlgorithm.Hash;

            Assert.That(hash.IsEquivalentTo(sha256HashValue.FromHex()), "Wrong SHA-256.");
        }
예제 #14
0
        public async Task TestFileWasCreatedWhereAKnownFolderWasExpected()
        {
            IDataContainer betterCloudInfo = New <IDataContainer>(@"C:\BetterCloud");
            IDataContainer fasterCloudInfo = New <IDataContainer>(@"C:\FasterCloud");
            KnownFolder    folder1         = new KnownFolder(betterCloudInfo, @"My AxCrypt", KnownFolderKind.GoogleDrive, null);
            KnownFolder    folder2         = new KnownFolder(fasterCloudInfo, @"My AxCrypt", KnownFolderKind.Dropbox, null);

            FakeDataStore.AddFile(@"C:\BetterCloud\My AxCrypt", Stream.Null);
            FakeDataStore.AddFolder(folder2.My.FullName);

            KnownIdentities       knownIdentities = new KnownIdentities(Resolve.FileSystemState, Resolve.SessionNotify);
            KnownFoldersViewModel vm = new KnownFoldersViewModel(Resolve.FileSystemState, Resolve.SessionNotify, knownIdentities);

            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(0));

            vm.KnownFolders = new KnownFolder[] { folder1, folder2 };
            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(2));
            Assert.That(vm.KnownFolders.First().Enabled, Is.False);
            Assert.That(vm.KnownFolders.Last().Enabled, Is.False);

            await knownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity("aaa"));

            Assert.That(Resolve.FileSystemState.WatchedFolders.Count(), Is.EqualTo(1));
            Assert.That(vm.KnownFolders.Count(), Is.EqualTo(2));
            Assert.That(vm.KnownFolders.First().Enabled, Is.False);
            Assert.That(vm.KnownFolders.Last().Enabled, Is.True);
        }
예제 #15
0
        public void TestDragAndDropFilesPropertyBindSetsDragAndDropFileTypes()
        {
            using (MainViewModel mvm = New <MainViewModel>())
            {
                string encryptedFilePath = @"C:\Folder\File-txt.axx";
                mvm.DragAndDropFiles = new string[] { encryptedFilePath, };
                Assert.That(mvm.DragAndDropFilesTypes, Is.EqualTo(FileInfoTypes.None));

                string decryptedFilePath = @"C:\Folder\File.txt";
                mvm.DragAndDropFiles = new string[] { decryptedFilePath, };
                Assert.That(mvm.DragAndDropFilesTypes, Is.EqualTo(FileInfoTypes.None));

                FakeDataStore.AddFile(encryptedFilePath, null);
                mvm.DragAndDropFiles = new string[] { encryptedFilePath, decryptedFilePath, };
                Assert.That(mvm.DragAndDropFilesTypes, Is.EqualTo(FileInfoTypes.EncryptedFile));

                FakeDataStore.AddFile(decryptedFilePath, null);
                mvm.DragAndDropFiles = new string[] { encryptedFilePath, decryptedFilePath, };
                Assert.That(mvm.DragAndDropFilesTypes, Is.EqualTo(FileInfoTypes.EncryptableFile | FileInfoTypes.EncryptedFile));

                string folderPath = @"C:\Folder\";
                mvm.DragAndDropFiles = new string[] { encryptedFilePath, decryptedFilePath, folderPath };
                Assert.That(mvm.DragAndDropFilesTypes, Is.EqualTo(FileInfoTypes.EncryptableFile | FileInfoTypes.EncryptedFile));

                FakeDataStore.AddFolder(folderPath);
                mvm.DragAndDropFiles = new string[] { encryptedFilePath, decryptedFilePath, folderPath };
                Assert.That(mvm.DragAndDropFilesTypes, Is.EqualTo(FileInfoTypes.EncryptableFile | FileInfoTypes.EncryptedFile));
            }
        }
        public void TestInvalidArguments()
        {
            using (Stream inputStream = FakeDataStore.ExpandableMemoryStream(Encoding.UTF8.GetBytes("AxCrypt is Great!")))
            {
                using (Stream outputStream = new MemoryStream())
                {
                    using (V1AxCryptDocument document = new V1AxCryptDocument())
                    {
                        Assert.Throws <ArgumentNullException>(() => { document.EncryptTo(inputStream, null, AxCryptOptions.EncryptWithCompression); });
                        Assert.Throws <ArgumentNullException>(() => { document.EncryptTo(null, outputStream, AxCryptOptions.EncryptWithCompression); });
                        Assert.Throws <ArgumentException>(() => { document.EncryptTo(inputStream, new NonSeekableStream(), AxCryptOptions.EncryptWithCompression); });
                        Assert.Throws <ArgumentException>(() => { document.EncryptTo(inputStream, outputStream, AxCryptOptions.EncryptWithCompression | AxCryptOptions.EncryptWithoutCompression); });
                        Assert.Throws <ArgumentException>(() => { document.EncryptTo(inputStream, outputStream, AxCryptOptions.None); });

                        Passphrase        passphrase = new Passphrase("a");
                        V1DocumentHeaders headers    = new V1DocumentHeaders(passphrase, 13);

                        Assert.Throws <ArgumentNullException>(() => { document.CopyEncryptedTo(null, outputStream); });
                        Assert.Throws <ArgumentNullException>(() => { document.CopyEncryptedTo(headers, null); });
                        Assert.Throws <ArgumentException>(() => { document.CopyEncryptedTo(headers, new NonSeekableStream()); });
                        Assert.Throws <InternalErrorException>(() => { document.CopyEncryptedTo(headers, outputStream); });
                    }
                }
            }
        }
예제 #17
0
        public static void Setup()
        {
            SetupAssembly.AssemblySetup();

            FakeDataStore.AddFile(_davidCopperfieldTxtPath, FakeDataStore.TestDate4Utc, FakeDataStore.TestDate5Utc, FakeDataStore.TestDate6Utc, FakeDataStore.ExpandableMemoryStream(Encoding.GetEncoding(1252).GetBytes(Resources.david_copperfield)));
            FakeDataStore.AddFile(_uncompressedAxxPath, FakeDataStore.ExpandableMemoryStream(Resources.uncompressable_zip));
            FakeDataStore.AddFile(_helloWorldAxxPath, FakeDataStore.ExpandableMemoryStream(Resources.helloworld_key_a_txt));
        }
예제 #18
0
 public static void Setup()
 {
     SetupAssembly.AssemblySetup();
     TypeMap.Register.Singleton <ISettingsStore>(() => new SettingsStore(Resolve.WorkFolder.FileInfo.FileItemInfo("UserSettings.txt")));
     TypeMap.Register.Singleton <UserSettingsVersion>(() => new UserSettingsVersion());
     TypeMap.Register.Singleton <UserSettings>(() => new UserSettings(New <ISettingsStore>(), New <IterationCalculator>()));
     FakeDataStore.AddFolder(@"C:\Folder\");
 }
예제 #19
0
        public void Setup()
        {
            SetupAssembly.AssemblySetup();
            SetupAssembly.AssemblySetupCrypto(_cryptoImplementation);

            FakeDataStore.AddFile(_testTextPath, FakeDataStore.TestDate1Utc, FakeDataStore.TestDate2Utc, FakeDataStore.TestDate3Utc, FakeDataStore.ExpandableMemoryStream(Encoding.UTF8.GetBytes("This is a short file")));
            FakeDataStore.AddFile(_davidCopperfieldTxtPath, FakeDataStore.TestDate4Utc, FakeDataStore.TestDate5Utc, FakeDataStore.TestDate6Utc, FakeDataStore.ExpandableMemoryStream(Encoding.GetEncoding(1252).GetBytes(Resources.david_copperfield)));
            FakeDataStore.AddFile(_uncompressedAxxPath, FakeDataStore.ExpandableMemoryStream(Resources.uncompressable_zip));
            FakeDataStore.AddFile(_helloWorldAxxPath, FakeDataStore.ExpandableMemoryStream(Resources.helloworld_key_a_txt));
        }
예제 #20
0
        public static void TestExtensions_FileFilter()
        {
            FakeDataStore.AddFile(@"c:\test.txt", null);
            IDataStore fileInfo = New <IDataStore>(@"c:\test.txt");

            Assert.That(New <FileFilter>().IsEncryptable(fileInfo), Is.True);

            New <FileFilter>().AddUnencryptableExtension("txt");

            Assert.That(New <FileFilter>().IsEncryptable(fileInfo), Is.False);
        }
예제 #21
0
 public static void TestFindMagicGuidFromSimpleFile()
 {
     using (Stream testStream = FakeDataStore.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
     {
         using (V1AxCryptReader axCryptReader = new V1AxCryptReader(new LookAheadStream(testStream)))
         {
             Assert.That(axCryptReader.Read(), Is.True, "We should be able to read the Guid");
             Assert.That(axCryptReader.CurrentItemType, Is.EqualTo(AxCryptItemType.MagicGuid), "We're expecting to have found a MagicGuid");
         }
     }
 }
        public void Setup()
        {
            SetupAssembly.AssemblySetup();
            SetupAssembly.AssemblySetupCrypto(_cryptoImplementation);

            FakeDataStore.AddFile(_davidCopperfieldTxtPath, FakeDataStore.TestDate4Utc, FakeDataStore.TestDate5Utc, FakeDataStore.TestDate6Utc, FakeDataStore.ExpandableMemoryStream(Encoding.GetEncoding(1252).GetBytes(Resources.david_copperfield)));
            FakeDataStore.AddFile(_uncompressedAxxPath, FakeDataStore.ExpandableMemoryStream(Resources.uncompressable_zip));
            FakeDataStore.AddFile(_helloWorldAxxPath, FakeDataStore.ExpandableMemoryStream(Resources.helloworld_key_a_txt));

            TypeMap.Register.Singleton <IUIThread>(() => new FakeUIThread());
        }
예제 #23
0
        public async Task TestWatchedFoldersNotLoggedOn()
        {
            KnownIdentities knownIdentities = new KnownIdentities(Resolve.FileSystemState, Resolve.SessionNotify);

            FakeDataStore.AddFolder(@"C:\WatchedFolder\");
            await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\WatchedFolder\", IdentityPublicTag.Empty));

            IEnumerable <WatchedFolder> watchedFolders = knownIdentities.LoggedOnWatchedFolders;

            Assert.That(watchedFolders.Count(), Is.EqualTo(0), "When not logged on, no watched folders should be known.");
        }
		/// <summary>
		/// Khởi tạo các thực thể trống
		/// </summary>
		/// <returns></returns>
		public static FakeDataStore GetEmpty()
		{
			FakeDataStore datastore = new FakeDataStore();
			datastore.Albums = new FakeDbSet<Album>();
			datastore.Artists = new FakeDbSet<Artist>();
			datastore.Carts = new FakeDbSet<Cart>();
			datastore.Genres = new FakeDbSet<Genre>();
			datastore.OrderDetails = new FakeDbSet<OrderDetail>();
			datastore.Orders = new FakeDbSet<Order>();
			return datastore;
		}
예제 #25
0
        public void AddProductToCartInNegative()
        {
            FakeDataStore dataStore = MusicStoreEntitiesFactory.GetEmpty();

            dataStore.GenerateAndAddGenre(1);
            dataStore.GenerateAndAddArtist(1);
            dataStore.GenerateAndAddAlbum(2, 1, 1, 10M);
            ShoppingCartController controller = ControllerFactory.GetWiredUpController((s) => new ShoppingCartController(s), store: dataStore);
            RedirectToRouteResult  result     = controller.AddToCart(2, -5) as RedirectToRouteResult;

            Assert.IsTrue(result.RouteValues.ContainsValue("InvalidRequest"));
        }
        public void TestValidateWrongButKnownPassphraseWithRealFile()
        {
            _identities.Add(new Passphrase("b"));

            FakeDataStore.AddFile(@"C:\My Folder\MyFile-txt.axx", new MemoryStream(Resources.helloworld_key_a_txt));
            FilePasswordViewModel npvm = new FilePasswordViewModel(@"C:\My Folder\MyFile-txt.axx");

            npvm.PasswordText = "b";

            Assert.That(npvm[nameof(FilePasswordViewModel.PasswordText)], Is.Not.EqualTo(String.Empty));
            Assert.That(npvm.ValidationError, Is.EqualTo((int)ValidationError.WrongPassphrase));
        }
예제 #27
0
        public async Task TestSimpleCreateAsymmetricKeysStore()
        {
            FakeDataStore.AddFolder(@"C:\Temp");
            IDataContainer workFolder  = New <IDataContainer>(@"C:\Temp");
            AccountStorage store       = new AccountStorage(new LocalAccountService(new LogOnIdentity(EmailAddress.Parse(@"*****@*****.**"), new Passphrase("secret")), workFolder));
            UserKeyPair    userKeyPair = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512);

            await store.ImportAsync(userKeyPair);

            Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PrivateKey, Is.Not.Null);
            Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PublicKey, Is.Not.Null);
        }
예제 #28
0
        public async Task TestCheckActiveFilesUpdateButWithTargetInaccessible()
        {
            DateTime utcNow = New <INow>().Utc;

            FakeDataStore.AddFile(_anAxxPath, utcNow, utcNow, utcNow, FakeDataStore.ExpandableMemoryStream(Resources.helloworld_key_a_txt));
            LogOnIdentity passphrase = new LogOnIdentity("a");

            New <AxCryptFile>().Decrypt(New <IDataStore>(_anAxxPath), New <IDataStore>(_decryptedFile1), passphrase, AxCryptOptions.None, new ProgressContext());

            ActiveFile activeFile = new ActiveFile(New <IDataStore>(_anAxxPath), New <IDataStore>(_decryptedFile1), passphrase, ActiveFileStatus.AssumedOpenAndDecrypted, new V1Aes128CryptoFactory().CryptoId);

            Resolve.FileSystemState.Add(activeFile);

            IDataStore decryptedFileInfo = New <IDataStore>(_decryptedFile1);

            decryptedFileInfo.SetFileTimes(utcNow.AddSeconds(30), utcNow.AddSeconds(30), utcNow.AddSeconds(30));

            ((FakeNow)New <INow>()).TimeFunction = (() => { return(utcNow.AddMinutes(1)); });

            await Resolve.KnownIdentities.AddAsync(passphrase);

            bool changedWasRaised = false;

            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange && notification.FullNames.Contains(_anAxxPath);
                return(Constant.CompletedTask);
            });

            EventHandler eventHandler = ((object sender, EventArgs e) =>
            {
                FakeDataStore fileInfo = (FakeDataStore)sender;
                if (fileInfo.FullName == Path.ChangeExtension(_anAxxPath, ".tmp"))
                {
                    throw new IOException("Faked access denied.");
                }
            });

            FakeDataStore.OpeningForWrite += eventHandler;
            try
            {
                Assert.ThrowsAsync <FileOperationException>(async() => await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext()));
            }
            finally
            {
                FakeDataStore.OpeningForWrite -= eventHandler;
            }

            Assert.That(changedWasRaised, Is.False, "The ActiveFile should not be modified because it was not accessible.");
            activeFile = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(_anAxxPath);
            Assert.That(activeFile.Status.HasMask(ActiveFileStatus.NotShareable), Is.False, "The ActiveFile should not be marked as not shareable after the checking of active files.");
        }
예제 #29
0
        public static void TestValidateWrongPassphraseWithRealFile(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            FakeDataStore.AddFile(@"C:\My Folder\MyFile-txt.axx", new MemoryStream(Resources.helloworld_key_a_txt));
            NewPasswordViewModel npvm = new NewPasswordViewModel(String.Empty, @"C:\My Folder\MyFile-txt.axx");

            npvm.PasswordText = "b";
            npvm.Verification = "b";

            Assert.That(npvm[nameof(NewPasswordViewModel.PasswordText)], Is.Not.EqualTo(""));
            Assert.That(npvm.ValidationError, Is.EqualTo((int)ValidationError.WrongPassphrase));
        }
예제 #30
0
        public async Task TestSetFilesArePending()
        {
            await Resolve.KnownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity("passphrase"));

            FakeDataStore.AddFolder(@"C:\MyFolders\Folder1");
            using (MainViewModel mvm = New <MainViewModel>())
            {
                Assert.That(mvm.FilesArePending, Is.False);
                await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\MyFolders\Folder1", Resolve.KnownIdentities.DefaultEncryptionIdentity.Tag));

                FakeDataStore.AddFile(@"C:\MyFolders\Folder1\Encryptable.txt", Stream.Null);
                Assert.That(mvm.FilesArePending, Is.True);
            }
        }