Example #1
0
        public void AesEncryptionProvider_Encrypt_Decrypt_Image()
        {
            // arrange
            byte[] encryptedData, decryptedData;
            Image  decryptedImage;

            var imageData = File.ReadAllBytes(@"..\..\Test Files\Tulips.jpg");
            var aes       = new AesEncryptionProvider(new TestCryptoKeyProvider("9781908006028",
                                                                                new Guid("F588C946-386F-4A49-A333-64A189D07DD4")));

            // act
            using (var ms = new MemoryStream())
            {
                aes.EncryptToStream(imageData, ms);
                encryptedData = ms.ToArray();
            }

            using (var ms = new MemoryStream())
            {
                aes.DecryptToStream(encryptedData, ms);
                decryptedData = ms.ToArray();
            }

            using (var ms = new MemoryStream(decryptedData))
                decryptedImage = Image.FromStream(ms);

            // assert
            Assert.IsNotNull(decryptedImage);
        }
Example #2
0
        public void CreateKeyTest()
        {
            var key = AesEncryptionProvider.GenerateKey();

            Assert.IsNotNull(key);
            Assert.IsTrue(key.Length > 0);
        }
Example #3
0
        public void TestAes()
        {
            var aes     = new AesEncryptionProvider();
            var key     = aes.Key;
            var aes2    = new AesEncryptionProvider();
            var message = "Unit Testing With Xunit is cool!!";
            var sb      = new StringBuilder(message);

            for (int i = 0; i < 1000; i++)
            {
                sb.Append(i.ToString());
                sb.Append(" : ");
                sb.Append(message);
                sb.AppendLine();
            }
            var Message = sb.ToString();
            var Enc1    = aes.Encrypt(message);
            var Enc2    = aes.Encrypt(Message);
            var Enc3    = aes2.Encrypt(Message);
            var Enc4    = aes.Encrypt(Message);

            Assert.NotEqual(Enc1, Enc2);
            Assert.NotEqual(Enc2, Enc3);
            Assert.Equal(Enc2, Enc4);
            Assert.Equal(message, aes.Decrpty(Enc1));
            Assert.Equal(Message, aes.Decrpty(Enc2));
            Assert.NotEqual(Message, aes.Decrpty(Enc1));
            Assert.Equal(Message, aes2.Decrpty(Enc3));
        }
        public void Encrypt_StaticEncryptIVPrependedInReturn()
        {
            byte[] key = Convert.FromBase64String("ho8LEsB+9jB9ByG9eFEDHr1r6UQjdgOG");
            byte[] iv  = Convert.FromBase64String("TQ36HLyQYwO0bYf5YFXMSw==");

            var result = AesEncryptionProvider.Encrypt("secret value", key, iv);

            byte[] ivFromResult = Convert.FromBase64String(result)[..16];
Example #5
0
        public void TestEncryptionAndDecryption()
        {
            var key       = AesEncryptionProvider.InitializeEncryptionKey();
            var encrypted = AesEncryptionProvider.Encrypt(key, Data);
            var decrypted = AesEncryptionProvider.Decrypt(key, encrypted);

            Assert.AreEqual(Data, decrypted);
        }
Example #6
0
        public static async ValueTask <Stream?> Decrypt(Stream data)
        {
            Stream decrypted = await AesEncryptionProvider.DecryptAsync(data);

            Stream result = SaveFileHandler.RemoveTrailingZeroes(decrypted);

            result.Seek(0, SeekOrigin.Begin);
            return(result);
        }
Example #7
0
        public static async ValueTask <Stream?> Encrypt(Stream data)
        {
            using Stream encrypted = await AesEncryptionProvider.EncryptAsync(data);

            Stream result = SaveFileHandler.PrependMagicToEncrypted(encrypted);

            result.Seek(0, SeekOrigin.Begin);
            return(result);
        }
        public void Should_not_return_original_text_when_decrypting_with_different_keys()
        {
            var inputText = "this is some text";
            var encText   = provider.Encrypt(inputText);

            var result = new AesEncryptionProvider(new PassphraseKeyGenerator("Wrong", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })).Decrypt(encText);

            result.ShouldNotEqual(inputText);
        }
        public CookieBasedSessionsFixture()
        {
            this.fakeEncryptionProvider = A.Fake <IEncryptionProvider>();
            this.fakeHmacProvider       = A.Fake <IHmacProvider>();
            this.fakeObjectSerializer   = new FakeObjectSerializer();
            this.cookieStore            = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, this.fakeObjectSerializer);

            this.aesEncryptionProvider   = new AesEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
            this.defaultHmacProvider     = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
            this.defaultObjectSerializer = new DefaultObjectSerializer();
        }
Example #10
0
        public IAsyncOperation <List <Account> > GetAvailableAccountsAsync()
        {
            return(Task.Run(async() =>
            {
                if (!_isInitialized)
                {
                    await InitializeStorageAsync();
                }
                if (IsRoamingStorageEncrypted && String.IsNullOrEmpty(LocalEncryptionTransferKey))
                {
                    throw new InvalidOperationException("The storage is encrypted but no key is provided.");
                }

                if (!IsRoamingStorageEncrypted)
                {
                    throw new SecurityException("NSA is watching you");
                }

                var accountList = new List <Account>();

                foreach (var file in await _roamingFolder.GetFilesAsync())
                {
                    var stream = await file.OpenAsync(FileAccessMode.Read);
                    var streamreader = new StreamReader(stream.AsStream());
                    var encryptedData = streamreader.ReadToEnd();

                    var data = AesEncryptionProvider.Decrypt(LocalEncryptionTransferKey, encryptedData);
                    JsonObject accountJsonObject;

                    if (!JsonObject.TryParse(data, out accountJsonObject))
                    {
                        continue;
                    }
                    if (accountJsonObject.ContainsKey("AccountName") &&
                        accountJsonObject.ContainsKey("AccountKeyBase32") &&
                        accountJsonObject.ContainsKey("AccountIcon"))
                    {
                        accountList.Add(new Account
                        {
                            AccountName = accountJsonObject.GetNamedString("AccountName"),
                            AccountKeyBase32 = accountJsonObject.GetNamedString("AccountKeyBase32"),
                            AccountIcon = accountJsonObject.GetNamedString("AccountIcon")
                        });
                    }
                }

                return accountList;
            }).AsAsyncOperation());
        }
Example #11
0
        public void AesEncryptionProvider_Encrypt_Decrypt_PlainText()
        {
            // arrange
            const string expected = "This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text. This is some plain text.";
            var          aes      = new AesEncryptionProvider(new TestCryptoKeyProvider("9781908006028",
                                                                                        new Guid("F588C946-386F-4A49-A333-64A189D07DD4")));

            // act
            var encrypted = aes.Encrypt(Encoding.UTF8.GetBytes(expected));
            var decrypted = aes.Decrypt(encrypted);
            var actual    = Encoding.ASCII.GetString(decrypted);

            // assert
            Assert.AreEqual(actual, expected);
        }
        public void Ctor_KeyValid(string key, string expectedB64)
        {
            const int keyLength = 24;

            // arrange
            byte[] expected = Convert.FromBase64String(expectedB64);

            // act
            var provider = new AesEncryptionProvider(key);

            // assert
            Assert.Equal(expected, provider.Key);
            Assert.Equal(keyLength, expected.Length);
            Assert.Equal(keyLength, provider.Key.Length);
        }
        public void Encrypt_StaticEncryptValuesSuccess(string value, string keyB64, string ivB64, string expectedB64)
        {
            // arrange
            var key           = Convert.FromBase64String(keyB64);
            var iv            = Convert.FromBase64String(ivB64);
            var asBytes       = Convert.FromBase64String(expectedB64);
            var expectedBytes = new byte[iv.Length + asBytes.Length];

            Array.ConstrainedCopy(iv, 0, expectedBytes, 0, iv.Length);
            Array.ConstrainedCopy(asBytes, 0, expectedBytes, iv.Length, asBytes.Length);
            var expected = Convert.ToBase64String(expectedBytes);

            // act
            var actual = AesEncryptionProvider.Encrypt(value, key, iv);

            // assert
            Assert.Equal(expected, actual);
            Assert.True(actual.Length > 16);
            Assert.True(IsBase64String(actual));
        }
Example #14
0
        public void EncryptionTests()
        {
            var key = AesEncryptionProvider.GenerateKey();

            Assert.IsNotNull(key);
            Assert.IsTrue(key.Length > 0);

            var          aes       = new AesEncryptionProvider(key);
            const string toEncrypt = "A man, a plan, a canal. Panama.";

            var encrypted = aes.Encrypt(toEncrypt);

            Assert.IsNotNull(encrypted);
            Assert.IsTrue(encrypted.Length > 0);
            Assert.AreNotEqual(toEncrypt, encrypted);

            var decrypted = aes.Decrypt(encrypted);

            Assert.IsNotNull(decrypted);
            Assert.IsTrue(decrypted.Length > 0);
            Assert.AreEqual(toEncrypt, decrypted);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var encryptionProvider  = new AesEncryptionProvider(ApplicationSettings.Database.EncryptionKey);
            var encryptionConverter = new EncryptionConverter(encryptionProvider);

            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                foreach (var property in entityType.GetProperties())
                {
                    if (property.ClrType != typeof(string) || IsDiscriminator(property))
                    {
                        continue;
                    }

                    var attributes = property.PropertyInfo.GetCustomAttributes(typeof(EncryptedAttribute), false);
                    if (attributes.Any())
                    {
                        property.SetValueConverter(encryptionConverter);
                    }
                }
            }
        }
Example #16
0
        public IAsyncOperation <Guid> AddAccountToRoamingStorageAsync(Account account, Guid roamingGuid)
        {
            return(Task.Run(async() =>
            {
                if (!_isInitialized)
                {
                    await InitializeStorageAsync();
                }
                if (IsRoamingStorageEncrypted && String.IsNullOrEmpty(LocalEncryptionTransferKey))
                {
                    throw new InvalidOperationException("The storage is encrypted but no key is provided.");
                }
                if (!IsRoamingStorageEncrypted)
                {
                    throw new SecurityException("NSA is watching you");
                }

                var accountFile = await _accountFolder.CreateFileAsync(roamingGuid + ".blob");
                var accountJson = new JsonObject
                {
                    { "AccountName", JsonValue.CreateStringValue(account.AccountName) },
                    { "AccountKeyBase32", JsonValue.CreateStringValue(account.AccountKeyBase32) },
                    { "AccountIcon", JsonValue.CreateStringValue(account.AccountIcon) }
                };

                // Encrypt the data
                var accountJsonString = accountJson.Stringify();
                var accountJsonStringEncrypted = AesEncryptionProvider.Encrypt(LocalEncryptionTransferKey,
                                                                               accountJsonString);
                var transcation = await accountFile.OpenTransactedWriteAsync();
                var streamwriter = new StreamWriter(transcation.Stream.AsStream());
                streamwriter.Write(accountJsonStringEncrypted);
                // Commit data
                streamwriter.Flush();
                await transcation.CommitAsync();

                return roamingGuid;
            }).AsAsyncOperation());
        }
        private IEncryptionProvider CreateEncryptionProvider()
        {
            IEncryptionProvider encryptionProvider;

            if (_noEncryptionKeyInfo)
            {
                encryptionProvider = new NoEncryptionProvider();
            }
            else
            {
                _interactiveService.WriteLine("Waiting on symmetric key from stdin");
                var input   = _interactiveService.ReadLine();
                var keyInfo = EncryptionKeyInfo.ParseStdInKeyInfo(input);

                switch (keyInfo.Version)
                {
                case EncryptionKeyInfo.VERSION_1_0:
                    var aes = Aes.Create();

                    if (keyInfo.Key != null)
                    {
                        aes.Key = Convert.FromBase64String(keyInfo.Key);
                    }

                    encryptionProvider = new AesEncryptionProvider(aes);
                    break;

                case null:
                    throw new InvalidEncryptionKeyInfoException("Missing required \"Version\" property in the symmetric key");

                default:
                    throw new InvalidEncryptionKeyInfoException($"Unsupported symmetric key {keyInfo.Version}");
                }

                _interactiveService.WriteLine("Encryption provider enabled");
            }

            return(encryptionProvider);
        }
Example #18
0
 public void TestRandomKey()
 {
     AesEncryptionProvider.InitializeEncryptionKey();
 }
Example #19
0
        private static async ValueTask <Stream?> Decrypt(Stream data)
        {
            Stream decrypted = await AesEncryptionProvider.DecryptAsync(data);

            return(SaveFileHandler.RemoveTrailingZeroes(decrypted));
        }
 public AesEncryptionProviderFixture()
 {
     this.provider = new AesEncryptionProvider(new PassphraseKeyGenerator("Passphrase", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }));
 }
Example #21
0
        private static async ValueTask <Stream?> Encrypt(Stream data)
        {
            await using Stream encrypted = await AesEncryptionProvider.EncryptAsync(data);

            return(SaveFileHandler.PrependMagicToEncrypted(encrypted));
        }
Example #22
0
        public void TestEncryption()
        {
            var key = AesEncryptionProvider.InitializeEncryptionKey();

            AesEncryptionProvider.Encrypt(key, Data);
        }