예제 #1
0
        public static void DecryptAndOpenFile(IRuntimeFileInfo encryptedDocument, Passphrase passphrase, ProgressContext progress, Action<string, ProgressContext> failure = null)
        {
            string tempPath = Path.GetTempPath();
            string decryptedFileName;
            lastUsedKey = passphrase.DerivedPassphrase;

            if (!TryDecrypt(encryptedDocument, tempPath, lastUsedKey, progress, out decryptedFileName)) {
                failure("Could not open file", progress);
                return;
            }

            string fullPathToDecryptedFile = Path.Combine(tempPath, decryptedFileName);
            IRuntimeFileInfo decryptedFile = OS.Current.FileInfo(fullPathToDecryptedFile);

            NSDictionary userInfo = new NSDictionary(Launcher.TargetFileUserInfoKey, decryptedFile.FullName);
            NSNotification notification = NSNotification.FromName(Launcher.FileDecryptedNotification, new NSObject(), userInfo);
            NSNotificationCenter.DefaultCenter.PostNotification(notification);

            ILauncher launcher = OS.Current.Launch (fullPathToDecryptedFile);
            launcher.Exited += (sender, e) => {
                fileSystemState.CheckActiveFiles(ChangedEventMode.RaiseOnlyOnModified, new ProgressContext());
            };

            fileSystemState.Add (new ActiveFile(encryptedDocument, decryptedFile, lastUsedKey, ActiveFileStatus.AssumedOpenAndDecrypted, launcher));
            //fileSystemState.Save ();
        }
예제 #2
0
        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.");
                        }
                    }
                }
            }
        }
예제 #3
0
        public static void TestPassphraseConstructor()
        {
            Passphrase passphrase = new Passphrase("A Passphrase");
            AesKey derivedKey = passphrase.DerivedPassphrase;
            Assert.That(derivedKey.Length, Is.EqualTo(16), "The default derived key is 128 bits.");

            Assert.Throws<ArgumentNullException>(() =>
            {
                passphrase = new Passphrase(null);
            });
        }
예제 #4
0
 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");
         }
     }
 }
예제 #5
0
        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.");
                }
            }
        }
        /// <summary>
        /// Instantiate a thumb print
        /// </summary>
        /// <param name="passphrase">The passphrase to thumbprint.</param>
        /// <param name="salt">The salt to use.</param>
        public SymmetricKeyThumbprint(Passphrase passphrase, Salt salt, long keyWrapIterations)
        {
            if (passphrase == null)
            {
                throw new ArgumentNullException("passphrase");
            }
            if (salt == null)
            {
                throw new ArgumentNullException("salt");
            }

            ICryptoFactory factory = Resolve.CryptoFactory.Minimum;
            ICrypto        crypto  = factory.CreateCrypto(factory.RestoreDerivedKey(passphrase, salt, CryptoFactory.DerivationIterations).DerivedKey, null, 0);
            KeyWrap        keyWrap = new KeyWrap(salt, keyWrapIterations, KeyWrapMode.Specification);

            byte[] wrap = keyWrap.Wrap(crypto, crypto.Key);

            _bytes = wrap.Reduce(6);
        }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="V1DerivedKey"/> class.
        /// </summary>
        /// <param name="passphrase">The passphrase.</param>
        public V1DerivedKey(Passphrase passphrase)
        {
            if (passphrase == null)
            {
                throw new ArgumentNullException("passphrase");
            }

            HashAlgorithm hashAlgorithm = New <Sha1>();

            byte[] ansiBytes      = Encoding.GetEncoding("Windows-1252").GetBytes(passphrase.Text);
            byte[] ansiBytesExtra = ansiBytes.Append(passphrase.Extra());
            byte[] hash           = hashAlgorithm.ComputeHash(ansiBytesExtra);
            byte[] derivedKey     = new byte[16];
            Array.Copy(hash, derivedKey, derivedKey.Length);

            DerivationSalt       = Salt.Zero;
            DerivationIterations = 0;
            DerivedKey           = new SymmetricKey(derivedKey);
        }
        /// <summary>
        /// Creates an enumeration of all relevant DecryptionParameters from the provided arguments.
        /// </summary>
        /// <param name="passphrases">The passphrases or null.</param>
        /// <param name="privateKeys">The private keys or null.</param>
        /// <param name="cryptoIds">The crypto ids.</param>
        /// <returns></returns>
        public static IEnumerable <DecryptionParameter> CreateAll(IEnumerable <Passphrase> passphrases, IEnumerable <IAsymmetricPrivateKey> privateKeys, IEnumerable <Guid> cryptoIds)
        {
            if (cryptoIds == null)
            {
                throw new ArgumentNullException("cryptoIds");
            }

            List <DecryptionParameter> all = new List <DecryptionParameter>();

            foreach (Passphrase passphrase in passphrases ?? new Passphrase[0])
            {
                foreach (Guid cryptoId in cryptoIds)
                {
                    all.Add(new DecryptionParameter(passphrase, cryptoId));
                    if (cryptoId != new V1Aes128CryptoFactory().CryptoId)
                    {
                        continue;
                    }
                    string filtered = FilterV1Disallowed(passphrase.Text);
                    if (string.CompareOrdinal(filtered, passphrase.Text) == 0)
                    {
                        continue;
                    }
                    all.Add(new DecryptionParameter(Passphrase.Create(filtered), cryptoId));
                }
            }

            foreach (IAsymmetricPrivateKey privateKey in privateKeys ?? new IAsymmetricPrivateKey[0])
            {
                foreach (Guid cryptoId in cryptoIds)
                {
                    if (cryptoId == new V1Aes128CryptoFactory().CryptoId)
                    {
                        continue;
                    }
                    all.Add(new DecryptionParameter(privateKey, cryptoId));
                }
            }

            return(all);
        }
        private bool OpenAxCryptDocument(string fullName, FileOperationEventArgs e)
        {
            e.AxCryptDocument = null;
            try
            {
                IRuntimeFileInfo source = OS.Current.FileInfo(fullName);
                e.OpenFileFullName = source.FullName;
                foreach (AesKey key in _fileSystemState.KnownKeys.Keys)
                {
                    e.AxCryptDocument = AxCryptFile.Document(source, key, new ProgressContext());
                    if (e.AxCryptDocument.PassphraseIsValid)
                    {
                        break;
                    }
                    e.AxCryptDocument.Dispose();
                    e.AxCryptDocument = null;
                }

                Passphrase passphrase;
                while (e.AxCryptDocument == null)
                {
                    OnQueryDecryptionPassphrase(e);
                    if (e.Cancel)
                    {
                        e.Status = FileOperationStatus.Canceled;
                        return false;
                    }
                    passphrase = new Passphrase(e.Passphrase);
                    e.AxCryptDocument = AxCryptFile.Document(source, passphrase.DerivedPassphrase, new ProgressContext());
                    if (!e.AxCryptDocument.PassphraseIsValid)
                    {
                        e.AxCryptDocument.Dispose();
                        e.AxCryptDocument = null;
                        continue;
                    }
                    e.Key = passphrase.DerivedPassphrase;
                    OnKnownKeyAdded(e);
                }
            }
            catch (IOException ioex)
            {
                if (e.AxCryptDocument != null)
                {
                    e.AxCryptDocument.Dispose();
                    e.AxCryptDocument = null;
                }
                FileOperationStatus status = ioex is FileNotFoundException ? FileOperationStatus.FileDoesNotExist : FileOperationStatus.Exception;
                e.Status = status;
                return false;
            }
            return true;
        }
예제 #10
0
 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 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.");
                    }
                }
            }
        }
예제 #12
0
 public LogOnIdentity(EmailAddress userEmail, Passphrase passphrase)
     : this(passphrase)
 {
     UserEmail = userEmail;
 }
예제 #13
0
 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.");
         }
     }
 }
예제 #14
0
 private void enterPassphraseToolStripMenuItem_Click(object sender, EventArgs e)
 {
     string passphraseText = AskForDecryptPassphrase();
     if (passphraseText == null)
     {
         return;
     }
     Passphrase passphrase = new Passphrase(passphraseText);
     persistentState.Current.KnownKeys.Add(passphrase.DerivedPassphrase);
 }
예제 #15
0
        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());
                    });
                }
            }
        }
예제 #16
0
        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()); });
                    }
                }
            }
        }
예제 #17
0
 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");
     }
 }
예제 #18
0
 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());
     }
 }
예제 #19
0
        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.");
            }
        }
예제 #20
0
 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());
         });
     }
 }
예제 #21
0
 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()); });
             }
         }
     }
 }
예제 #22
0
 public IDerivedKey RestoreDerivedKey(Passphrase passphrase, Salt salt, int derivationIterations)
 {
     return(new V2DerivedKey(passphrase, salt, derivationIterations, 128));
 }
예제 #23
0
        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); });
                }
            }
        }
예제 #24
0
 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!");
     }
 }
예제 #25
0
 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.");
         }
     }
 }
예제 #26
0
 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.");
     }
 }
예제 #27
0
 public override int GetHashCode()
 {
     return(Passphrase.GetHashCode() ^ _keyPairs.GetHashCode());
 }
예제 #28
0
 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.");
     }
 }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogOnIdentity"/> class.
 /// </summary>
 /// <param name="passphrase">The passphrase.</param>
 public LogOnIdentity(Passphrase passphrase)
     : this(new UserKeyPair[0], passphrase)
 {
 }
예제 #30
0
 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.");
     }
 }
예제 #31
0
 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()); });
             }
         }
     }
 }
예제 #32
0
 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.");
                 }
             }
         }
     }
 }
        private bool EncryptFilePreparation(string fullName)
        {
            if (String.Compare(Path.GetExtension(fullName), OS.Current.AxCryptExtension, StringComparison.OrdinalIgnoreCase) == 0)
            {
                _eventArgs.Status = FileOperationStatus.FileAlreadyEncrypted;
                return false;
            }
            IRuntimeFileInfo sourceFileInfo = OS.Current.FileInfo(fullName);
            IRuntimeFileInfo destinationFileInfo = OS.Current.FileInfo(AxCryptFile.MakeAxCryptFileName(sourceFileInfo));
            _eventArgs.SaveFileFullName = destinationFileInfo.FullName;
            _eventArgs.OpenFileFullName = fullName;
            if (destinationFileInfo.Exists)
            {
                OnQuerySaveFileAs(_eventArgs);
                if (_eventArgs.Cancel)
                {
                    _eventArgs.Status = FileOperationStatus.Canceled;
                    return false;
                }
            }

            if (_fileSystemState.KnownKeys.DefaultEncryptionKey == null)
            {
                OnQueryEncryptionPassphrase(_eventArgs);
                if (_eventArgs.Cancel)
                {
                    _eventArgs.Status = FileOperationStatus.Canceled;
                    return false;
                }
                Passphrase passphrase = new Passphrase(_eventArgs.Passphrase);
                _eventArgs.Key = passphrase.DerivedPassphrase;
            }
            else
            {
                _eventArgs.Key = _fileSystemState.KnownKeys.DefaultEncryptionKey;
            }

            return true;
        }
예제 #34
0
 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()); });
             }
         }
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EncryptionParameters"/> class.
 /// </summary>
 /// <param name="passphrase">The passphrase.</param>
 public EncryptionParameters(Guid cryptoId, Passphrase passphrase)
     : this(cryptoId)
 {
     _identity = new LogOnIdentity(passphrase);
 }
예제 #36
0
        private void EncryptFile(string file, IThreadWorker worker, ProgressContext progress)
        {
            FileOperationsController operationsController = new FileOperationsController(persistentState.Current, progress);

            operationsController.QuerySaveFileAs += (object sender, FileOperationEventArgs e) =>
                {
                    using (SaveFileDialog sfd = new SaveFileDialog())
                    {
                        sfd.Title = Resources.EncryptFileSaveAsDialogTitle;
                        sfd.AddExtension = true;
                        sfd.ValidateNames = true;
                        sfd.CheckPathExists = true;
                        sfd.DefaultExt = OS.Current.AxCryptExtension;
                        sfd.FileName = e.SaveFileFullName;
                        sfd.Filter = Resources.EncryptedFileDialogFilterPattern.InvariantFormat(OS.Current.AxCryptExtension);
                        sfd.InitialDirectory = Path.GetDirectoryName(e.SaveFileFullName);
                        sfd.ValidateNames = true;
                        DialogResult saveAsResult = sfd.ShowDialog();
                        if (saveAsResult != DialogResult.OK)
                        {
                            e.Cancel = true;
                            return;
                        }
                        e.SaveFileFullName = sfd.FileName;
                    }
                };

            operationsController.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
                {
                    string passphrase = AskForEncryptionPassphrase();
                    if (String.IsNullOrEmpty(passphrase))
                    {
                        e.Cancel = true;
                        return;
                    }
                    e.Passphrase = passphrase;
                    AesKey defaultEncryptionKey = new Passphrase(e.Passphrase).DerivedPassphrase;
                    persistentState.Current.KnownKeys.DefaultEncryptionKey = defaultEncryptionKey;
                };

            operationsController.Completed += (object sender, FileOperationEventArgs e) =>
                {
                    if (e.Status == FileOperationStatus.FileAlreadyEncrypted)
                    {
                        e.Status = FileOperationStatus.Success;
                        return;
                    }
                    if (CheckStatusAndShowMessage(e.Status, e.OpenFileFullName))
                    {
                        IRuntimeFileInfo encryptedInfo = OS.Current.FileInfo(e.SaveFileFullName);
                        IRuntimeFileInfo decryptedInfo = OS.Current.FileInfo(FileOperation.GetTemporaryDestinationName(e.OpenFileFullName));
                        ActiveFile activeFile = new ActiveFile(encryptedInfo, decryptedInfo, e.Key, ActiveFileStatus.NotDecrypted, null);
                        persistentState.Current.Add(activeFile);
                        persistentState.Current.Save();
                    }
                };

            operationsController.EncryptFile(file, worker);
        }
예제 #37
0
 public V2DerivedKey(Passphrase passphrase, int keySize)
     : this(passphrase, new Salt(256), CryptoFactory.DerivationIterations, keySize)
 {
 }
예제 #38
0
 private void encryptionKeyToolStripButton_Click(object sender, EventArgs e)
 {
     if (persistentState.Current.KnownKeys.DefaultEncryptionKey == null)
     {
         string passphrase = AskForEncryptionPassphrase();
         if (String.IsNullOrEmpty(passphrase))
         {
             return;
         }
         AesKey defaultEncryptionKey = new Passphrase(passphrase).DerivedPassphrase;
         persistentState.Current.KnownKeys.DefaultEncryptionKey = defaultEncryptionKey;
     }
     else
     {
         persistentState.Current.KnownKeys.DefaultEncryptionKey = null;
     }
     SetToolButtonsState();
 }
예제 #39
0
 public IDerivedKey CreateDerivedKey(Passphrase passphrase)
 {
     return(new V2DerivedKey(passphrase, 128));
 }
예제 #40
0
 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.");
         }
     }
 }