コード例 #1
0
        public static void CheckWatchedFolders(this FileSystemState fileSystemState, ProgressContext progress)
        {
            if (fileSystemState == null)
            {
                throw new ArgumentNullException("fileSystemState");
            }
            AesKey encryptionKey = fileSystemState.KnownKeys.DefaultEncryptionKey;

            if (encryptionKey == null)
            {
                return;
            }
            IEnumerable <IRuntimeFileInfo> files = fileSystemState.DecryptedFilesInWatchedFolders();

            progress.NotifyLevelStart();
            try
            {
                progress.AddTotal(files.Count());
                foreach (IRuntimeFileInfo fileInfo in files)
                {
                    IRuntimeFileInfo destinationFileInfo = fileInfo.CreateEncryptedName();
                    AxCryptFile.EncryptFileWithBackupAndWipe(fileInfo, destinationFileInfo, encryptionKey, progress);
                    progress.AddCount(1);
                }
            }
            finally
            {
                progress.NotifyLevelFinished();
            }
        }
コード例 #2
0
        private static string EncryptPrivateKey(UserKeyPair keys, Passphrase passphrase)
        {
            if (keys.KeyPair.PrivateKey == null)
            {
                return(String.Empty);
            }

            byte[] privateKeyPemBytes = Encoding.UTF8.GetBytes(keys.KeyPair.PrivateKey.ToString());

            if (passphrase == Passphrase.Empty)
            {
                byte[] encryptedPrivateKeyBytes = New <IProtectedData>().Protect(privateKeyPemBytes, null);
                return(Convert.ToBase64String(encryptedPrivateKeyBytes));
            }

            StringBuilder encryptedPrivateKey = new StringBuilder();

            using (StringWriter writer = new StringWriter(encryptedPrivateKey))
            {
                using (Stream stream = new MemoryStream(privateKeyPemBytes))
                {
                    EncryptionParameters encryptionParameters = new EncryptionParameters(Resolve.CryptoFactory.Preferred.CryptoId, passphrase);
                    EncryptedProperties  properties           = new EncryptedProperties("private-key.pem");
                    using (MemoryStream encryptedStream = new MemoryStream())
                    {
                        AxCryptFile.Encrypt(stream, encryptedStream, properties, encryptionParameters, AxCryptOptions.EncryptWithCompression, new ProgressContext());
                        writer.Write(Convert.ToBase64String(encryptedStream.ToArray()));
                    }
                }
            }
            return(encryptedPrivateKey.ToString());
        }
コード例 #3
0
        private bool EncryptFileOperation()
        {
            AxCryptFile.EncryptFileWithBackupAndWipe(_eventArgs.OpenFileFullName, _eventArgs.SaveFileFullName, _eventArgs.Key, _progress);

            _eventArgs.Status = FileOperationStatus.Success;
            return(true);
        }
コード例 #4
0
        public static void TestSmallEncryptDecrypt()
        {
            IRuntimeFileInfo sourceFileInfo      = OS.Current.FileInfo(_testTextPath);
            IRuntimeFileInfo destinationFileInfo = sourceFileInfo.CreateEncryptedName();

            Assert.That(destinationFileInfo.Name, Is.EqualTo("test-txt.axx"), "Wrong encrypted file name based on the plain text file name.");
            AxCryptFile.Encrypt(sourceFileInfo, destinationFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, new ProgressContext());
            using (AxCryptDocument document = AxCryptFile.Document(destinationFileInfo, new Passphrase("axcrypt").DerivedPassphrase, new ProgressContext()))
            {
                Assert.That(document.PassphraseIsValid, Is.True, "The passphrase should be ok.");
                Assert.That(document.DocumentHeaders.FileName, Is.EqualTo("test.txt"), "Unexpected file name in headers.");
                Assert.That(document.DocumentHeaders.CreationTimeUtc, Is.EqualTo(FakeRuntimeFileInfo.TestDate1Utc));
                Assert.That(document.DocumentHeaders.LastAccessTimeUtc, Is.EqualTo(FakeRuntimeFileInfo.TestDate2Utc));
                Assert.That(document.DocumentHeaders.LastWriteTimeUtc, Is.EqualTo(FakeRuntimeFileInfo.TestDate3Utc));
                IRuntimeFileInfo decryptedFileInfo = OS.Current.FileInfo(Path.Combine(_rootPath, "decrypted test.txt"));
                AxCryptFile.Decrypt(document, decryptedFileInfo, AxCryptOptions.SetFileTimes, new ProgressContext());
                using (Stream decryptedStream = decryptedFileInfo.OpenRead())
                {
                    string decrypted = new StreamReader(decryptedStream, Encoding.UTF8).ReadToEnd();
                    Assert.That(decrypted, Is.EqualTo("This is a short file"));
                }
                Assert.That(decryptedFileInfo.CreationTimeUtc, Is.EqualTo(document.DocumentHeaders.CreationTimeUtc), "We're expecting file times to be set as the original from the headers.");
                Assert.That(decryptedFileInfo.LastAccessTimeUtc, Is.EqualTo(document.DocumentHeaders.LastAccessTimeUtc), "We're expecting file times to be set as the original from the headers.");
                Assert.That(decryptedFileInfo.LastWriteTimeUtc, Is.EqualTo(document.DocumentHeaders.LastWriteTimeUtc), "We're expecting file times to be set as the original from the headers.");
            }
        }
コード例 #5
0
        public static void TestLargeEncryptDecrypt()
        {
            string sourceFullName = _davidCopperfieldTxtPath;

            IRuntimeFileInfo sourceRuntimeFileInfo      = OS.Current.FileInfo(sourceFullName);
            IRuntimeFileInfo destinationRuntimeFileInfo = sourceRuntimeFileInfo.CreateEncryptedName();
            Passphrase       passphrase = new Passphrase("laDabled@tAmeopot33");

            AxCryptFile.Encrypt(sourceRuntimeFileInfo, destinationRuntimeFileInfo, passphrase, AxCryptOptions.SetFileTimes | AxCryptOptions.EncryptWithCompression, new ProgressContext());

            Assert.That(destinationRuntimeFileInfo.CreationTimeUtc, Is.EqualTo(sourceRuntimeFileInfo.CreationTimeUtc), "We're expecting file times to be set as the original from the headers.");
            Assert.That(destinationRuntimeFileInfo.LastAccessTimeUtc, Is.EqualTo(sourceRuntimeFileInfo.LastAccessTimeUtc), "We're expecting file times to be set as the original from the headers.");
            Assert.That(destinationRuntimeFileInfo.LastWriteTimeUtc, Is.EqualTo(sourceRuntimeFileInfo.LastWriteTimeUtc), "We're expecting file times to be set as the original from the headers.");

            DirectoryInfo    decryptedDirectoryInfo   = new DirectoryInfo(_rootPath.PathCombine("Destination", "Decrypted.txt"));
            string           decryptedFullName        = Path.Combine(decryptedDirectoryInfo.FullName, "David Copperfield.txt");
            IRuntimeFileInfo decryptedRuntimeFileInfo = OS.Current.FileInfo(decryptedFullName);

            AxCryptFile.Decrypt(destinationRuntimeFileInfo, decryptedRuntimeFileInfo, passphrase.DerivedPassphrase, AxCryptOptions.SetFileTimes, new ProgressContext());

            Assert.That(decryptedRuntimeFileInfo.CreationTimeUtc, Is.EqualTo(sourceRuntimeFileInfo.CreationTimeUtc), "We're expecting file times to be set as the original from the headers.");
            Assert.That(decryptedRuntimeFileInfo.LastAccessTimeUtc, Is.EqualTo(sourceRuntimeFileInfo.LastAccessTimeUtc), "We're expecting file times to be set as the original from the headers.");
            Assert.That(decryptedRuntimeFileInfo.LastWriteTimeUtc, Is.EqualTo(sourceRuntimeFileInfo.LastWriteTimeUtc), "We're expecting file times to be set as the original from the headers.");

            using (StreamReader sourceStreamReader = new StreamReader(sourceRuntimeFileInfo.OpenRead(), Encoding.GetEncoding("Windows-1252")))
            {
                using (StreamReader decryptedStreamReader = new StreamReader(decryptedRuntimeFileInfo.OpenRead(), Encoding.GetEncoding("Windows-1252")))
                {
                    string source    = sourceStreamReader.ReadToEnd();
                    string decrypted = decryptedStreamReader.ReadToEnd();

                    Assert.That(decrypted, Is.EqualTo(source), "Comparing original plain text with the decrypted encrypted plain text.");
                }
            }
        }
コード例 #6
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.");
        }
コード例 #7
0
        private static ActiveFile TryDecrypt(IRuntimeFileInfo sourceFileInfo, IRuntimeFileInfo destinationFolderInfo, IEnumerable <AesKey> keys, ProgressContext progress)
        {
            ActiveFile destinationActiveFile = null;

            foreach (AesKey key in keys)
            {
                if (OS.Log.IsInfoEnabled)
                {
                    OS.Log.LogInfo("Decrypting '{0}'".InvariantFormat(sourceFileInfo.FullName));
                }
                using (FileLock sourceLock = FileLock.Lock(sourceFileInfo))
                {
                    using (AxCryptDocument document = AxCryptFile.Document(sourceFileInfo, key, new ProgressContext()))
                    {
                        if (!document.PassphraseIsValid)
                        {
                            continue;
                        }

                        destinationActiveFile = DecryptActiveFileDocument(sourceFileInfo, destinationFolderInfo, document, progress);
                        break;
                    }
                }
            }
            return(destinationActiveFile);
        }
コード例 #8
0
 public SessionNotificationHandler(FileSystemState fileSystemState, KnownIdentities knownIdentities, ActiveFileAction activeFileAction, AxCryptFile axCryptFile, IStatusChecker statusChecker)
 {
     _fileSystemState  = fileSystemState;
     _knownIdentities  = knownIdentities;
     _activeFileAction = activeFileAction;
     _axCryptFile      = axCryptFile;
     _statusChecker    = statusChecker;
 }
コード例 #9
0
        public void TestMakeAxCryptFileName()
        {
            string testFile = _rootPath.PathCombine("Directory", "file.txt");
            string axxFile  = _rootPath.PathCombine("Directory", "file-txt.axx");
            string madeName = AxCryptFile.MakeAxCryptFileName(New <IDataStore>(testFile));

            Assert.That(madeName, Is.EqualTo(axxFile), "The AxCrypt version of the name is unexpected.");
        }
コード例 #10
0
        public async Task EncryptAsync(Stream clearIn, Stream encryptedOut, string fileName)
        {
            EncryptionParameters parameters = new EncryptionParameters(_cryptoId, _passphrase);
            await parameters.AddAsync(_publicKeys);

            EncryptedProperties properties = new EncryptedProperties(fileName);

            AxCryptFile.Encrypt(clearIn, encryptedOut, properties, parameters, _options, new ProgressContext());
        }
コード例 #11
0
        public static void TestDecryptToDestinationDirectoryWithWrongPassphrase()
        {
            IRuntimeFileInfo sourceFileInfo       = OS.Current.FileInfo(_helloWorldAxxPath);
            string           destinationDirectory = Path.Combine(_rootPath, "Encrypted");

            string destinationFileName = AxCryptFile.Decrypt(sourceFileInfo, destinationDirectory, new Passphrase("Wrong Passphrase").DerivedPassphrase, AxCryptOptions.None, new ProgressContext());

            Assert.That(destinationFileName, Is.Null, "When the wrong passphrase is given, the returned file name should be null to signal this.");
        }
コード例 #12
0
        public static void TestDecryptToDestinationDirectory()
        {
            IRuntimeFileInfo sourceFileInfo       = OS.Current.FileInfo(_helloWorldAxxPath);
            string           destinationDirectory = Path.Combine(_rootPath, "Encrypted");

            string destinationFileName = AxCryptFile.Decrypt(sourceFileInfo, destinationDirectory, new Passphrase("a").DerivedPassphrase, AxCryptOptions.None, new ProgressContext());

            Assert.That(destinationFileName, Is.EqualTo("HelloWorld-Key-a.txt"), "The correct filename should be returned from decryption.");
        }
コード例 #13
0
        public void TestInvalidArguments()
        {
            IDataStore       sourceFileInfo      = New <IDataStore>(_testTextPath);
            IDataStore       destinationFileInfo = sourceFileInfo.CreateEncryptedName();
            IAxCryptDocument document            = new V1AxCryptDocument();
            IDataStore       decryptedFileInfo   = New <IDataStore>(Path.Combine(_rootPath, "decrypted test.txt"));

            IAxCryptDocument     nullDocument             = null;
            IDataStore           nullFileInfo             = null;
            LogOnIdentity        nullKey                  = null;
            ProgressContext      nullProgress             = null;
            EncryptionParameters nullEncryptionParameters = null;
            Stream nullStream = null;
            string nullString = null;
            Func <Stream, Task> nullStreamAction = null;
            FileLock            nullFileLock     = null;

            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(nullFileInfo, destinationFileInfo, new EncryptionParameters(new V1Aes128CryptoFactory().CryptoId, new Passphrase("axcrypt")), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(sourceFileInfo, nullFileInfo, new EncryptionParameters(new V1Aes128CryptoFactory().CryptoId, new Passphrase("axcrypt")), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(sourceFileInfo, destinationFileInfo, nullEncryptionParameters, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(sourceFileInfo, destinationFileInfo, new EncryptionParameters(new V1Aes128CryptoFactory().CryptoId, new Passphrase("axcrypt")), AxCryptOptions.EncryptWithCompression, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(nullFileInfo, new MemoryStream(), EncryptionParameters.Empty, AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(sourceFileInfo, nullStream, EncryptionParameters.Empty, AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(sourceFileInfo, new MemoryStream(), nullEncryptionParameters, AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { new AxCryptFile().Encrypt(sourceFileInfo, new MemoryStream(), EncryptionParameters.Empty, AxCryptOptions.None, nullProgress); });

            using (FileLock fileInfoLock = New <FileLocker>().Acquire(New <IDataStore>(_testTextPath)))
            {
                Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(nullDocument, fileInfoLock, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
                Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(document, nullFileLock, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
                Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(document, fileInfoLock, AxCryptOptions.SetFileTimes, nullProgress); }));
            }

            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(nullFileInfo, decryptedFileInfo, LogOnIdentity.Empty, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(sourceFileInfo, nullFileInfo, LogOnIdentity.Empty, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(sourceFileInfo, decryptedFileInfo, nullKey, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(sourceFileInfo, decryptedFileInfo, LogOnIdentity.Empty, AxCryptOptions.SetFileTimes, nullProgress); }));

            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(nullFileInfo, Path.Combine(_rootPath, "Directory"), LogOnIdentity.Empty, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(sourceFileInfo, nullString, LogOnIdentity.Empty, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(sourceFileInfo, Path.Combine(_rootPath, "Directory"), nullKey, AxCryptOptions.SetFileTimes, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Decrypt(sourceFileInfo, Path.Combine(_rootPath, "Directory"), LogOnIdentity.Empty, AxCryptOptions.SetFileTimes, nullProgress); }));

            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Document(nullFileInfo, LogOnIdentity.Empty, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Document(sourceFileInfo, nullKey, new ProgressContext()); }));
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Document(sourceFileInfo, LogOnIdentity.Empty, nullProgress); }));

            Assert.ThrowsAsync <ArgumentNullException>((async() => { await New <AxCryptFile>().EncryptToFileWithBackupAsync(null, async(Stream stream) => { await Task.Delay(0); }, new ProgressContext()); }));
            using (FileLock fileInfoLock = New <FileLocker>().Acquire(New <IDataStore>(_testTextPath)))
            {
                Assert.ThrowsAsync <ArgumentNullException>((async() => { await New <AxCryptFile>().EncryptToFileWithBackupAsync(fileInfoLock, nullStreamAction, new ProgressContext()); }));
            }

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.MakeAxCryptFileName(nullFileInfo); });
            Assert.Throws <ArgumentNullException>((TestDelegate)(() => { New <AxCryptFile>().Wipe(nullFileLock, new ProgressContext()); }));
        }
コード例 #14
0
        static bool TryDecrypt(IRuntimeFileInfo file, string filePath, AesKey key, ProgressContext progress, out string encryptedFileName)
        {
            encryptedFileName = AxCryptFile.Decrypt(file, filePath, key, AxCryptOptions.EncryptWithCompression, progress);

            if (encryptedFileName == null)
            {
                return(false);
            }
            return(true);
        }
コード例 #15
0
        public static void TestDefault()
        {
            AxCryptFile axCryptFile = New <AxCryptFile>();

            Assert.That(axCryptFile is AxCryptFile, Is.True);

            TypeMap.Register.New <FileSystemState>(() => new FileSystemState());
            ActiveFileAction actions = New <ActiveFileAction>();

            Assert.That(actions is ActiveFileAction, Is.True);
        }
コード例 #16
0
        public static void TestWriteToFileWithBackupWithCancel()
        {
            IRuntimeFileInfo destinationFileInfo = OS.Current.FileInfo(_rootPath.PathCombine("Written", "File.txt"));

            using (MemoryStream inputStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("A string with some text")))
            {
                Assert.Throws <OperationCanceledException>(() => { AxCryptFile.WriteToFileWithBackup(destinationFileInfo, (Stream stream) => { throw new OperationCanceledException(); }, new ProgressContext()); });
                string           tempFilePath = _rootPath.PathCombine("Written", "File.bak");
                IRuntimeFileInfo tempFileInfo = OS.Current.FileInfo(tempFilePath);
                Assert.That(tempFileInfo.Exists, Is.False, "The .bak file should be removed.");
            }
        }
コード例 #17
0
        public static void TestWipe()
        {
            string           testFile = _rootPath.PathCombine("Folder", "file-to-be-wiped.txt");
            IRuntimeFileInfo fileInfo = OS.Current.FileInfo(testFile);

            using (Stream writeStream = fileInfo.OpenWrite())
            {
            }
            Assert.That(fileInfo.Exists, "Now it should exist.");
            AxCryptFile.Wipe(fileInfo, new ProgressContext());
            Assert.That(!fileInfo.Exists, "And now it should not exist after wiping.");
        }
コード例 #18
0
        private bool OpenAxCryptDocument(string fullName, FileOperationEventArgs e)
        {
            e.AxCryptDocument = null;
            try
            {
                IRuntimeFileInfo source = OS.Current.FileInfo(fullName);
                e.OpenFileFullName = source.FullName;
                foreach (AesKey key in _fileSystemState.KnownKeys.Keys)
                {
                    e.AxCryptDocument = AxCryptFile.Document(source, key, new ProgressContext());
                    if (e.AxCryptDocument.PassphraseIsValid)
                    {
                        break;
                    }
                    e.AxCryptDocument.Dispose();
                    e.AxCryptDocument = null;
                }

                Passphrase passphrase;
                while (e.AxCryptDocument == null)
                {
                    OnQueryDecryptionPassphrase(e);
                    if (e.Cancel)
                    {
                        e.Status = FileOperationStatus.Canceled;
                        return(false);
                    }
                    passphrase        = new Passphrase(e.Passphrase);
                    e.AxCryptDocument = AxCryptFile.Document(source, passphrase.DerivedPassphrase, new ProgressContext());
                    if (!e.AxCryptDocument.PassphraseIsValid)
                    {
                        e.AxCryptDocument.Dispose();
                        e.AxCryptDocument = null;
                        continue;
                    }
                    e.Key = passphrase.DerivedPassphrase;
                    OnKnownKeyAdded(e);
                }
            }
            catch (IOException ioex)
            {
                if (e.AxCryptDocument != null)
                {
                    e.AxCryptDocument.Dispose();
                    e.AxCryptDocument = null;
                }
                FileOperationStatus status = ioex is FileNotFoundException ? FileOperationStatus.FileDoesNotExist : FileOperationStatus.Exception;
                e.Status = status;
                return(false);
            }
            return(true);
        }
コード例 #19
0
        public static void TestInvalidArguments()
        {
            IRuntimeFileInfo sourceFileInfo      = OS.Current.FileInfo(_testTextPath);
            IRuntimeFileInfo destinationFileInfo = sourceFileInfo.CreateEncryptedName();
            AxCryptDocument  document            = new AxCryptDocument();
            IRuntimeFileInfo decryptedFileInfo   = OS.Current.FileInfo(Path.Combine(_rootPath, "decrypted test.txt"));

            AxCryptDocument  nullDocument     = null;
            IRuntimeFileInfo nullFileInfo     = null;
            AesKey           nullKey          = null;
            ProgressContext  nullProgress     = null;
            Passphrase       nullPassphrase   = null;
            Stream           nullStream       = null;
            string           nullString       = null;
            Action <Stream>  nullStreamAction = null;

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(nullFileInfo, destinationFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, nullFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, destinationFileInfo, nullPassphrase, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, destinationFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(nullFileInfo, new MemoryStream(), new AesKey(), AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, nullStream, new AesKey(), AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, new MemoryStream(), nullKey, AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, new MemoryStream(), new AesKey(), AxCryptOptions.None, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(nullDocument, decryptedFileInfo, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(document, nullFileInfo, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(document, decryptedFileInfo, AxCryptOptions.SetFileTimes, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(nullFileInfo, decryptedFileInfo, new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, nullFileInfo, new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, decryptedFileInfo, nullKey, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, decryptedFileInfo, new AesKey(), AxCryptOptions.SetFileTimes, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(nullFileInfo, Path.Combine(_rootPath, "Directory"), new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, nullString, new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, Path.Combine(_rootPath, "Directory"), nullKey, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, Path.Combine(_rootPath, "Directory"), new AesKey(), AxCryptOptions.SetFileTimes, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Document(nullFileInfo, new AesKey(), new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Document(sourceFileInfo, nullKey, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Document(sourceFileInfo, new AesKey(), nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.WriteToFileWithBackup(null, (Stream stream) => { }, new ProgressContext()); });
            IRuntimeFileInfo fileInfo = OS.Current.FileInfo(_testTextPath);

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.WriteToFileWithBackup(fileInfo, nullStreamAction, new ProgressContext()); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.MakeAxCryptFileName(nullFileInfo); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Wipe(nullFileInfo, new ProgressContext()); });
        }
コード例 #20
0
        public static void TestInvalidPassphrase()
        {
            IRuntimeFileInfo sourceFileInfo    = OS.Current.FileInfo(_testTextPath);
            IRuntimeFileInfo encryptedFileInfo = sourceFileInfo.CreateEncryptedName();

            Assert.That(encryptedFileInfo.Name, Is.EqualTo("test-txt.axx"), "Wrong encrypted file name based on the plain text file name.");
            AxCryptFile.Encrypt(sourceFileInfo, encryptedFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, new ProgressContext());

            IRuntimeFileInfo decryptedFileInfo = OS.Current.FileInfo(Path.Combine(_rootPath, "decrypted.txt"));
            bool             isPassphraseOk    = AxCryptFile.Decrypt(encryptedFileInfo, decryptedFileInfo, new Passphrase("wrong").DerivedPassphrase, AxCryptOptions.None, new ProgressContext());

            Assert.That(isPassphraseOk, Is.False, "The passphrase is wrong and should be wrong!");
        }
コード例 #21
0
        public static void TestWipeWithDelayedUntilDoneCancel()
        {
            IRuntimeFileInfo fileInfo = OS.Current.FileInfo(_davidCopperfieldTxtPath);

            ProgressContext progress = new ProgressContext(TimeSpan.Zero);

            progress.Progressing += (object sender, ProgressEventArgs e) =>
            {
                ((ProgressContext)sender).Cancel = true;
            };
            Assert.Throws <OperationCanceledException>(() => { AxCryptFile.Wipe(fileInfo, progress); });
            Assert.That(!fileInfo.Exists, "The file should be completely wiped, even if canceled at start.");
        }
コード例 #22
0
        public async Task TestEncryptFileWhenDestinationExists()
        {
            IDataStore sourceInfo = New <IDataStore>(_davidCopperfieldTxtPath);
            IDataStore expectedDestinationInfo = New <IDataStore>(AxCryptFile.MakeAxCryptFileName(sourceInfo));

            using (Stream stream = expectedDestinationInfo.OpenWrite())
            {
            }

            FileOperationsController controller = new FileOperationsController();
            string        destinationPath       = String.Empty;
            LogOnIdentity logOnIdentity         = null;

            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("allan");
            };
            controller.QuerySaveFileAs += (object sender, FileOperationEventArgs e) =>
            {
                e.SaveFileFullName = Path.Combine(Path.GetDirectoryName(e.SaveFileFullName), "alternative-name.axx");
            };
            Guid cryptoId = Guid.Empty;

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
                logOnIdentity   = e.LogOnIdentity;
                cryptoId        = e.CryptoId;
            };

            FileOperationContext status = await controller.EncryptFileAsync(New <IDataStore>(_davidCopperfieldTxtPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");

            Assert.That(Path.GetFileName(destinationPath), Is.EqualTo("alternative-name.axx"), "The alternative name should be used, since the default existed.");
            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(destinationInfo.IsAvailable, "After encryption the destination file should be created.");

            EncryptionParameters encryptionParameters = new EncryptionParameters(cryptoId, logOnIdentity);
            await encryptionParameters.AddAsync(logOnIdentity.PublicKeys);

            Headers           headers = new Headers();
            AxCryptReaderBase reader  = headers.CreateReader(new LookAheadStream(destinationInfo.OpenRead()));

            using (IAxCryptDocument document = AxCryptReaderBase.Document(reader))
            {
                document.Load(logOnIdentity.Passphrase, cryptoId, headers);
                Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the passphrase given.");
            }
        }
コード例 #23
0
        public void TestVerifyHmacOkV2()
        {
            string sourceFullName = _davidCopperfieldTxtPath;

            IDataStore           plainStore           = New <IDataStore>(sourceFullName);
            IDataStore           encryptedStore       = plainStore.CreateEncryptedName();
            LogOnIdentity        identity             = new LogOnIdentity("laDabled@tAmeopot33");
            EncryptionParameters encryptionParameters = new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, identity.Passphrase);

            new AxCryptFile().Encrypt(plainStore, encryptedStore, encryptionParameters, AxCryptOptions.SetFileTimes | AxCryptOptions.EncryptWithCompression, new ProgressContext());
            bool hmacIsOk = new AxCryptFile().VerifyFileHmac(encryptedStore, identity, new ProgressContext());

            Assert.That(hmacIsOk, "HMAC did not verify as expected for a V2 document.");
        }
コード例 #24
0
        public static void TestUncompressedEncryptedDecryptAxCrypt17()
        {
            IRuntimeFileInfo sourceRuntimeFileInfo      = OS.Current.FileInfo(_uncompressedAxxPath);
            IRuntimeFileInfo destinationRuntimeFileInfo = OS.Current.FileInfo(Path.Combine(Path.GetDirectoryName(_uncompressedAxxPath), "Uncompressed.zip"));
            Passphrase       passphrase = new Passphrase("Uncompressable");

            using (AxCryptDocument document = new AxCryptDocument())
            {
                bool isOk = document.Load(sourceRuntimeFileInfo.OpenRead(), passphrase.DerivedPassphrase);
                Assert.That(isOk, Is.True, "The document should load ok.");
                AxCryptFile.Decrypt(document, destinationRuntimeFileInfo, AxCryptOptions.None, new ProgressContext());
                Assert.That(document.DocumentHeaders.UncompressedLength, Is.EqualTo(0), "Since the data is not compressed, there should not be a CompressionInfo, but in 1.x there is, with value zero.");
            }
        }
コード例 #25
0
        public static void TestCheckActiveFilesUpdateButWithTargetLockedForSharing()
        {
            DateTime utcNow = OS.Current.UtcNow;

            FakeRuntimeFileInfo.AddFile(_encryptedFile1, utcNow, utcNow, utcNow, FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt));
            Passphrase passphrase = new Passphrase("a");

            AxCryptFile.Decrypt(OS.Current.FileInfo(_encryptedFile1), OS.Current.FileInfo(_decryptedFile1), passphrase.DerivedPassphrase, AxCryptOptions.None, new ProgressContext());

            ActiveFile activeFile = new ActiveFile(OS.Current.FileInfo(_encryptedFile1), OS.Current.FileInfo(_decryptedFile1), passphrase.DerivedPassphrase, ActiveFileStatus.AssumedOpenAndDecrypted, null);

            _fileSystemState.Add(activeFile);

            IRuntimeFileInfo decryptedFileInfo = OS.Current.FileInfo(_decryptedFile1);

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

            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = (() => { return(utcNow.AddMinutes(1)); });
            bool changedWasRaised = false;

            _fileSystemState.Changed += ((object sender, ActiveFileChangedEventArgs e) =>
            {
                changedWasRaised = true;
            });

            _fileSystemState.KnownKeys.Add(passphrase.DerivedPassphrase);

            EventHandler eventHandler = ((object sender, EventArgs e) =>
            {
                FakeRuntimeFileInfo fileInfo = (FakeRuntimeFileInfo)sender;
                if (fileInfo.FullName == _decryptedFile1)
                {
                    throw new IOException("Faked sharing violation.");
                }
            });

            FakeRuntimeFileInfo.OpeningForRead += eventHandler;
            try
            {
                _fileSystemState.CheckActiveFiles(ChangedEventMode.RaiseOnlyOnModified, new ProgressContext());
            }
            finally
            {
                FakeRuntimeFileInfo.OpeningForRead -= eventHandler;
            }

            Assert.That(changedWasRaised, Is.True, "The ActiveFile should be modified because it should now be marked as not shareable.");
            activeFile = _fileSystemState.FindEncryptedPath(_encryptedFile1);
            Assert.That(activeFile.Status.HasMask(ActiveFileStatus.NotShareable), Is.True, "The ActiveFile should be marked as not shareable after the checking of active files.");
        }
コード例 #26
0
        private Task <bool> EncryptFilePreparationAsync(IDataStore sourceFileInfo)
        {
            _eventArgs.OpenFileFullName = sourceFileInfo.FullName;

            if (String.Compare(Resolve.Portable.Path().GetExtension(sourceFileInfo.FullName), OS.Current.AxCryptExtension, StringComparison.OrdinalIgnoreCase) == 0)
            {
                _eventArgs.Status = new FileOperationContext(sourceFileInfo.FullName, ErrorStatus.FileAlreadyEncrypted);
                return(Task.FromResult(false));
            }

            using (FileLock fileLock = New <FileLocker>().Acquire(sourceFileInfo))
            {
                if (IsLocked(fileLock))
                {
                    return(Task.FromResult(false));
                }

                IDataStore destinationFileInfo = New <IDataStore>(AxCryptFile.MakeAxCryptFileName(sourceFileInfo));
                _eventArgs.SaveFileFullName = destinationFileInfo.FullName;
                _eventArgs.OpenFileFullName = sourceFileInfo.FullName;
                if (destinationFileInfo.IsAvailable)
                {
                    OnQuerySaveFileAs(_eventArgs);
                    if (_eventArgs.Cancel)
                    {
                        _eventArgs.Status = new FileOperationContext(sourceFileInfo.FullName, ErrorStatus.Canceled);
                        return(Task.FromResult(false));
                    }
                }

                if (Resolve.KnownIdentities.DefaultEncryptionIdentity == LogOnIdentity.Empty)
                {
                    OnQueryEncryptionPassphrase(_eventArgs);
                    if (_eventArgs.Cancel)
                    {
                        _eventArgs.Status = new FileOperationContext(sourceFileInfo.FullName, ErrorStatus.Canceled);
                        return(Task.FromResult(false));
                    }
                }
                else
                {
                    _eventArgs.LogOnIdentity = Resolve.KnownIdentities.DefaultEncryptionIdentity;
                }

                OnQuerySharedPublicKeys(_eventArgs);
            }

            return(Task.FromResult(true));
        }
コード例 #27
0
        private static byte[] GetSaveDataForKeys(UserKeyPair keys, string originalFileName, Passphrase passphrase)
        {
            string json = Resolve.Serializer.Serialize(keys);

            using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                EncryptionParameters encryptionParameters = new EncryptionParameters(Resolve.CryptoFactory.Preferred.CryptoId, passphrase);
                EncryptedProperties  properties           = new EncryptedProperties(originalFileName);
                using (MemoryStream exportStream = new MemoryStream())
                {
                    AxCryptFile.Encrypt(stream, exportStream, properties, encryptionParameters, AxCryptOptions.EncryptWithCompression, new ProgressContext());
                    return(exportStream.ToArray());
                }
            }
        }
コード例 #28
0
        private bool WipeFileOperation()
        {
            if (_eventArgs.Skip)
            {
                _eventArgs.Status = FileOperationStatus.Success;
                return(true);
            }

            _progress.NotifyLevelStart();
            AxCryptFile.Wipe(OS.Current.FileInfo(_eventArgs.SaveFileFullName), _progress);
            _progress.NotifyLevelFinished();

            _eventArgs.Status = FileOperationStatus.Success;
            return(true);
        }
コード例 #29
0
        public static void TestWriteToFileWithBackup()
        {
            string destinationFilePath = _rootPath.PathCombine("Written", "File.txt");

            using (MemoryStream inputStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("A string with some text")))
            {
                IRuntimeFileInfo destinationFileInfo = OS.Current.FileInfo(destinationFilePath);
                AxCryptFile.WriteToFileWithBackup(destinationFileInfo, (Stream stream) => { inputStream.CopyTo(stream, 4096); }, new ProgressContext());
                using (TextReader read = new StreamReader(destinationFileInfo.OpenRead()))
                {
                    string readString = read.ReadToEnd();
                    Assert.That(readString, Is.EqualTo("A string with some text"), "Where expecting the same string to be read back.");
                }
            }
        }
コード例 #30
0
        public static void EncryptFile(ProgressContext progress, Action <string, ProgressContext> failure)
        {
            CreatePassphraseViewController passphraseController = new CreatePassphraseViewController {
                EncryptedFileName = DateTime.Now.ToString("yyyyMMddHHmmss")
            };

            NSOpenPanel open = new NSOpenPanel {
                AccessoryView            = passphraseController.View,
                AllowsMultipleSelection  = false,
                CanChooseDirectories     = false,
                CanChooseFiles           = true,
                CanSelectHiddenExtension = true,
                CollectionBehavior       = NSWindowCollectionBehavior.Transient,
                ExtensionHidden          = true,
                Message = "Please select the file you would like to encrypt",
                Prompt  = "Encrypt file",
                Title   = "Encrypt",
                TreatsFilePackagesAsDirectories = false,
            };

            open.Begin(result => {
                if (result == 0 || open.Urls.Length == 0)
                {
                    return;
                }
                if (!open.Urls[0].IsFileUrl)
                {
                    return;
                }
                string sourceFilePath = open.Urls[0].Path;
                open.Close();

                IRuntimeFileInfo sourceFile = OS.Current.FileInfo(sourceFilePath);
                Passphrase passphrase       = passphraseController.VerifiedPassphrase;
                if (passphrase == null)
                {
                    return;
                }

                IRuntimeFileInfo targetFile = GetTargetFileName(sourceFilePath, passphraseController.EncryptedFileName);

                ThreadPool.QueueUserWorkItem(delegate {
                    using (new NSAutoreleasePool()) {
                        AxCryptFile.EncryptFileWithBackupAndWipe(sourceFile, targetFile, passphrase.DerivedPassphrase, progress);
                    };
                });
            });
        }