예제 #1
0
        public void encrypt()
        {
            Assert.Throws <ArgumentNullException>(() => SecurityExtensions.Encrypt(null, Enumerable.Empty <byte>().ToArray()));
            Assert.Throws <ArgumentNullException>(() => Aes.Create().Encrypt((byte[])null));
            Assert.Throws <ArgumentNullException>(() => SecurityExtensions.Encrypt(null, Stream.Null));
            Assert.Throws <ArgumentNullException>(() => Aes.Create().Encrypt(null, false));

            var bytes     = Guid.NewGuid().ToByteArray();
            var algorithm = Aes.Create();

            var encrypted = algorithm.Encrypt(bytes);

            Assert.False(encrypted.SequenceEqual(bytes));
            using (var encryptor = Aes.Create())
            {
                encryptor.Key = algorithm.Key;
                encryptor.IV  = algorithm.IV;
                Assert.True(encryptor.Encrypt(bytes).SequenceEqual(encrypted));
            }
            using (var encryptor = Aes.Create())
            {
                encryptor.Key = algorithm.Key;
                Assert.False(encryptor.Encrypt(bytes).SequenceEqual(encrypted));
            }
            using (var encryptor = Aes.Create())
            {
                encryptor.IV = algorithm.IV;
                Assert.False(encryptor.Encrypt(bytes).SequenceEqual(encrypted));
            }
            using (var encryptor = Aes.Create())
            {
                Assert.False(encryptor.Encrypt(bytes).SequenceEqual(encrypted));
            }

            using (var stream = new MemoryStream(bytes))
            {
                Assert.True(algorithm.Encrypt(stream).SequenceEqual(encrypted));
                Assert.Equal(-1, stream.ReadByte());
            }
            using (var stream = new MemoryStream(bytes))
            {
                Assert.True(algorithm.Encrypt(stream, true).SequenceEqual(encrypted));
                Assert.Throws <ObjectDisposedException>(() => stream.ReadByte());
            }
            using (var stream = new MemoryStream(bytes))
            {
                Assert.True(algorithm.Encrypt(stream).SequenceEqual(encrypted));
                Assert.Equal(-1, stream.ReadByte());
            }
            using (var encryptor = Aes.Create())
            {
                encryptor.Key = algorithm.Key;
                Assert.False(encryptor.Encrypt(new MemoryStream(bytes), true).SequenceEqual(encrypted));
            }
            using (var encryptor = Aes.Create())
            {
                encryptor.IV = algorithm.IV;
                Assert.False(encryptor.Encrypt(new MemoryStream(bytes), true).SequenceEqual(encrypted));
            }
            using (var encryptor = Aes.Create())
            {
                Assert.False(encryptor.Encrypt(new MemoryStream(bytes), true).SequenceEqual(encrypted));
            }

            algorithm.Clear();
        }