Exemplo n.º 1
0
        private void ExecuteAesEncryptionTest <TContext>(AesKeySize aesKeyType) where TContext : DatabaseContext
        {
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(aesKeyType);
            var        provider          = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV, CipherMode.CBC, PaddingMode.Zeros);
            var        author            = new AuthorEntity("John", "Doe", 42)
            {
                Books = new List <BookEntity>()
                {
                    new BookEntity("Lorem Ipsum", 300),
                    new BookEntity("Dolor sit amet", 390)
                }
            };
            string authorEncryptedFirstName = provider.Encrypt(author.FirstName);
            string authorEncryptedLastName  = provider.Encrypt(author.LastName);
            string firstBookEncryptedName   = provider.Encrypt(author.Books.First().Name);
            string lastBookEncryptedName    = provider.Encrypt(author.Books.Last().Name);

            using (var contextFactory = new DatabaseContextFactory())
            {
                // Save data to an encrypted database context
                using (var dbContext = contextFactory.CreateContext <TContext>(provider))
                {
                    dbContext.Authors.Add(author);
                    dbContext.SaveChanges();
                }

                // Read encrypted data from normal context and compare with encrypted data.
                using (var dbContext = contextFactory.CreateContext <DatabaseContext>())
                {
                    var authorFromDb = dbContext.Authors.Include(x => x.Books).FirstOrDefault();

                    Assert.NotNull(authorFromDb);
                    Assert.Equal(authorEncryptedFirstName, authorFromDb.FirstName);
                    Assert.Equal(authorEncryptedLastName, authorFromDb.LastName);
                    Assert.NotNull(authorFromDb.Books);
                    Assert.NotEmpty(authorFromDb.Books);
                    Assert.Equal(2, authorFromDb.Books.Count);
                    Assert.Equal(firstBookEncryptedName, authorFromDb.Books.First().Name);
                    Assert.Equal(lastBookEncryptedName, authorFromDb.Books.Last().Name);
                }

                // Read decrypted data and compare with original data
                using (var dbContext = contextFactory.CreateContext <TContext>(provider))
                {
                    var authorFromDb = dbContext.Authors.Include(x => x.Books).FirstOrDefault();

                    Assert.NotNull(authorFromDb);
                    Assert.Equal(author.FirstName, authorFromDb.FirstName);
                    Assert.Equal(author.LastName, authorFromDb.LastName);
                    Assert.NotNull(authorFromDb.Books);
                    Assert.NotEmpty(authorFromDb.Books);
                    Assert.Equal(2, authorFromDb.Books.Count);
                    Assert.Equal(author.Books.First().Name, authorFromDb.Books.First().Name);
                    Assert.Equal(author.Books.Last().Name, authorFromDb.Books.Last().Name);
                }
            }
        }
Exemplo n.º 2
0
        private byte[] Encrypt <T>(T plainText)
        {
            var json  = JsonConvert.SerializeObject(plainText);
            var bytes = Encoding.UTF8.GetBytes(json);
            var aes   = new AesProvider(this.sessionService.SessionKey);

            return(aes.Encrypt(bytes));
        }
Exemplo n.º 3
0
            static void Test(AesProvider aesProvider)
            {
                var text         = Guid.NewGuid().ToString();
                var cipherIVPair = aesProvider.Encrypt(text.Bytes());

                var bytes         = AesIVHandler.Default.Combine(cipherIVPair);
                var _cipherIVPair = AesIVHandler.Default.Separate(bytes);

                var source = aesProvider.Decrypt(_cipherIVPair).String();

                Assert.Equal(text, source);
            }
Exemplo n.º 4
0
            static void Test(AesProvider aesProvider)
            {
                var text   = Guid.NewGuid().ToString();
                var cipher = aesProvider.Encrypt(text.Bytes());

                var bytes   = cipher.ToBytes();
                var _cipher = new AesCipher().FromBytes(bytes);

                var source = aesProvider.Decrypt(_cipher).String();

                Assert.Equal(text, source);
            }
Exemplo n.º 5
0
        public void ConfirmTestVectors(string hexKey, string hexIv, string plainText, string expectedCipherText)
        {
            byte[]      key = hexKey.FromHex();
            byte[]      iv  = hexIv.FromHex();
            AesProvider aes = new AesProvider(key, iv, System.Security.Cryptography.PaddingMode.None);

            byte[] plainBytes    = plainText.FromHex();
            byte[] encrptedBytes = aes.Encrypt(plainBytes);

            string cipherText = encrptedBytes.ToHex();

            Assert.Equal(expectedCipherText, cipherText, true);
        }
Exemplo n.º 6
0
        public void GoodKeyAndIVTest(int keyLen, int ivLen)
        {
            AesProvider aes = new AesProvider();
            ShaProvider sha = new ShaProvider();

            byte[] plain    = new byte[] { 0x96, 0x0D, 0x38, 0x4E, 0xE8, 0xE2, 0xE4, 0x7C, 0x32, 0x7D, 0xDB, 0x28, 0x50, 0x15, 0x23, 0x5E, 0xC1, 0xD8, 0x7A, 0x05, 0x19, 0x62, 0x63, 0x23, 0x1F, 0x27, 0x9C, 0x3B, 0xA9, 0x0E, 0x81, 0xB6 };
            string plainHex = plain.ToHex();

            byte[] encrypted = aes.Encrypt(plain);
            byte[] decrypted = aes.Decrypt(encrypted);

            Assert.Equal(plainHex, decrypted.ToHex());
        }
Exemplo n.º 7
0
        public void EncryptDecryptByteArrayTest(AesKeySize keySize)
        {
            byte[]     input             = DataHelper.RandomBytes(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            byte[] encryptedData = provider.Encrypt(input, b => b, StandardConverters.StreamToBytes);
            Assert.NotNull(encryptedData);

            byte[] decryptedData = provider.Decrypt(encryptedData, b => b, StandardConverters.StreamToBytes);
            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
Exemplo n.º 8
0
        public void Aes_Encryption_Decryption_Success(string testPhrase, int keySize)
        {
            // ARRANGE
            var aesCrypto = new AesProvider();

            var key = aesCrypto.GenerateKey(keySize);
            var IV  = aesCrypto.GenerateInitializationVector();

            // ACT
            var encrypted = aesCrypto.Encrypt(testPhrase, key, IV, CipherMode.CBC);
            var decrypted = aesCrypto.Decrypt(encrypted, key, IV, CipherMode.CBC);

            // ASSERT
            Assert.AreEqual(testPhrase, decrypted);
        }
Exemplo n.º 9
0
        public async Task RefreshSessionKey()
        {
            var aes    = new AesProvider(this.SessionKey);
            var secret = aes.Encrypt(this.clientRandom);

            string url = $"api/sessions/{this.SessionId}/refresh";

            var result = await this.http.PostAsync(Environment.ApplicationUrl + url, new StringContent(JsonConvert.SerializeObject(secret), Encoding.UTF8, "application/json"));

            var obj = await result.Content.ReadAsStringAsync();

            var refreshedKey = JsonConvert.DeserializeObject <byte[]>(obj);

            this.SessionKey = aes.Decrypt(refreshedKey);
        }
        public void EncryptDecryptStringTest(AesKeySize keySize)
        {
            string     input             = StringHelper.RandomString(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            string encryptedData = provider.Encrypt(input);

            Assert.NotNull(encryptedData);

            string decryptedData = provider.Decrypt(encryptedData);

            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
Exemplo n.º 11
0
        public void EncryptDecryptTest(string hexKey, string hexIv, string plainText)
        {
            byte[] key        = hexKey.FromHex();
            byte[] iv         = hexIv.FromHex();
            byte[] plainBytes = plainText.FromHex();

            AesProvider aes = new AesProvider(key, iv);

            byte[] encrptedBytes  = aes.Encrypt(plainBytes);
            byte[] decryptedBytes = aes.Decrypt(encrptedBytes);

            string encryptedHex = encrptedBytes.ToHex();
            string decryptedHex = decryptedBytes.ToHex();

            Assert.Equal(plainText, decryptedHex, true);
        }
Exemplo n.º 12
0
        private HttpContent CreateHttpContent <T>(T obj, bool encrypt)
        {
            var jsonRequest = JsonConvert.SerializeObject(obj);

            if (encrypt)
            {
                var byteMessage = Encoding.UTF8.GetBytes(jsonRequest);
                var aes         = new AesProvider(this.sessionService.SessionKey);
                var encrypted   = aes.Encrypt(byteMessage);
                return(new ByteArrayContent(encrypted));
            }
            else
            {
                return(new StringContent(jsonRequest, Encoding.UTF8, "application/json"));
            }
        }
Exemplo n.º 13
0
        public void EncryptDecryptStringTest(AesKeySize keySize)
        {
            string     input             = DataHelper.RandomString(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            string encryptedData = provider.Encrypt(input, Encoding.UTF8.GetBytes, StandardConverters.StreamToBase64String);

            Assert.NotNull(encryptedData);

            string decryptedData = provider.Decrypt(encryptedData, Convert.FromBase64String, StandardConverters.StreamToString);

            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
Exemplo n.º 14
0
        /// <summary>
        /// 测试操作的可用性
        /// </summary>
        /// <remarks>
        /// 测试完成后,需删除方法内部所有内容, 并返回false
        /// </remarks>
        /// <returns>是否正在测试,true: 正在测试, false: 不在测试</returns>
        private static bool AesTest()
        {
            Rsa();
            return(true);

            var text       = "Hello World!";
            var encryptKey = Guid.NewGuid().ToString("N"); //"d9b46c3513654f66bea91f7e81009ce9";
            var key        = encryptKey.ToBytes();
            //key = Encoding.UTF8.GetBytes(encryptKey);
            var iv = new byte[16];

            var enc = AesProvider.Encrypt(text, key, iv);
            var dec = AesProvider.Decrypt(enc, key, iv);

            Console.WriteLine($"加密前:{text}");
            Console.WriteLine($"加密后:{enc}");
            Console.WriteLine($"   key:{BitConverter.ToString(key).Replace("-", "")}");
            Console.WriteLine($"    iv:{BitConverter.ToString(iv).Replace("-", "")}");

            return(true);
        }
Exemplo n.º 15
0
        public void InvalidPaddingMode(string hexKey, string hexIv, string plainText, System.Security.Cryptography.PaddingMode paddingMode)
        {
            byte[] key        = hexKey.FromHex();
            byte[] iv         = hexIv.FromHex();
            byte[] plainBytes = plainText.FromHex();
            byte[] encrptedBytes;

            //None of the cipher texts are an even multiple of the block size, so using no padding causes .NET to throw an error
            AesProvider aes = new AesProvider(key, iv, paddingMode);
            Exception   ex  = Assert.Throws <System.Security.Cryptography.CryptographicException>(() => encrptedBytes = aes.Encrypt(plainBytes));
        }