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 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); });
                    }
                }
            }
        }
        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 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 #6
0
        public static void Setup()
        {
            SetupAssembly.AssemblySetup();

            FakeRuntimeFileInfo.AddFile(_testTextPath, FakeRuntimeFileInfo.TestDate1Utc, FakeRuntimeFileInfo.TestDate2Utc, FakeRuntimeFileInfo.TestDate3Utc, FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("This is a short file")));
            FakeRuntimeFileInfo.AddFile(_davidCopperfieldTxtPath, FakeRuntimeFileInfo.TestDate4Utc, FakeRuntimeFileInfo.TestDate5Utc, FakeRuntimeFileInfo.TestDate6Utc, FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.GetEncoding(1252).GetBytes(Resources.david_copperfield)));
            FakeRuntimeFileInfo.AddFile(_uncompressedAxxPath, FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.uncompressable_zip));
            FakeRuntimeFileInfo.AddFile(_helloWorldAxxPath, FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt));
        }
 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 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 #10
0
 public static void TestFindMagicGuidFromSimpleFile()
 {
     using (Stream testStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
     {
         using (AxCryptReader axCryptReader = AxCryptReader.Create(testStream))
         {
             Assert.That(axCryptReader.Read(), Is.True, "We should be able to read the Guid");
             Assert.That(axCryptReader.CurrentItemType, Is.EqualTo(AxCryptItemType.MagicGuid), "We're expecting to have found a MagicGuid");
         }
     }
 }
 public 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.");
     }
 }
Example #12
0
        public static void Setup()
        {
            SetupAssembly.AssemblySetup();

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

            _fileSystemState = new FileSystemState();
            _fileSystemState.Load(FileSystemState.DefaultPathInfo);
        }
Example #13
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.");
            }
        }
Example #14
0
        public static void Setup()
        {
            SetupAssembly.AssemblySetup();

            FakeRuntimeFileInfo.AddFile(_testTextPath, FakeRuntimeFileInfo.TestDate1Utc, FakeRuntimeFileInfo.TestDate2Utc, FakeRuntimeFileInfo.TestDate1Utc, FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("This is a short file")));
            FakeRuntimeFileInfo.AddFile(_davidCopperfieldTxtPath, FakeRuntimeFileInfo.TestDate4Utc, FakeRuntimeFileInfo.TestDate5Utc, FakeRuntimeFileInfo.TestDate6Utc, FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.GetEncoding(1252).GetBytes(Resources.david_copperfield)));
            FakeRuntimeFileInfo.AddFile(_uncompressedAxxPath, FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.uncompressable_zip));
            FakeRuntimeFileInfo.AddFile(_helloWorldAxxPath, FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt));

            _fileSystemState = new FileSystemState();
            _fileSystemState.Load(OS.Current.FileInfo(Path.Combine(Path.GetTempPath(), "FileSystemState.xml")));
        }
        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 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 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");
         }
     }
 }
Example #18
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.");
        }
Example #19
0
 public static void TestPropertiesAndMethods()
 {
     using (MemoryStream memoryStream = FakeRuntimeFileInfo.ExpandableMemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }))
     {
         string kilroy = String.Empty;
         using (FakeStream testStream = new FakeStream(memoryStream, (string wasHere) => { kilroy += wasHere; }))
         {
             using (ProgressStream progressStream = new ProgressStream(testStream, new ProgressContext()))
             {
                 kilroy = String.Empty;
                 Assert.That(progressStream.CanRead, Is.True, "The underlying stream is readable.");
                 Assert.That(kilroy, Is.EqualTo("CanRead"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 Assert.That(progressStream.CanWrite, Is.True, "The underlying stream is writable.");
                 Assert.That(kilroy, Is.EqualTo("CanWrite"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 Assert.That(progressStream.CanSeek, Is.True, "The underlying stream is seekable.");
                 Assert.That(kilroy, Is.EqualTo("CanSeek"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 progressStream.Flush();
                 Assert.That(kilroy, Is.EqualTo("Flush"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 Assert.That(progressStream.Length, Is.EqualTo(10), "There are 10 bytes  in the underlying stream.");
                 Assert.That(kilroy, Is.EqualTo("Length"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 Assert.That(progressStream.Seek(-4, SeekOrigin.End), Is.EqualTo(6), "4 bytes from the end of 10 should be 6.");
                 Assert.That(kilroy, Is.EqualTo("Seek"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 Assert.That(progressStream.Position, Is.EqualTo(6), "The position should still be at 6.");
                 Assert.That(kilroy, Is.EqualTo("getPosition"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 progressStream.Position = 0;
                 Assert.That(kilroy, Is.EqualTo("setPosition"), "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 progressStream.Write(new byte[] { 13 }, 0, 1);
                 Assert.That(kilroy.Contains("Write"), Is.True, "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 progressStream.Position = 0;
                 byte[] firstByte = new byte[1];
                 progressStream.Read(firstByte, 0, 1);
                 Assert.That(kilroy.Contains("Read"), Is.True, "ProgressStream should delegate to the underlying stream.");
                 kilroy = String.Empty;
                 Assert.That(firstByte[0], Is.EqualTo(13), "13 was just written to the first position.");
                 progressStream.SetLength(5);
                 Assert.That(kilroy, Is.EqualTo("SetLength"), "ProgressStream should delegate to the underlying stream.");
             }
         }
     }
 }
 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.");
         }
     }
 }
Example #21
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.");
                }
            }
        }
        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.");
            }
        }
        public static void TestObjectDisposed()
        {
            using (Stream inputStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
            {
                using (AxCryptReader axCryptReader = new AxCryptStreamReader(inputStream))
                {
                    axCryptReader.Dispose();

                    Assert.Throws <ObjectDisposedException>(() =>
                    {
                        bool isOk = axCryptReader.Read();
                        Object.Equals(isOk, null);
                    }, "The reader is disposed.");
                }
            }
        }
        public static void TestBadKey()
        {
            using (Stream testStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
            {
                using (AxCryptReader reader = AxCryptReader.Create(testStream))
                {
                    Passphrase      passphrase        = new Passphrase("b");
                    DocumentHeaders documentHeaders   = new DocumentHeaders(passphrase.DerivedPassphrase);
                    bool            isPassphraseValid = documentHeaders.Load(reader);

                    Assert.That(isPassphraseValid, Is.False, "The passphrase is intentionally wrong for this test case.");
                    Assert.That(documentHeaders.HmacSubkey, Is.Null, "Since the passphrase is wrong, HmacSubkey should return null.");
                    Assert.That(documentHeaders.DataSubkey, Is.Null, "Since the passphrase is wrong, DataSubkey should return null.");
                    Assert.That(documentHeaders.HeadersSubkey, Is.Null, "Since the passphrase is wrong, HeadersSubkey should return null.");
                }
            }
        }
 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.");
         }
     }
 }
Example #26
0
        public void TestUnwrapFromSimpleFile()
        {
            using (Stream testStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
            {
                KeyWrap1HeaderBlock keyWrapHeaderBlock = null;
                using (AxCryptReader axCryptReader = AxCryptReader.Create(testStream))
                {
                    int headers = 0;
                    while (axCryptReader.Read())
                    {
                        switch (axCryptReader.CurrentItemType)
                        {
                        case AxCryptItemType.None:
                            break;

                        case AxCryptItemType.MagicGuid:
                            break;

                        case AxCryptItemType.HeaderBlock:
                            if (axCryptReader.CurrentHeaderBlock.HeaderBlockType == HeaderBlockType.KeyWrap1)
                            {
                                keyWrapHeaderBlock = (KeyWrap1HeaderBlock)axCryptReader.CurrentHeaderBlock;
                                ++headers;
                            }
                            break;

                        case AxCryptItemType.Data:
                            break;

                        case AxCryptItemType.EndOfStream:
                            break;

                        default:
                            break;
                        }
                    }
                    Assert.That(headers, Is.EqualTo(1), "We're expecting exactly one KeyWrap1 block to be found!");
                    byte[] wrapped = keyWrapHeaderBlock.GetKeyData();
                    using (KeyWrap keyWrap = new KeyWrap(new Passphrase("a").DerivedPassphrase, keyWrapHeaderBlock.Salt, keyWrapHeaderBlock.Iterations, KeyWrapMode.AxCrypt))
                    {
                        byte[] unwrapped = keyWrap.Unwrap(wrapped);
                        Assert.That(unwrapped.Length, Is.Not.EqualTo(0), "An unwrapped key is invalid if it is returned as a zero-length array.");
                    }
                }
            }
        }
Example #27
0
        public static void TestFindPreambleHeaderBlockFromSimpleFile()
        {
            using (Stream testStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
            {
                using (AxCryptReader axCryptReader = AxCryptReader.Create(testStream))
                {
                    bool blockFound = false;
                    int  headers    = 0;
                    while (axCryptReader.Read())
                    {
                        switch (axCryptReader.CurrentItemType)
                        {
                        case AxCryptItemType.None:
                            break;

                        case AxCryptItemType.MagicGuid:
                            break;

                        case AxCryptItemType.HeaderBlock:
                            if (axCryptReader.CurrentHeaderBlock.HeaderBlockType == HeaderBlockType.Preamble)
                            {
                                Assert.That(blockFound, Is.False, "We should only find one single PreambleHeaderBlock");
                                blockFound = true;

                                Assert.That(headers, Is.EqualTo(0), "Preamble must be first");
                                PreambleHeaderBlock preambleHeaderBlock = (PreambleHeaderBlock)axCryptReader.CurrentHeaderBlock;
                                Assert.That(preambleHeaderBlock.Hmac.Length, Is.EqualTo(16), "The HMAC in the preamble must be exactly 16 bytes.");
                            }
                            ++headers;
                            break;

                        case AxCryptItemType.Data:
                            break;

                        case AxCryptItemType.EndOfStream:
                            break;

                        default:
                            break;
                        }
                    }
                    Assert.That(blockFound, Is.True, "We're expecting a VersionHeaderBlock to be found!");
                }
            }
        }
 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 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 TestHmac()
        {
            using (Stream inputStream = FakeRuntimeFileInfo.ExpandableMemoryStream(Resources.helloworld_key_a_txt))
            {
                using (AxCryptReader axCryptReader = new AxCryptStreamReader(inputStream))
                {
                    Assert.Throws <InvalidOperationException>(() =>
                    {
                        if (axCryptReader.Hmac == null)
                        {
                        }
                    }, "The reader is not positioned properly to get the HMAC.");

                    Passphrase      passphrase      = new Passphrase("a");
                    DocumentHeaders documentHeaders = new DocumentHeaders(passphrase.DerivedPassphrase);
                    bool            keyIsOk         = documentHeaders.Load(axCryptReader);
                    Assert.That(keyIsOk, Is.True, "The passphrase provided is correct!");

                    using (Stream encrypedDataStream = axCryptReader.CreateEncryptedDataStream(documentHeaders.HmacSubkey.Key, documentHeaders.CipherTextLength, new ProgressContext()))
                    {
                        Assert.Throws <InvalidOperationException>(() =>
                        {
                            if (axCryptReader.Hmac == null)
                            {
                            }
                        }, "We have not read the encrypted data yet.");

                        Assert.That(axCryptReader.Read(), Is.False, "The reader should be at end of stream now, and Read() should return false.");

                        encrypedDataStream.CopyTo(Stream.Null, 4096);
                        Assert.That(documentHeaders.Hmac, Is.EqualTo(axCryptReader.Hmac), "The HMAC should be correct.");

                        axCryptReader.Dispose();

                        Assert.Throws <ObjectDisposedException>(() =>
                        {
                            DataHmac disposedHmac = axCryptReader.Hmac;
                            Object.Equals(disposedHmac, null);
                        }, "The reader is disposed.");
                    }
                }
            }
        }