public static void TestInvalidArguments()
        {
            using (Stream inputStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("AxCrypt is Great!")))
            {
                using (Stream outputStream = new MemoryStream())
                {
                    using (AxCryptDocument document = new AxCryptDocument())
                    {
                        Passphrase      passphrase = new Passphrase("a");
                        DocumentHeaders headers    = new DocumentHeaders(passphrase.DerivedPassphrase);

                        Assert.Throws <ArgumentNullException>(() => { document.EncryptTo(null, inputStream, outputStream, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws <ArgumentNullException>(() => { document.EncryptTo(headers, null, outputStream, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws <ArgumentNullException>(() => { document.EncryptTo(headers, inputStream, null, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws <ArgumentNullException>(() => { document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.EncryptWithCompression, null); });
                        Assert.Throws <ArgumentException>(() => { document.EncryptTo(headers, inputStream, new NonSeekableStream(), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws <ArgumentException>(() => { document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.EncryptWithCompression | AxCryptOptions.EncryptWithoutCompression, new ProgressContext()); });
                        Assert.Throws <ArgumentException>(() => { document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.None, new ProgressContext()); });

                        Assert.Throws <ArgumentNullException>(() => { document.CopyEncryptedTo(null, outputStream, new ProgressContext()); });
                        Assert.Throws <ArgumentNullException>(() => { document.CopyEncryptedTo(headers, null, new ProgressContext()); });
                        Assert.Throws <ArgumentException>(() => { document.CopyEncryptedTo(headers, new NonSeekableStream(), new ProgressContext()); });
                        Assert.Throws <InternalErrorException>(() => { document.CopyEncryptedTo(headers, outputStream, new ProgressContext()); });
                    }
                }
            }
        }
Example #2
0
        public static void TestEncryptFileWithDefaultEncryptionKey()
        {
            _fileSystemState.KnownKeys.DefaultEncryptionKey = new Passphrase("default").DerivedPassphrase;
            FileOperationsController controller     = new FileOperationsController(_fileSystemState);
            bool queryEncryptionPassphraseWasCalled = false;

            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                queryEncryptionPassphraseWasCalled = true;
            };
            string destinationPath = String.Empty;

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

            FileOperationStatus status = controller.EncryptFile(_davidCopperfieldTxtPath);

            Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success.");
            Assert.That(!queryEncryptionPassphraseWasCalled, "No query of encryption passphrase should be needed since there is a default set.");

            IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath);

            Assert.That(destinationInfo.Exists, "After encryption the destination file should be created.");
            using (AxCryptDocument document = new AxCryptDocument())
            {
                using (Stream stream = destinationInfo.OpenRead())
                {
                    document.Load(stream, new Passphrase("default").DerivedPassphrase);
                    Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the default passphrase given.");
                }
            }
        }
        public static void TestChangePassphraseForSimpleFile()
        {
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct and should work!");

                Passphrase newPassphrase = new Passphrase("b");
                using (Stream changedStream = new MemoryStream())
                {
                    DocumentHeaders outputDocumentHeaders = new DocumentHeaders(document.DocumentHeaders);
                    outputDocumentHeaders.SetCurrentVersion();
                    outputDocumentHeaders.RewrapMasterKey(newPassphrase.DerivedPassphrase);

                    document.CopyEncryptedTo(outputDocumentHeaders, changedStream, new ProgressContext());
                    changedStream.Position = 0;
                    using (AxCryptDocument changedDocument = new AxCryptDocument())
                    {
                        bool changedKeyIsOk = changedDocument.Load(changedStream, newPassphrase.DerivedPassphrase);
                        Assert.That(changedKeyIsOk, Is.True, "The changed passphrase provided is correct and should work!");

                        using (MemoryStream plaintextStream = new MemoryStream())
                        {
                            changedDocument.DecryptTo(plaintextStream, new ProgressContext());
                            Assert.That(Encoding.ASCII.GetString(plaintextStream.GetBuffer(), 0, (int)plaintextStream.Length), Is.EqualTo("HelloWorld"), "Unexpected result of decryption.");
                            Assert.That(changedDocument.DocumentHeaders.PlaintextLength, Is.EqualTo(10), "'HelloWorld' should be 10 bytes uncompressed plaintext.");
                        }
                    }
                }
            }
        }
        public static void TestChangePassphraseForSimpleFile()
        {
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct and should work!");

                Passphrase newPassphrase = new Passphrase("b");
                using (Stream changedStream = new MemoryStream())
                {
                    DocumentHeaders outputDocumentHeaders = new DocumentHeaders(document.DocumentHeaders);
                    outputDocumentHeaders.SetCurrentVersion();
                    outputDocumentHeaders.RewrapMasterKey(newPassphrase.DerivedPassphrase);

                    document.CopyEncryptedTo(outputDocumentHeaders, changedStream, new ProgressContext());
                    changedStream.Position = 0;
                    using (AxCryptDocument changedDocument = new AxCryptDocument())
                    {
                        bool changedKeyIsOk = changedDocument.Load(changedStream, newPassphrase.DerivedPassphrase);
                        Assert.That(changedKeyIsOk, Is.True, "The changed passphrase provided is correct and should work!");

                        using (MemoryStream plaintextStream = new MemoryStream())
                        {
                            changedDocument.DecryptTo(plaintextStream, new ProgressContext());
                            Assert.That(Encoding.ASCII.GetString(plaintextStream.GetBuffer(), 0, (int)plaintextStream.Length), Is.EqualTo("HelloWorld"), "Unexpected result of decryption.");
                            Assert.That(changedDocument.DocumentHeaders.PlaintextLength, Is.EqualTo(10), "'HelloWorld' should be 10 bytes uncompressed plaintext.");
                        }
                    }
                }
            }
        }
        public static void TestInvalidHmacInCopyEncryptedTo()
        {
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct and should work!");

                Passphrase newPassphrase = new Passphrase("b");
                using (Stream changedStream = new MemoryStream())
                {
                    DocumentHeaders outputDocumentHeaders = new DocumentHeaders(document.DocumentHeaders);
                    outputDocumentHeaders.SetCurrentVersion();
                    outputDocumentHeaders.RewrapMasterKey(newPassphrase.DerivedPassphrase);

                    byte[] modifiedHmacBytes = document.DocumentHeaders.Hmac.GetBytes();
                    modifiedHmacBytes[0]         += 1;
                    document.DocumentHeaders.Hmac = new DataHmac(modifiedHmacBytes);
                    Assert.Throws <Axantum.AxCrypt.Core.Runtime.InvalidDataException>(() =>
                    {
                        document.CopyEncryptedTo(outputDocumentHeaders, changedStream, new ProgressContext());
                    });
                }
            }
        }
        public static 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 = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("AxCrypt is Great!")))
            {
                using (Stream outputStream = new MemoryStream())
                {
                    using (AxCryptDocument document = new AxCryptDocument())
                    {
                        Passphrase             passphrase = new Passphrase("a");
                        DocumentHeadersForTest headers    = new DocumentHeadersForTest(passphrase.DerivedPassphrase);
                        headers.FileName          = "MyFile.txt";
                        headers.CreationTimeUtc   = creationTimeUtc;
                        headers.LastAccessTimeUtc = lastAccessTimeUtc;
                        headers.LastWriteTimeUtc  = lastWriteTimeUtc;
                        headers.SetNextFileVersionMajor();
                        document.DocumentHeaders = headers;
                        document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.EncryptWithoutCompression, new ProgressContext());
                    }
                    outputStream.Position = 0;
                    using (AxCryptDocument document = new AxCryptDocument())
                    {
                        Passphrase passphrase = new Passphrase("a");
                        Assert.Throws <FileFormatException>(() => { document.Load(outputStream, passphrase.DerivedPassphrase); });
                    }
                }
            }
        }
Example #7
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.");
            }
        }
Example #8
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);
        }
Example #9
0
        public static void TestOpenAndLaunchOfAxCryptDocumentWhenAlreadyDecrypted()
        {
            TestOpenAndLaunchOfAxCryptDocument();

            FakeLauncher launcher = null;

            SetupAssembly.FakeRuntimeEnvironment.Launcher = ((string path) =>
            {
                launcher = new FakeLauncher(path);
                return(launcher);
            });

            FileOperationStatus status;

            using (AxCryptDocument document = new AxCryptDocument())
            {
                using (Stream stream = OS.Current.FileInfo(_helloWorldAxxPath).OpenRead())
                {
                    document.Load(stream, new Passphrase("a").DerivedPassphrase);
                    status = _fileSystemState.OpenAndLaunchApplication(_helloWorldAxxPath, document, new ProgressContext());
                }
            }

            Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The launch should succeed.");
            Assert.That(launcher, Is.Not.Null, "There should be a call to launch.");
            Assert.That(Path.GetFileName(launcher.Path), Is.EqualTo("HelloWorld-Key-a.txt"), "The file should be decrypted and the name should be the original from the encrypted headers.");
        }
        public static void TestDoubleDispose()
        {
            AxCryptDocument document = new AxCryptDocument();

            document.Dispose();
            document.Dispose();
        }
Example #11
0
        public static void TestSimpleEncryptFile()
        {
            FileOperationsController controller = new FileOperationsController(_fileSystemState);
            string destinationPath = String.Empty;

            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.Passphrase = "allan";
            };
            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
            };

            FileOperationStatus status = controller.EncryptFile(_davidCopperfieldTxtPath);

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

            IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath);

            Assert.That(destinationInfo.Exists, "After encryption the destination file should be created.");
            using (AxCryptDocument document = new AxCryptDocument())
            {
                using (Stream stream = destinationInfo.OpenRead())
                {
                    document.Load(stream, new Passphrase("allan").DerivedPassphrase);
                    Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the passphrase given.");
                }
            }
        }
 public static void TestNoMagicGuidFound()
 {
     byte[] dummy = Encoding.ASCII.GetBytes("This is a string that generates some bytes, none of which will match the magic GUID");
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         Assert.Throws <FileFormatException>(() => { document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(dummy), passphrase.DerivedPassphrase); }, "Calling with dummy data that does not contain a GUID.");
     }
 }
 public static void TestInvalidPassphraseWithSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("b");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.False, "The passphrase provided is wrong!");
     }
 }
 public static void TestHmacCalculationFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         document.DecryptTo(Stream.Null, new ProgressContext());
     }
 }
 public static void TestDecryptWithoutLoadFirstFromEmptyFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             Assert.Throws <InternalErrorException>(() => { document.DecryptTo(plaintextStream, new ProgressContext()); });
         }
     }
 }
 public static void TestIsCompressedFromLargerFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("Å ä Ö");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.david_copperfield_key__aa_ae_oe__ulu_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         bool isCompressed = document.DocumentHeaders.IsCompressed;
         Assert.That(isCompressed, Is.True, "This file should be compressed.");
     }
 }
 public static void TestIsCompressedFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         bool isCompressed = document.DocumentHeaders.IsCompressed;
         Assert.That(isCompressed, Is.False, "This file should not be compressed.");
     }
 }
Example #18
0
        public static void TestOpenAndLaunchOfAxCryptDocumentArgumentNullException()
        {
            FileSystemState nullFileSystemState = null;
            string          nullString          = null;
            AxCryptDocument nullDocument        = null;
            ProgressContext nullProgressContext = null;

            Assert.Throws <ArgumentNullException>(() => { nullFileSystemState.OpenAndLaunchApplication(_helloWorldAxxPath, new AxCryptDocument(), new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { _fileSystemState.OpenAndLaunchApplication(nullString, new AxCryptDocument(), new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { _fileSystemState.OpenAndLaunchApplication(_helloWorldAxxPath, nullDocument, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { _fileSystemState.OpenAndLaunchApplication(_helloWorldAxxPath, new AxCryptDocument(), nullProgressContext); });
        }
Example #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()); });
        }
 public static void TestInputStreamTooShort()
 {
     using (MemoryStream testStream = new MemoryStream())
     {
         byte[] guid = AxCrypt1Guid.GetBytes();
         testStream.Write(guid, 0, guid.Length);
         testStream.Position = 0;
         using (AxCryptDocument document = new AxCryptDocument())
         {
             Assert.Throws <FileFormatException>(() => { document.Load(testStream, new Passphrase(String.Empty).DerivedPassphrase); }, "Calling with too short a stream, only containing a GUID.");
         }
     }
 }
        public static void TestHmacFromSimpleFile()
        {
            DataHmac expectedHmac = new DataHmac(new byte[] { 0xF9, 0xAF, 0x2E, 0x67, 0x7D, 0xCF, 0xC9, 0xFE, 0x06, 0x4B, 0x39, 0x08, 0xE7, 0x5A, 0x87, 0x81 });

            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
                DataHmac hmac = document.DocumentHeaders.Hmac;
                Assert.That(hmac.GetBytes(), Is.EqualTo(expectedHmac.GetBytes()), "Wrong HMAC");
            }
        }
 public static void TestFileNameFromSimpleFileWithUnicode()
 {
     using (Stream testStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
     {
         using (AxCryptDocument document = new AxCryptDocument())
         {
             Passphrase passphrase = new Passphrase("a");
             bool       keyIsOk    = document.Load(testStream, passphrase.DerivedPassphrase);
             Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
             string fileName = document.DocumentHeaders.FileName;
             Assert.That(fileName, Is.EqualTo("HelloWorld-Key-a.txt"), "Wrong file name");
         }
     }
 }
 public static void TestAnsiFileNameFromSimpleFile()
 {
     using (Stream testStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
     {
         using (AxCryptDocument document = new AxCryptDocument())
         {
             Passphrase passphrase = new Passphrase("a");
             bool keyIsOk = document.Load(testStream, passphrase.DerivedPassphrase);
             Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
             string fileName = document.DocumentHeaders.FileName;
             Assert.That(fileName, Is.EqualTo("HelloWorld-Key-a.txt"), "Wrong file name");
         }
     }
 }
 public static void TestFailedHmacCalculationFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         document.DocumentHeaders.Hmac = new DataHmac(new byte[document.DocumentHeaders.Hmac.Length]);
         Assert.Throws <Axantum.AxCrypt.Core.Runtime.InvalidDataException>(() =>
         {
             document.DecryptTo(Stream.Null, new ProgressContext());
         });
     }
 }
Example #25
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.");
            }
        }
 public static void TestDecryptUncompressedFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             document.DecryptTo(plaintextStream, new ProgressContext());
             Assert.That(Encoding.ASCII.GetString(plaintextStream.GetBuffer(), 0, (int)plaintextStream.Length), Is.EqualTo("HelloWorld"), "Unexpected result of decryption.");
             Assert.That(document.DocumentHeaders.PlaintextLength, Is.EqualTo(10), "'HelloWorld' should be 10 bytes uncompressed plaintext.");
         }
     }
 }
        public static void TestFileTimesFromSimpleFile()
        {
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");

                string creationTime = document.DocumentHeaders.CreationTimeUtc.ToString(CultureInfo.InvariantCulture);
                Assert.That(creationTime, Is.EqualTo("01/13/2012 17:17:18"), "Checking creation time.");
                string lastAccessTime = document.DocumentHeaders.LastAccessTimeUtc.ToString(CultureInfo.InvariantCulture);
                Assert.That(lastAccessTime, Is.EqualTo("01/13/2012 17:17:18"), "Checking last access time.");
                string lastWriteTime = document.DocumentHeaders.LastWriteTimeUtc.ToString(CultureInfo.InvariantCulture);
                Assert.That(lastWriteTime, Is.EqualTo("01/13/2012 17:17:45"), "Checking last modify time.");
            }
        }
Example #28
0
        public static void TestEncryptToStream()
        {
            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.");
            using (Stream destinationStream = destinationFileInfo.OpenWrite())
            {
                AxCryptFile.Encrypt(sourceFileInfo, destinationStream, new Passphrase("axcrypt").DerivedPassphrase, 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.");
            }
        }
 public static void TestDecryptCompressedFromLegacy0B6()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("åäö");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.tst_0_0b6_key__aaaeoe__medium_html), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "A correct passphrase was provided, but it was not accepted.");
         Assert.That(document.DocumentHeaders.IsCompressed, Is.True, "The file is compressed.");
         Assert.That(document.DocumentHeaders.FileName, Is.EqualTo("readme.html"), "The file name should be 'readme.html'.");
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             document.DecryptTo(plaintextStream, new ProgressContext());
             Assert.That(document.DocumentHeaders.PlaintextLength, Is.EqualTo(3736), "The compressed content should be recorded as 3736 bytes in the headers.");
             Assert.That(plaintextStream.Length, Is.EqualTo(9528), "The file should be 9528 bytes uncompressed plaintext in actual fact.");
         }
     }
 }
 public static void TestDecryptAfterFailedLoad()
 {
     using (Stream testStream = new MemoryStream())
     {
         AxCrypt1Guid.Write(testStream);
         testStream.Position = 0;
         using (AxCryptDocument document = new AxCryptDocument())
         {
             Passphrase passphrase = new Passphrase("Å ä Ö");
             Assert.Throws <FileFormatException>(() => { document.Load(testStream, passphrase.DerivedPassphrase); });
             using (MemoryStream plaintextStream = new MemoryStream())
             {
                 Assert.Throws <InternalErrorException>(() => { document.DecryptTo(plaintextStream, new ProgressContext()); });
             }
         }
     }
 }
Example #31
0
 private static ActiveFile CheckKeysForAlreadyDecryptedFile(ActiveFile destinationActiveFile, IEnumerable <AesKey> keys, ProgressContext progress)
 {
     foreach (AesKey key in keys)
     {
         using (AxCryptDocument document = AxCryptFile.Document(destinationActiveFile.EncryptedFileInfo, key, progress))
         {
             if (document.PassphraseIsValid)
             {
                 if (OS.Log.IsWarningEnabled)
                 {
                     OS.Log.LogWarning("File was already decrypted and the key was known for '{0}' to '{1}'".InvariantFormat(destinationActiveFile.EncryptedFileInfo.FullName, destinationActiveFile.DecryptedFileInfo.FullName));
                 }
                 return(new ActiveFile(destinationActiveFile, key));
             }
         }
     }
     return(null);
 }
 public static void TestDecryptCompressedFromLargerFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("Å ä Ö");
         bool       keyIsOk    = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.david_copperfield_key__aa_ae_oe__ulu_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             document.DecryptTo(plaintextStream, new ProgressContext());
             string text = Encoding.UTF8.GetString(plaintextStream.GetBuffer(), 0, (int)plaintextStream.Length);
             Assert.That(text, Is.StringStarting("The Project Gutenberg EBook of David Copperfield, by Charles Dickens"), "Unexpected start of David Copperfield.");
             Assert.That(text, Is.StringEnding("subscribe to our email newsletter to hear about new eBooks." + (Char)13 + (Char)10), "Unexpected end of David Copperfield.");
             Assert.That(text.Length, Is.EqualTo(1992490), "Wrong length of full text of David Copperfield.");
             Assert.That(document.DocumentHeaders.PlaintextLength, Is.EqualTo(795855), "Wrong expected length of compressed text of David Copperfield.");
         }
     }
 }
        public static void TestDecryptUncompressedWithCancel()
        {
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
                using (MemoryStream plaintextStream = new MemoryStream())
                {
                    ProgressContext progress = new ProgressContext(TimeSpan.Zero);
                    progress.Progressing += (object sender, ProgressEventArgs e) =>
                    {
                        throw new OperationCanceledException();
                    };

                    Assert.Throws<OperationCanceledException>(() => { document.DecryptTo(plaintextStream, progress); });
                }
            }
        }
 public static void TestDecryptUncompressedWithPaddingError()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         using (MemoryStream encryptedFile = FakeRuntimeFileInfo.ExpandableMemoryStream((byte[])Resources.helloworld_key_a_txt.Clone()))
         {
             encryptedFile.Seek(-1, SeekOrigin.End);
             byte lastByte = (byte)encryptedFile.ReadByte();
             ++lastByte;
             encryptedFile.Seek(-1, SeekOrigin.End);
             encryptedFile.WriteByte(lastByte);
             encryptedFile.Position = 0;
             bool keyIsOk = document.Load(encryptedFile, passphrase.DerivedPassphrase);
             Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
             using (MemoryStream plaintextStream = new MemoryStream())
             {
                 Assert.Throws<CryptographicException>(() => { document.DecryptTo(plaintextStream, new ProgressContext()); });
             }
         }
     }
 }
Example #35
0
        public static FileOperationStatus OpenAndLaunchApplication(this FileSystemState fileSystemState, string file, AxCryptDocument document, ProgressContext progress)
        {
            if (fileSystemState == null)
            {
                throw new ArgumentNullException("fileSystemState");
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }
            if (progress == null)
            {
                throw new ArgumentNullException("progress");
            }

            IRuntimeFileInfo fileInfo = OS.Current.FileInfo(file);

            ActiveFile destinationActiveFile = fileSystemState.FindEncryptedPath(fileInfo.FullName);
            if (destinationActiveFile == null || !destinationActiveFile.DecryptedFileInfo.Exists)
            {
                IRuntimeFileInfo destinationFolderInfo = GetTemporaryDestinationFolder(destinationActiveFile);
                destinationActiveFile = DecryptActiveFileDocument(fileInfo, destinationFolderInfo, document, progress);
            }
            else
            {
                destinationActiveFile = new ActiveFile(destinationActiveFile, document.DocumentHeaders.KeyEncryptingKey);
            }

            fileSystemState.Add(destinationActiveFile);
            fileSystemState.Save();

            FileOperationStatus status = LaunchApplicationForDocument(fileSystemState, destinationActiveFile);
            return status;
        }
 public static void TestSimpleEncryptToWithoutCompression()
 {
     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 = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("AxCrypt is Great!")))
     {
         using (Stream outputStream = new MemoryStream())
         {
             using (AxCryptDocument document = new AxCryptDocument())
             {
                 Passphrase passphrase = new Passphrase("a");
                 DocumentHeaders headers = new DocumentHeaders(passphrase.DerivedPassphrase);
                 headers.FileName = "MyFile.txt";
                 headers.CreationTimeUtc = creationTimeUtc;
                 headers.LastAccessTimeUtc = lastAccessTimeUtc;
                 headers.LastWriteTimeUtc = lastWriteTimeUtc;
                 document.DocumentHeaders = headers;
                 document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.EncryptWithoutCompression, new ProgressContext());
             }
             outputStream.Position = 0;
             using (AxCryptDocument document = new AxCryptDocument())
             {
                 Passphrase passphrase = new Passphrase("a");
                 bool keyIsOk = document.Load(outputStream, passphrase.DerivedPassphrase);
                 Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
                 Assert.That(document.DocumentHeaders.FileName, Is.EqualTo("MyFile.txt"));
                 Assert.That(document.DocumentHeaders.CreationTimeUtc, Is.EqualTo(creationTimeUtc));
                 Assert.That(document.DocumentHeaders.LastAccessTimeUtc, Is.EqualTo(lastAccessTimeUtc));
                 Assert.That(document.DocumentHeaders.LastWriteTimeUtc, Is.EqualTo(lastWriteTimeUtc));
                 using (MemoryStream plaintextStream = new MemoryStream())
                 {
                     document.DecryptTo(plaintextStream, new ProgressContext());
                     Assert.That(document.DocumentHeaders.UncompressedLength, Is.EqualTo(-1), "'AxCrypt is Great!' should not return a value at all for uncompressed, since it was not compressed.");
                     Assert.That(document.DocumentHeaders.PlaintextLength, Is.EqualTo(17), "'AxCrypt is Great!' is 17 bytes plaintext length.");
                     Assert.That(Encoding.ASCII.GetString(plaintextStream.GetBuffer(), 0, (int)plaintextStream.Length), Is.EqualTo("AxCrypt is Great!"), "Unexpected result of decryption.");
                 }
             }
         }
     }
 }
 public static void TestNoMagicGuidFound()
 {
     byte[] dummy = Encoding.ASCII.GetBytes("This is a string that generates some bytes, none of which will match the magic GUID");
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         Assert.Throws<FileFormatException>(() => { document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(dummy), passphrase.DerivedPassphrase); }, "Calling with dummy data that does not contain a GUID.");
     }
 }
Example #38
0
        public static void TestDecryptWithCancel()
        {
            IRuntimeFileInfo sourceFileInfo = OS.Current.FileInfo(_helloWorldAxxPath);
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                using (Stream sourceStream = sourceFileInfo.OpenRead())
                {
                    bool keyIsOk = document.Load(sourceStream, passphrase.DerivedPassphrase);
                    Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
                    IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(_rootPath.PathCombine("Destination", "Decrypted.txt"));

                    ProgressContext progress = new ProgressContext(TimeSpan.Zero);
                    progress.Progressing += (object sender, ProgressEventArgs e) =>
                    {
                        throw new OperationCanceledException();
                    };

                    Assert.Throws<OperationCanceledException>(() => { AxCryptFile.Decrypt(document, destinationInfo, AxCryptOptions.None, progress); });
                }
            }
        }
 public static void TestDecryptCompressedWithTruncatedFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("Å ä Ö");
         using (MemoryStream encryptedFile = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.david_copperfield_key__aa_ae_oe__ulu_txt))
         {
             encryptedFile.SetLength(encryptedFile.Length / 2);
             encryptedFile.Position = 0;
             bool keyIsOk = document.Load(encryptedFile, passphrase.DerivedPassphrase);
             Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
             using (MemoryStream plaintextStream = new MemoryStream())
             {
                 Assert.Throws<CryptographicException>(() => { document.DecryptTo(plaintextStream, new ProgressContext()); });
             }
         }
     }
 }
 public static void TestDecryptAfterFailedLoad()
 {
     using (Stream testStream = new MemoryStream())
     {
         AxCrypt1Guid.Write(testStream);
         testStream.Position = 0;
         using (AxCryptDocument document = new AxCryptDocument())
         {
             Passphrase passphrase = new Passphrase("Å ä Ö");
             Assert.Throws<FileFormatException>(() => { document.Load(testStream, passphrase.DerivedPassphrase); });
             using (MemoryStream plaintextStream = new MemoryStream())
             {
                 Assert.Throws<InternalErrorException>(() => { document.DecryptTo(plaintextStream, new ProgressContext()); });
             }
         }
     }
 }
 public static void TestInputStreamTooShort()
 {
     using (MemoryStream testStream = new MemoryStream())
     {
         byte[] guid = AxCrypt1Guid.GetBytes();
         testStream.Write(guid, 0, guid.Length);
         testStream.Position = 0;
         using (AxCryptDocument document = new AxCryptDocument())
         {
             Assert.Throws<FileFormatException>(() => { document.Load(testStream, new Passphrase(String.Empty).DerivedPassphrase); }, "Calling with too short a stream, only containing a GUID.");
         }
     }
 }
 public static void TestHmacFromSimpleFile()
 {
     DataHmac expectedHmac = new DataHmac(new byte[] { 0xF9, 0xAF, 0x2E, 0x67, 0x7D, 0xCF, 0xC9, 0xFE, 0x06, 0x4B, 0x39, 0x08, 0xE7, 0x5A, 0x87, 0x81 });
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         DataHmac hmac = document.DocumentHeaders.Hmac;
         Assert.That(hmac.GetBytes(), Is.EqualTo(expectedHmac.GetBytes()), "Wrong HMAC");
     }
 }
 public static void TestHmacCalculationFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         document.DecryptTo(Stream.Null, new ProgressContext());
     }
 }
 public static void TestDecryptUncompressedFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             document.DecryptTo(plaintextStream, new ProgressContext());
             Assert.That(Encoding.ASCII.GetString(plaintextStream.GetBuffer(), 0, (int)plaintextStream.Length), Is.EqualTo("HelloWorld"), "Unexpected result of decryption.");
             Assert.That(document.DocumentHeaders.PlaintextLength, Is.EqualTo(10), "'HelloWorld' should be 10 bytes uncompressed plaintext.");
         }
     }
 }
 public static void TestDecryptCompressedFromLegacy0B6()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("åäö");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.tst_0_0b6_key__aaaeoe__medium_html), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "A correct passphrase was provided, but it was not accepted.");
         Assert.That(document.DocumentHeaders.IsCompressed, Is.True, "The file is compressed.");
         Assert.That(document.DocumentHeaders.FileName, Is.EqualTo("readme.html"), "The file name should be 'readme.html'.");
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             document.DecryptTo(plaintextStream, new ProgressContext());
             Assert.That(document.DocumentHeaders.PlaintextLength, Is.EqualTo(3736), "The compressed content should be recorded as 3736 bytes in the headers.");
             Assert.That(plaintextStream.Length, Is.EqualTo(9528), "The file should be 9528 bytes uncompressed plaintext in actual fact.");
         }
     }
 }
 public static void TestIsCompressedFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         bool isCompressed = document.DocumentHeaders.IsCompressed;
         Assert.That(isCompressed, Is.False, "This file should not be compressed.");
     }
 }
        public static void TestInvalidArguments()
        {
            using (Stream inputStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("AxCrypt is Great!")))
            {
                using (Stream outputStream = new MemoryStream())
                {
                    using (AxCryptDocument document = new AxCryptDocument())
                    {
                        Passphrase passphrase = new Passphrase("a");
                        DocumentHeaders headers = new DocumentHeaders(passphrase.DerivedPassphrase);

                        Assert.Throws<ArgumentNullException>(() => { document.EncryptTo(null, inputStream, outputStream, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws<ArgumentNullException>(() => { document.EncryptTo(headers, null, outputStream, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws<ArgumentNullException>(() => { document.EncryptTo(headers, inputStream, null, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws<ArgumentNullException>(() => { document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.EncryptWithCompression, null); });
                        Assert.Throws<ArgumentException>(() => { document.EncryptTo(headers, inputStream, new NonSeekableStream(), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
                        Assert.Throws<ArgumentException>(() => { document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.EncryptWithCompression | AxCryptOptions.EncryptWithoutCompression, new ProgressContext()); });
                        Assert.Throws<ArgumentException>(() => { document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.None, new ProgressContext()); });

                        Assert.Throws<ArgumentNullException>(() => { document.CopyEncryptedTo(null, outputStream, new ProgressContext()); });
                        Assert.Throws<ArgumentNullException>(() => { document.CopyEncryptedTo(headers, null, new ProgressContext()); });
                        Assert.Throws<ArgumentException>(() => { document.CopyEncryptedTo(headers, new NonSeekableStream(), new ProgressContext()); });
                        Assert.Throws<InternalErrorException>(() => { document.CopyEncryptedTo(headers, outputStream, new ProgressContext()); });
                    }
                }
            }
        }
        public static void TestEncryptFileWithDefaultEncryptionKey()
        {
            _fileSystemState.KnownKeys.DefaultEncryptionKey = new Passphrase("default").DerivedPassphrase;
            FileOperationsController controller = new FileOperationsController(_fileSystemState);
            bool queryEncryptionPassphraseWasCalled = false;
            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
                {
                    queryEncryptionPassphraseWasCalled = true;
                };
            string destinationPath = String.Empty;
            controller.Completed += (object sender, FileOperationEventArgs e) =>
                {
                    destinationPath = e.SaveFileFullName;
                };

            FileOperationStatus status = controller.EncryptFile(_davidCopperfieldTxtPath);
            Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success.");
            Assert.That(!queryEncryptionPassphraseWasCalled, "No query of encryption passphrase should be needed since there is a default set.");

            IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath);
            Assert.That(destinationInfo.Exists, "After encryption the destination file should be created.");
            using (AxCryptDocument document = new AxCryptDocument())
            {
                using (Stream stream = destinationInfo.OpenRead())
                {
                    document.Load(stream, new Passphrase("default").DerivedPassphrase);
                    Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the default passphrase given.");
                }
            }
        }
        public static void TestInvalidHmacInCopyEncryptedTo()
        {
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct and should work!");

                Passphrase newPassphrase = new Passphrase("b");
                using (Stream changedStream = new MemoryStream())
                {
                    DocumentHeaders outputDocumentHeaders = new DocumentHeaders(document.DocumentHeaders);
                    outputDocumentHeaders.SetCurrentVersion();
                    outputDocumentHeaders.RewrapMasterKey(newPassphrase.DerivedPassphrase);

                    byte[] modifiedHmacBytes = document.DocumentHeaders.Hmac.GetBytes();
                    modifiedHmacBytes[0] += 1;
                    document.DocumentHeaders.Hmac = new DataHmac(modifiedHmacBytes);
                    Assert.Throws<Axantum.AxCrypt.Core.Runtime.InvalidDataException>(() =>
                    {
                        document.CopyEncryptedTo(outputDocumentHeaders, changedStream, new ProgressContext());
                    });
                }
            }
        }
 public static void TestInvalidPassphraseWithSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("b");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.False, "The passphrase provided is wrong!");
     }
 }
 public static 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 = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("AxCrypt is Great!")))
     {
         using (Stream outputStream = new MemoryStream())
         {
             using (AxCryptDocument document = new AxCryptDocument())
             {
                 Passphrase passphrase = new Passphrase("a");
                 DocumentHeadersForTest headers = new DocumentHeadersForTest(passphrase.DerivedPassphrase);
                 headers.FileName = "MyFile.txt";
                 headers.CreationTimeUtc = creationTimeUtc;
                 headers.LastAccessTimeUtc = lastAccessTimeUtc;
                 headers.LastWriteTimeUtc = lastWriteTimeUtc;
                 headers.SetNextFileVersionMajor();
                 document.DocumentHeaders = headers;
                 document.EncryptTo(headers, inputStream, outputStream, AxCryptOptions.EncryptWithoutCompression, new ProgressContext());
             }
             outputStream.Position = 0;
             using (AxCryptDocument document = new AxCryptDocument())
             {
                 Passphrase passphrase = new Passphrase("a");
                 Assert.Throws<FileFormatException>(() => { document.Load(outputStream, passphrase.DerivedPassphrase); });
             }
         }
     }
 }
 public static void TestIsCompressedFromLargerFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("Å ä Ö");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.david_copperfield_key__aa_ae_oe__ulu_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         bool isCompressed = document.DocumentHeaders.IsCompressed;
         Assert.That(isCompressed, Is.True, "This file should be compressed.");
     }
 }
 public static void TestDecryptWithoutLoadFirstFromEmptyFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             Assert.Throws<InternalErrorException>(() => { document.DecryptTo(plaintextStream, new ProgressContext()); });
         }
     }
 }
 public static void TestDecryptCompressedFromLargerFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("Å ä Ö");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.david_copperfield_key__aa_ae_oe__ulu_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         using (MemoryStream plaintextStream = new MemoryStream())
         {
             document.DecryptTo(plaintextStream, new ProgressContext());
             string text = Encoding.UTF8.GetString(plaintextStream.GetBuffer(), 0, (int)plaintextStream.Length);
             Assert.That(text, Is.StringStarting("The Project Gutenberg EBook of David Copperfield, by Charles Dickens"), "Unexpected start of David Copperfield.");
             Assert.That(text, Is.StringEnding("subscribe to our email newsletter to hear about new eBooks." + (Char)13 + (Char)10), "Unexpected end of David Copperfield.");
             Assert.That(text.Length, Is.EqualTo(1992490), "Wrong length of full text of David Copperfield.");
             Assert.That(document.DocumentHeaders.PlaintextLength, Is.EqualTo(795855), "Wrong expected length of compressed text of David Copperfield.");
         }
     }
 }
Example #55
0
        private static ActiveFile DecryptActiveFileDocument(IRuntimeFileInfo sourceFileInfo, IRuntimeFileInfo destinationFolderInfo, AxCryptDocument document, ProgressContext progress)
        {
            string destinationName = document.DocumentHeaders.FileName;
            string destinationPath = Path.Combine(destinationFolderInfo.FullName, destinationName);

            IRuntimeFileInfo destinationFileInfo = OS.Current.FileInfo(destinationPath);
            using (FileLock fileLock = FileLock.Lock(destinationFileInfo))
            {
                AxCryptFile.Decrypt(document, destinationFileInfo, AxCryptOptions.SetFileTimes, progress);
            }
            ActiveFile destinationActiveFile = new ActiveFile(sourceFileInfo, destinationFileInfo, document.DocumentHeaders.KeyEncryptingKey, ActiveFileStatus.AssumedOpenAndDecrypted | ActiveFileStatus.IgnoreChange, null);
            if (OS.Log.IsInfoEnabled)
            {
                OS.Log.LogInfo("File decrypted from '{0}' to '{1}'".InvariantFormat(sourceFileInfo.FullName, destinationActiveFile.DecryptedFileInfo.FullName));
            }
            return destinationActiveFile;
        }
 public static void TestDoubleDispose()
 {
     AxCryptDocument document = new AxCryptDocument();
     document.Dispose();
     document.Dispose();
 }
        public static void TestEncryptFileWhenDestinationExists()
        {
            IRuntimeFileInfo sourceInfo = OS.Current.FileInfo(_davidCopperfieldTxtPath);
            IRuntimeFileInfo expectedDestinationInfo = OS.Current.FileInfo(AxCryptFile.MakeAxCryptFileName(sourceInfo));
            using (Stream stream = expectedDestinationInfo.OpenWrite())
            {
            }

            FileOperationsController controller = new FileOperationsController(_fileSystemState);
            string destinationPath = String.Empty;
            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.Passphrase = "allan";
            };
            controller.QuerySaveFileAs += (object sender, FileOperationEventArgs e) =>
            {
                e.SaveFileFullName = Path.Combine(Path.GetDirectoryName(e.SaveFileFullName), "alternative-name.axx");
            };
            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
            };

            FileOperationStatus status = controller.EncryptFile(_davidCopperfieldTxtPath);
            Assert.That(status, Is.EqualTo(FileOperationStatus.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.");
            IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath);
            Assert.That(destinationInfo.Exists, "After encryption the destination file should be created.");
            using (AxCryptDocument document = new AxCryptDocument())
            {
                using (Stream stream = destinationInfo.OpenRead())
                {
                    document.Load(stream, new Passphrase("allan").DerivedPassphrase);
                    Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the passphrase given.");
                }
            }
        }
 public static void TestFailedHmacCalculationFromSimpleFile()
 {
     using (AxCryptDocument document = new AxCryptDocument())
     {
         Passphrase passphrase = new Passphrase("a");
         bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
         Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");
         document.DocumentHeaders.Hmac = new DataHmac(new byte[document.DocumentHeaders.Hmac.Length]);
         Assert.Throws<Axantum.AxCrypt.Core.Runtime.InvalidDataException>(() =>
         {
             document.DecryptTo(Stream.Null, new ProgressContext());
         });
     }
 }
        public static void TestSimpleEncryptFileOnThreadWorker()
        {
            FileOperationsController controller = new FileOperationsController(_fileSystemState);
            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.Passphrase = "allan";
            };
            string destinationPath = String.Empty;
            FileOperationStatus status = FileOperationStatus.Unknown;
            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
                status = e.Status;
            };

            using (ThreadWorker worker = new ThreadWorker(new ProgressContext()))
            {
                controller.EncryptFile(_davidCopperfieldTxtPath, worker);
                worker.Join();
            }
            Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success.");

            IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath);
            Assert.That(destinationInfo.Exists, "After encryption the destination file should be created.");
            using (AxCryptDocument document = new AxCryptDocument())
            {
                using (Stream stream = destinationInfo.OpenRead())
                {
                    document.Load(stream, new Passphrase("allan").DerivedPassphrase);
                    Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the passphrase given.");
                }
            }
        }
        public static void TestFileTimesFromSimpleFile()
        {
            using (AxCryptDocument document = new AxCryptDocument())
            {
                Passphrase passphrase = new Passphrase("a");
                bool keyIsOk = document.Load(FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt), passphrase.DerivedPassphrase);
                Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");

                string creationTime = document.DocumentHeaders.CreationTimeUtc.ToString(CultureInfo.InvariantCulture);
                Assert.That(creationTime, Is.EqualTo("01/13/2012 17:17:18"), "Checking creation time.");
                string lastAccessTime = document.DocumentHeaders.LastAccessTimeUtc.ToString(CultureInfo.InvariantCulture);
                Assert.That(lastAccessTime, Is.EqualTo("01/13/2012 17:17:18"), "Checking last access time.");
                string lastWriteTime = document.DocumentHeaders.LastWriteTimeUtc.ToString(CultureInfo.InvariantCulture);
                Assert.That(lastWriteTime, Is.EqualTo("01/13/2012 17:17:45"), "Checking last modify time.");
            }
        }