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 bool Load(Headers headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            headers.EnsureFileFormatVersion(4, 4);

            if (!IsMasterKeyKnown(headers))
            {
                return(false);
            }

            HmacCalculator = new V2HmacCalculator(new SymmetricKey(GetHmacKey()));
            using (Stream hmacStream = V2HmacStream.Create(HmacCalculator))
            {
                AxCrypt1Guid.Write(hmacStream);
                foreach (HeaderBlock header in headers.HeaderBlocks)
                {
                    header.Write(hmacStream);
                }
            }

            SetDataEncryptingCryptoForEncryptedHeaderBlocks(headers.HeaderBlocks);

            _headers = headers;
            return(true);
        }
示例#3
0
 public static void TestCapabilities()
 {
     using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(new byte[512]))))
     {
         Assert.That(stream.CanRead, Is.False);
         Assert.That(stream.CanSeek, Is.False);
         Assert.That(stream.CanWrite, Is.True);
     }
 }
示例#4
0
 public static void TestDispose()
 {
     using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(new byte[512]))))
     {
         stream.Dispose();
         Assert.DoesNotThrow(() => stream.Dispose());
         Assert.Throws <ObjectDisposedException>(() => stream.Write(new byte[1], 0, 1));
     }
 }
示例#5
0
        private Stream CreateEncryptedDataStream()
        {
            if (_reader.CurrentItemType != AxCryptItemType.Data)
            {
                throw new InvalidOperationException("An attempt was made to create an encrypted data stream when the reader is not positioned at the data.");
            }

            _reader.SetStartOfData();
            return(V2AxCryptDataStream.Create(_reader, V2HmacStream.Create(DocumentHeaders.HmacCalculator)));
        }
示例#6
0
 public static void TestPosition()
 {
     using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(new byte[512]))))
     {
         Assert.That(stream.Position, Is.EqualTo(0));
         stream.Write(new byte[1], 0, 1);
         Assert.That(stream.Position, Is.EqualTo(1));
         Assert.That(stream.Length, Is.EqualTo(1));
     }
 }
示例#7
0
 public static void TestNotSupportedMethods()
 {
     using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(new byte[512]))))
     {
         Assert.Throws <NotSupportedException>(() => stream.Read(new byte[1], 0, 1));
         Assert.Throws <NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin));
         Assert.Throws <NotSupportedException>(() => stream.SetLength(0));
         Assert.Throws <NotSupportedException>(() => stream.Position = 0);
     }
 }
示例#8
0
        /// <summary>
        /// Encrypt a stream with a given set of headers and write to an output stream. The caller is responsible for consistency and completeness
        /// of the headers. Headers that are not known until encryption and compression are added here.
        /// </summary>
        /// <param name="outputDocumentHeaders"></param>
        /// <param name="inputStream"></param>
        /// <param name="outputStream"></param>
        public void EncryptTo(Stream inputStream, Stream outputStream, AxCryptOptions options)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }
            if (outputStream == null)
            {
                throw new ArgumentNullException("outputStream");
            }
            if (options.HasMask(AxCryptOptions.EncryptWithCompression) && options.HasMask(AxCryptOptions.EncryptWithoutCompression))
            {
                throw new ArgumentException("Invalid options, cannot specify both with and without compression.");
            }
            if (!options.HasMask(AxCryptOptions.EncryptWithCompression) && !options.HasMask(AxCryptOptions.EncryptWithoutCompression))
            {
                throw new ArgumentException("Invalid options, must specify either with or without compression.");
            }

            DocumentHeaders.IsCompressed = options.HasMask(AxCryptOptions.EncryptWithCompression);
            V2HmacCalculator      hmacCalculator   = new V2HmacCalculator(new SymmetricKey(DocumentHeaders.GetHmacKey()));
            V2HmacStream <Stream> outputHmacStream = V2HmacStream.Create(hmacCalculator, outputStream);

            CryptoStreamBase encryptingStream = New <CryptoStreamBase>().Initialize(V2AxCryptDataStream.Create(outputHmacStream), DocumentHeaders.DataCrypto().EncryptingTransform(), CryptoStreamMode.Write);

            DocumentHeaders.WriteStartWithHmac(outputHmacStream);
            if (DocumentHeaders.IsCompressed)
            {
                using (ZOutputStream deflatingStream = new ZOutputStream(encryptingStream, -1))
                {
                    deflatingStream.FlushMode = JZlib.Z_SYNC_FLUSH;
                    inputStream.CopyTo(deflatingStream);
                    deflatingStream.FlushMode = JZlib.Z_FINISH;
                    deflatingStream.Finish();

                    _plaintextLength           = deflatingStream.TotalIn;
                    _compressedPlaintextLength = deflatingStream.TotalOut;
                    encryptingStream.FinalFlush();
                    DocumentHeaders.WriteEndWithHmac(hmacCalculator, outputHmacStream, _plaintextLength, _compressedPlaintextLength);
                }
            }
            else
            {
                try
                {
                    _compressedPlaintextLength = _plaintextLength = StreamExtensions.CopyTo(inputStream, encryptingStream);
                    encryptingStream.FinalFlush();
                    DocumentHeaders.WriteEndWithHmac(hmacCalculator, outputHmacStream, _plaintextLength, _compressedPlaintextLength);
                }
                finally
                {
                    encryptingStream.Dispose();
                }
            }
        }
示例#9
0
        public static void TestConstructorNullArgument()
        {
            V2HmacCalculator nullCalculator = null;
            Stream           nullStream     = null;
            Stream           stream         = null;

            Assert.Throws <ArgumentNullException>(() => stream = V2HmacStream.Create(nullCalculator));
            Assert.That(stream, Is.Null);

            Assert.Throws <ArgumentNullException>(() => stream = V2HmacStream.Create(new V2HmacCalculator(SymmetricKey.Zero128), nullStream));
            Assert.That(stream, Is.Null);
        }
示例#10
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 Trailers(AxCryptReaderBase axCryptReader)
 {
     _headers.Trailers(axCryptReader);
     using (Stream hmacStream = V2HmacStream.Create(HmacCalculator))
     {
         foreach (HeaderBlock header in _headers.TrailerBlocks)
         {
             if (header.HeaderBlockType == HeaderBlockType.V2Hmac)
             {
                 continue;
             }
             header.Write(hmacStream);
         }
     }
 }
示例#12
0
        public static void Rfc4231TestCase6()
        {
            byte[] key          = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa".FromHex();
            byte[] data         = "54657374205573696e67204c61726765 72205468616e20426c6f636b2d53697a 65204b6579202d2048617368204b6579 204669727374".FromHex();
            byte[] hmac_sha_512 = "80b24263c7c1a3ebb71493c1dd7be8b4 9b46d1f41b4aeec1121b013783f8f352 6b56d037e05f2598bd0fd2215d6a1e52 95e64f73f63f0aec8b915a985d786598".FromHex();

            byte[] result;
            using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(key))))
            {
                stream.Write(data, 0, data.Length);
                result = stream.Hmac.GetBytes();
            }

            Assert.That(result, Is.EquivalentTo(hmac_sha_512));
        }
示例#13
0
        public static void Rfc4231TestCase4()
        {
            byte[] key          = "0102030405060708090a0b0c0d0e0f10 111213141516171819".FromHex();
            byte[] data         = "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd cdcd".FromHex();
            byte[] hmac_sha_512 = "b0ba465637458c6990e5a8c5f61d4af7 e576d97ff94b872de76f8050361ee3db a91ca5c11aa25eb4d679275cc5788063 a5f19741120c4f2de2adebeb10a298dd".FromHex();

            byte[] result;
            using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(key))))
            {
                stream.Write(data, 0, data.Length);
                result = stream.Hmac.GetBytes();
            }

            Assert.That(result, Is.EquivalentTo(hmac_sha_512));
        }
示例#14
0
        public static void Rfc4231TestCase3()
        {
            byte[] key          = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".FromHex();
            byte[] data         = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd".FromHex();
            byte[] hmac_sha_512 = "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb".FromHex();

            byte[] result;
            using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(key))))
            {
                stream.Write(data, 0, data.Length);
                result = stream.Hmac.GetBytes();
            }

            Assert.That(result, Is.EquivalentTo(hmac_sha_512));
        }
示例#15
0
        public static void Rfc4231TestCase2()
        {
            byte[] key          = "4a656665".FromHex();
            byte[] data         = "7768617420646f2079612077616e7420666f72206e6f7468696e673f".FromHex();
            byte[] hmac_sha_512 = "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737".FromHex();

            byte[] result;
            using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(key))))
            {
                stream.Write(data, 0, data.Length);
                result = stream.Hmac.GetBytes();
            }

            Assert.That(result, Is.EquivalentTo(hmac_sha_512));
        }
示例#16
0
        public static void Rfc4231TestCase1()
        {
            byte[] key          = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".FromHex();
            byte[] data         = "4869205468657265".FromHex();
            byte[] hmac_sha_512 = "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854".FromHex();

            byte[] result;
            using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(key))))
            {
                stream.Write(data, 0, data.Length);
                result = stream.Hmac.GetBytes();
            }

            Assert.That(result, Is.EquivalentTo(hmac_sha_512));
        }
示例#17
0
        public static void Rfc4231TestCase7()
        {
            byte[] key          = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa".FromHex();
            byte[] data         = "54686973206973206120746573742075 73696e672061206c6172676572207468 616e20626c6f636b2d73697a65206b65 7920616e642061206c61726765722074 68616e20626c6f636b2d73697a652064 6174612e20546865206b6579206e6565 647320746f2062652068617368656420 6265666f7265206265696e6720757365 642062792074686520484d414320616c 676f726974686d2e".FromHex();
            byte[] hmac_sha_512 = "e37b6a775dc87dbaa4dfa9f96e5e3ffd debd71f8867289865df5a32d20cdc944 b6022cac3c4982b10d5eeb55c3e4de15 134676fb6de0446065c97440fa8c6a58".FromHex();

            byte[] result;
            using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(key))))
            {
                stream.Write(data, 0, data.Length);
                result = stream.Hmac.GetBytes();
            }

            Assert.That(result, Is.EquivalentTo(hmac_sha_512));
        }
示例#18
0
        public static void Rfc4231TestCase5()
        {
            byte[] key          = "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c 0c0c0c0c".FromHex();
            byte[] data         = "546573742057697468205472756e6361 74696f6e".FromHex();
            byte[] hmac_sha_512 = "415fad6271580a531d4179bc891d87a6".FromHex();

            byte[] result;
            using (V2HmacStream <Stream> stream = V2HmacStream.Create(new V2HmacCalculator(new SymmetricKey(key))))
            {
                stream.Write(data, 0, data.Length);
                result = new byte[16];
                Array.Copy(stream.Hmac.GetBytes(), 0, result, 0, 16);
            }

            Assert.That(result, Is.EquivalentTo(hmac_sha_512));
        }
示例#19
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));
                }
            }
        }