public async Task TestAddingSingleV2AsymmetricKeyWrap()
        {
            EncryptionParameters encryptionParameters = new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("allan"));
            IAsymmetricPublicKey publicKey            = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey1);
            await encryptionParameters.AddAsync(new UserPublicKey[] { new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey), });

            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(encryptionParameters, 1000);
            IEnumerable <V2AsymmetricKeyWrapHeaderBlock> wraps = documentHeaders.Headers.HeaderBlocks.OfType <V2AsymmetricKeyWrapHeaderBlock>();

            Assert.That(wraps.Count(), Is.EqualTo(1), "There should be one V2AsymmetricKeyWrapHeaderBlock found.");

            V2AsymmetricKeyWrapHeaderBlock block1 = wraps.First();

            ICryptoFactory cryptoFactory = Resolve.CryptoFactory.Create(encryptionParameters.CryptoId);

            IAsymmetricPrivateKey privateKey1 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey1);

            block1.SetPrivateKey(cryptoFactory, privateKey1);
            ICrypto cryptoFromAsymmetricKey = block1.Crypto(0);

            V2KeyWrapHeaderBlock symmetricKeyWrap = documentHeaders.Headers.HeaderBlocks.OfType <V2KeyWrapHeaderBlock>().First();
            ICrypto cryptoFromSymmetricKey        = cryptoFactory.CreateCrypto(symmetricKeyWrap.MasterKey, symmetricKeyWrap.MasterIV, 0);

            Assert.That(cryptoFromAsymmetricKey.Key, Is.EqualTo(cryptoFromSymmetricKey.Key), "The keys from Asymmetric and Symmetric should be equal.");

            IAsymmetricPrivateKey privateKey2 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey2);

            block1.SetPrivateKey(cryptoFactory, privateKey2);
            ICrypto cryptoFromAsymmetricKey1WithKey2 = block1.Crypto(0);

            Assert.That(cryptoFromAsymmetricKey1WithKey2, Is.Null, "There should be no valid key set and thus no ICrypto instance returned.");
        }
        public void TestHeadersPropertyGetter()
        {
            V2KeyWrapHeaderBlock keyWrap         = new V2KeyWrapHeaderBlock(new V2Aes256CryptoFactory(), new V2DerivedKey(new Passphrase("Key"), 256), 256);
            V2DocumentHeaders    documentHeaders = new V2DocumentHeaders(keyWrap);

            Assert.That(documentHeaders.Headers.HeaderBlocks.Count, Is.EqualTo(0));
        }
        public void TestWriteWithHmac()
        {
            V2DocumentHeaders headers = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("v2passzz")), 20);

            byte[]           output;
            V2HmacCalculator hmacCalculator = new V2HmacCalculator(new SymmetricKey(headers.GetHmacKey()));

            using (V2HmacStream <MemoryStream> hmacStream = V2HmacStream.Create <MemoryStream>(hmacCalculator, new MemoryStream()))
            {
                headers.WriteStartWithHmac(hmacStream);
                headers.WriteEndWithHmac(hmacCalculator, hmacStream, 0, 0);
                hmacStream.Flush();
                output = hmacStream.Chained.ToArray();
            }

            byte[] hmacBytesFromHeaders = new byte[V2Hmac.RequiredLength];
            Array.Copy(output, output.Length - V2Hmac.RequiredLength, hmacBytesFromHeaders, 0, V2Hmac.RequiredLength);
            V2Hmac hmacFromHeaders = new V2Hmac(hmacBytesFromHeaders);

            byte[] dataToHmac = new byte[output.Length - (V2Hmac.RequiredLength + 5)];
            Array.Copy(output, 0, dataToHmac, 0, dataToHmac.Length);

            HMACSHA512 hmac = new HMACSHA512(headers.GetHmacKey());

            hmac.TransformFinalBlock(dataToHmac, 0, dataToHmac.Length);
            V2Hmac hmacFromCalculation = new V2Hmac(hmac.Hash);

            Assert.That(hmacFromHeaders, Is.EqualTo(hmacFromCalculation));
        }
        public void TestUnicodeFileNameShort()
        {
            V2DocumentHeaders headers = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("v2passz")), 10);

            headers.FileName = "My Secret Document.txt";
            Assert.That(headers.FileName, Is.EqualTo("My Secret Document.txt"));
        }
        public void TestCompression()
        {
            V2DocumentHeaders headers = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("v2pass")), 10);

            headers.IsCompressed = true;
            Assert.That(headers.IsCompressed, Is.True);

            headers.IsCompressed = false;
            Assert.That(headers.IsCompressed, Is.False);
        }
        public void TestUnicodeFileNameLong()
        {
            V2DocumentHeaders headers  = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("v2passy")), 10);
            string            longName = "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.";

            Assert.That(longName.Length, Is.GreaterThan(256));

            headers.FileName = longName;
            Assert.That(headers.FileName, Is.EqualTo(longName));
        }
Exemple #7
0
        public static async Task TestGetTwoAsymmetricCryptosFromHeaders(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            Headers headers = new Headers();

            EncryptionParameters parameters = new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("secrets"));
            IAsymmetricPublicKey publicKey1 = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey1);
            IAsymmetricPublicKey publicKey2 = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey2);
            await parameters.AddAsync(new UserPublicKey[] { new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey1), new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey2), });

            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(parameters, 10);

            using (V2HmacStream <MemoryStream> stream = V2HmacStream.Create <MemoryStream>(new V2HmacCalculator(new SymmetricKey(new byte[0])), new MemoryStream()))
            {
                documentHeaders.WriteStartWithHmac(stream);
                stream.Flush();
                stream.Chained.Position = 0;

                using (V2AxCryptReader reader = new V2AxCryptReader(new LookAheadStream(stream.Chained)))
                {
                    while (reader.Read())
                    {
                        if (reader.CurrentItemType == AxCryptItemType.HeaderBlock)
                        {
                            headers.HeaderBlocks.Add(reader.CurrentHeaderBlock);
                        }
                    }

                    SymmetricKey dataEncryptingKey = documentHeaders.Headers.FindHeaderBlock <V2KeyWrapHeaderBlock>().MasterKey;

                    IEnumerable <V2AsymmetricKeyWrapHeaderBlock> readerAsymmetricKeys = headers.HeaderBlocks.OfType <V2AsymmetricKeyWrapHeaderBlock>();
                    Assert.That(readerAsymmetricKeys.Count(), Is.EqualTo(2), "There should be two asymmetric keys in the headers.");

                    V2AsymmetricKeyWrapHeaderBlock asymmetricKey1 = readerAsymmetricKeys.First();
                    IAsymmetricPrivateKey          privateKey1    = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey1);
                    asymmetricKey1.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey1);
                    Assert.That(dataEncryptingKey, Is.EqualTo(asymmetricKey1.Crypto(0).Key), "The asymmetric wrapped key should be the one in the ICrypto instance.");

                    IAsymmetricPrivateKey privateKey2 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey2);
                    asymmetricKey1.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey2);
                    Assert.That(asymmetricKey1.Crypto(0), Is.Null, "The ICrypto instance should be null, since the private key was wrong.");

                    V2AsymmetricKeyWrapHeaderBlock asymmetricKey2 = readerAsymmetricKeys.Last();
                    asymmetricKey2.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey2);
                    Assert.That(dataEncryptingKey, Is.EqualTo(asymmetricKey2.Crypto(0).Key), "The asymmetric wrapped key should be the one in the ICrypto instance.");

                    asymmetricKey2.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey1);
                    Assert.That(asymmetricKey2.Crypto(0), Is.Null, "The ICrypto instance should be null, since the private key was wrong.");
                }
            }
        }
        public void TestFileTimes()
        {
            V2DocumentHeaders headers = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("v2passx")), 12);
            DateTime          now     = DateTime.UtcNow;

            headers.LastAccessTimeUtc = now;
            headers.LastWriteTimeUtc  = now.AddHours(1);
            headers.CreationTimeUtc   = now.AddHours(2);

            Assert.That(headers.LastAccessTimeUtc, Is.EqualTo(now));
            Assert.That(headers.LastWriteTimeUtc, Is.EqualTo(now.AddHours(1)));
            Assert.That(headers.CreationTimeUtc, Is.EqualTo(now.AddHours(2)));
        }
Exemple #9
0
        /// <summary>
        /// Loads an AxCrypt file from the specified reader. After this, the reader is positioned to
        /// read encrypted data.
        /// </summary>
        /// <param name="passphrase">The passphrase.</param>
        /// <param name="cryptoId">The crypto identifier.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="headers">The headers.</param>
        /// <returns>
        /// True if the key was valid, false if it was wrong.
        /// </returns>
        private bool Load(Passphrase passphrase, Guid cryptoId, AxCryptReader reader, Headers headers)
        {
            ResetState();
            if (cryptoId == new V1Aes128CryptoFactory().CryptoId)
            {
                return(PassphraseIsValid);
            }

            _reader       = reader;
            CryptoFactory = Resolve.CryptoFactory.Create(cryptoId);
            V2KeyWrapHeaderBlock keyWrap = headers.FindHeaderBlock <V2KeyWrapHeaderBlock>();
            IDerivedKey          key     = CryptoFactory.RestoreDerivedKey(passphrase, keyWrap.DerivationSalt, keyWrap.DerivationIterations);

            keyWrap.SetDerivedKey(CryptoFactory, key);
            DocumentHeaders   = new V2DocumentHeaders(keyWrap);
            PassphraseIsValid = DocumentHeaders.Load(headers);
            Properties        = EncryptedProperties.Create(this);

            return(PassphraseIsValid);
        }
        public void TestUnknownEncryptedHeader()
        {
            Headers     headers = new Headers();
            IDerivedKey key     = new V2DerivedKey(new Passphrase("A key"), 256);

            headers.HeaderBlocks.Add(new PreambleHeaderBlock());
            headers.HeaderBlocks.Add(new VersionHeaderBlock(new byte[] { 4, 0, 2, 0, 0 }));
            V2KeyWrapHeaderBlock wrapHeader = new V2KeyWrapHeaderBlock(new V2Aes256CryptoFactory(), key, 10);

            headers.HeaderBlocks.Add(wrapHeader);
            headers.HeaderBlocks.Add(new FileInfoEncryptedHeaderBlock(new byte[0]));
            headers.HeaderBlocks.Add(new V2CompressionEncryptedHeaderBlock(new byte[1]));
            headers.HeaderBlocks.Add(new V2UnicodeFileNameInfoEncryptedHeaderBlock(new byte[0]));
            headers.HeaderBlocks.Add(new UnknownEncryptedHeaderBlock(new byte[0]));
            headers.HeaderBlocks.Add(new DataHeaderBlock());

            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(wrapHeader);

            Assert.Throws <InternalErrorException>(() => documentHeaders.Load(headers));
        }
Exemple #11
0
        public bool Load(IAsymmetricPrivateKey privateKey, Guid cryptoId, Headers headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            ResetState();

            CryptoFactory = Resolve.CryptoFactory.Create(cryptoId);

            IEnumerable <V2AsymmetricKeyWrapHeaderBlock> keyWraps = headers.HeaderBlocks.OfType <V2AsymmetricKeyWrapHeaderBlock>();

            foreach (V2AsymmetricKeyWrapHeaderBlock keyWrap in keyWraps)
            {
                keyWrap.SetPrivateKey(CryptoFactory, privateKey);
                if (keyWrap.Crypto(0) == null)
                {
                    continue;
                }

                DocumentHeaders = new V2DocumentHeaders(keyWrap);
                if (!DocumentHeaders.Load(headers))
                {
                    throw new InvalidOperationException("If the master key was decrypted with the private key, the load should not be able to fail.");
                }

                V2AlgorithmVerifierEncryptedHeaderBlock algorithmVerifier = DocumentHeaders.Headers.FindHeaderBlock <V2AlgorithmVerifierEncryptedHeaderBlock>();
                PassphraseIsValid = algorithmVerifier != null && algorithmVerifier.IsVerified;
                if (PassphraseIsValid)
                {
                    Properties = EncryptedProperties.Create(this);
                    return(true);
                }
            }
            return(false);
        }
        public void TestLoadWithInvalidPassphrase()
        {
            Headers headers = new Headers();
            V2Aes256CryptoFactory cryptoFactory = new V2Aes256CryptoFactory();

            headers.HeaderBlocks.Add(new PreambleHeaderBlock());
            headers.HeaderBlocks.Add(new VersionHeaderBlock(new byte[] { 4, 0, 2, 0, 0 }));
            V2KeyWrapHeaderBlock originalKeyWrapBlock = new V2KeyWrapHeaderBlock(cryptoFactory, new V2DerivedKey(new Passphrase("RealKey"), 256), 10);
            V2KeyWrapHeaderBlock headerKeyWrapBlock   = new V2KeyWrapHeaderBlock(originalKeyWrapBlock.GetDataBlockBytes());

            headers.HeaderBlocks.Add(headerKeyWrapBlock);
            headers.HeaderBlocks.Add(new FileInfoEncryptedHeaderBlock(new byte[0]));
            headers.HeaderBlocks.Add(new V2CompressionEncryptedHeaderBlock(new byte[1]));
            headers.HeaderBlocks.Add(new V2UnicodeFileNameInfoEncryptedHeaderBlock(new byte[0]));
            headers.HeaderBlocks.Add(new DataHeaderBlock());

            IDerivedKey key;

            key = cryptoFactory.RestoreDerivedKey(new Passphrase("WrongKey"), headerKeyWrapBlock.DerivationSalt, headerKeyWrapBlock.DerivationIterations);
            headerKeyWrapBlock.SetDerivedKey(cryptoFactory, key);

            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(headerKeyWrapBlock);

            Assert.That(documentHeaders.Load(headers), Is.False);

            key = cryptoFactory.RestoreDerivedKey(new Passphrase("AnotherWrongKey"), headerKeyWrapBlock.DerivationSalt, headerKeyWrapBlock.DerivationIterations);
            headerKeyWrapBlock.SetDerivedKey(cryptoFactory, key);

            documentHeaders = new V2DocumentHeaders(headerKeyWrapBlock);
            Assert.That(documentHeaders.Load(headers), Is.False);

            key = cryptoFactory.RestoreDerivedKey(new Passphrase("RealKey"), headerKeyWrapBlock.DerivationSalt, headerKeyWrapBlock.DerivationIterations);
            headerKeyWrapBlock.SetDerivedKey(cryptoFactory, key);

            documentHeaders = new V2DocumentHeaders(headerKeyWrapBlock);
            Assert.That(documentHeaders.Load(headers), Is.True);
        }
Exemple #13
0
        public static void TestGetCryptoFromHeaders(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            Headers           headers         = new Headers();
            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("passphrase")), 10);

            using (V2HmacStream <MemoryStream> stream = V2HmacStream.Create <MemoryStream>(new V2HmacCalculator(new SymmetricKey(new byte[0])), new MemoryStream()))
            {
                documentHeaders.WriteStartWithHmac(stream);
                stream.Flush();
                stream.Chained.Position = 0;

                using (V2AxCryptReader reader = new V2AxCryptReader(new LookAheadStream(stream.Chained)))
                {
                    while (reader.Read())
                    {
                        if (reader.CurrentItemType == AxCryptItemType.HeaderBlock)
                        {
                            headers.HeaderBlocks.Add(reader.CurrentHeaderBlock);
                        }
                    }
                    SymmetricKey         dataEncryptingKey = documentHeaders.Headers.FindHeaderBlock <V2KeyWrapHeaderBlock>().MasterKey;
                    V2KeyWrapHeaderBlock keyWrap           = headers.FindHeaderBlock <V2KeyWrapHeaderBlock>();

                    IDerivedKey key = new V2Aes256CryptoFactory().RestoreDerivedKey(new Passphrase("passphrase"), keyWrap.DerivationSalt, keyWrap.DerivationIterations);
                    keyWrap.SetDerivedKey(new V2Aes256CryptoFactory(), key);

                    Assert.That(dataEncryptingKey, Is.EqualTo(keyWrap.MasterKey));

                    key = new V2Aes256CryptoFactory().RestoreDerivedKey(new Passphrase("wrong"), keyWrap.DerivationSalt, keyWrap.DerivationIterations);
                    keyWrap.SetDerivedKey(new V2Aes256CryptoFactory(), key);

                    Assert.That(dataEncryptingKey, Is.Not.EqualTo(keyWrap.MasterKey));
                }
            }
        }
Exemple #14
0
 public V2AxCryptDocument(EncryptionParameters encryptionParameters, long keyWrapIterations)
     : this()
 {
     DocumentHeaders = new V2DocumentHeaders(encryptionParameters, keyWrapIterations);
 }
        public void TestWriteStartWithHmacWithNullArgument()
        {
            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("Key")), 10);

            Assert.Throws <ArgumentNullException>(() => documentHeaders.WriteStartWithHmac(null));
        }