static void Main() { var options = new DbContextOptionsBuilder <DatabaseContext>() .UseInMemoryDatabase(databaseName: "MyInMemoryDatabase") .Options; // AES key randomly generated at each run. byte[] encryptionKey = AesProvider.GenerateKey(AesKeySize.AES256Bits).Key; var encryptionProvider = new AesProvider(encryptionKey); using var context = new DatabaseContext(options, encryptionProvider); var user = new UserEntity { FirstName = "John", LastName = "Doe", Email = "*****@*****.**", Password = BuildPassword(), }; context.Users.Add(user); context.SaveChanges(); Console.WriteLine($"Users count: {context.Users.Count()}"); user = context.Users.First(); Console.WriteLine($"User: {user.FirstName} {user.LastName} - {user.Email} ({user.Password.Length})"); }
private void HandleCcmAuthentication(int length) { if (ccmLengthOfAuthenticationField.Value == 0 && aesOperationLength == 0) { // no authentication header is calculated return; } var adataPresent = false; if (ccmCbcMacAesProvider == null) { // this is a first ccm dma transfer; // if it uses adata there will be a second one; // CCM mode uses CBC-MAC for authentication; ccmCbcMacAesProvider = AesProvider.GetCbcMacProvider(GetSelectedKey()); ccmCbcMacAesProvider.EncryptBlockInSitu(GenerateB0Block()); var adataBlock = GenerateFirstAdataBlock(); if (adataBlock != null) { adataPresent = true; // there is adata ProcessDataInMemory(dmaInputAddress.Value, null, length, ccmCbcMacAesProvider.EncryptBlockInSitu, adataBlock); if (aesOperationLength > 0) { // message data will be sent in a second dma transfer return; } } } if (!adataPresent) { if (aesOperationLength != length) { this.Log(LogLevel.Warning, "Message data detected, but aes operation length ({0}) is different than this transfer length ({1}). Aborting the transfer.", aesOperationLength, length); ccmCbcMacAesProvider.Dispose(); ccmCbcMacAesProvider = null; return; } if (direction.Value == Direction.Decryption) { // we must first decrypt the message data before calculating the tag return; } // this is the second transfer with message data ProcessDataInMemory(dmaInputAddress.Value, null, length, ccmCbcMacAesProvider.EncryptBlockInSitu); } // calculate tag GenerateS0Block().XorWith(ccmCbcMacAesProvider.LastBlock).CopyTo(tag); ccmCbcMacAesProvider.Dispose(); ccmCbcMacAesProvider = null; }
public async Task MigrateEncryptedToOriginalTest() { var aesKeys = AesProvider.GenerateKey(AesKeySize.AES256Bits); var sourceProvider = new AesProvider(aesKeys.Key); var provider = new MigrationEncryptionProvider(sourceProvider, null); await Execute(provider); }
public void GenerateAesKeyTest(AesKeySize keySize) { AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize); Assert.NotNull(encryptionKeyInfo.Key); Assert.NotNull(encryptionKeyInfo.IV); Assert.Equal((int)keySize / 8, encryptionKeyInfo.Key.Length); }
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)); }
public async Task MigrateOriginalToEncryptedTest() { var aesKeys = AesProvider.GenerateKey(AesKeySize.AES256Bits); var destinationProvider = new AesProvider(aesKeys.Key); var provider = new MigrationEncryptionProvider(null, destinationProvider); await Execute(provider); }
public void EncryptDecryptBufferTest() { string STRING_EncryptionKey = "thisIsMyP@55w0rd"; byte[] vBYTE_ToEncrypt = Encoding.UTF8.GetBytes("0123456789qwertyuiopasdfghjklzxcvbnm");//new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }; byte[] vBYTE_EncryptedBuffer = AesProvider.AES_CBC_Encryption_Rand_IV(vBYTE_ToEncrypt, STRING_EncryptionKey); byte[] vBYTE_DecryptedBuffer = AesProvider.AES_CBC_Decryption_Rand_IV(vBYTE_EncryptedBuffer, STRING_EncryptionKey); Assert.IsTrue(vBYTE_ToEncrypt.SequenceEqual(vBYTE_DecryptedBuffer)); }
public void EncryptDecryptStringTest() { string STRING_EncryptionKey = "thisIsMyP@55w0rd"; string STRING_ToEncrypt = "0123456789qwertyuiopasdfghjklzxcvbnm"; string STRING_EncryptedString = AesProvider.AES_CBC_Encryption_Rand_IV(STRING_ToEncrypt, STRING_EncryptionKey); string STRING_DecryptedString = AesProvider.AES_CBC_Decryption_Rand_IV(STRING_EncryptedString, STRING_EncryptionKey); Assert.IsTrue(STRING_DecryptedString.Equals(STRING_ToEncrypt)); }
public void Run(string[] args) { var conArgs = new ConArgs(args, "-"); var aesKey = conArgs[1] == "hex" ? AesKey.HexString : AesKey.Base64String; var aes = new AesProvider(); Console.WriteLine($"New {aesKey.ToString()}:\t{aes.ExportKey(aesKey)}"); }
public EncryptionProviderLoaderAes() { //this configuration is just for test proposous. In real cases we need to load the keys from a secure location by environment maybe var key = AesProvider.GenerateKey(AesKeySize.AES256Bits); var encryptionKey = key.Key; var encryptionIv = key.IV; _aesProvider = new AesProvider(encryptionKey, encryptionIv); }
public async Task MigrateV1ToV2Test() { var aesKeys = AesProvider.GenerateKey(AesKeySize.AES256Bits); var sourceProvider = new AesProvider(aesKeys.Key, aesKeys.IV); var destinationProvider = new AesProvider(aesKeys.Key); var provider = new MigrationEncryptionProvider(sourceProvider, destinationProvider); await Execute(provider); }
public void OnExecute(CommandLineApplication app, IConsole console) { if (string.IsNullOrEmpty(DatabaseConfigurationFile)) { DatabaseConfigurationFile = Application.DefaultDatabaseConfigurationFile; } var dbConfiguration = new DatabaseConfiguration() { EncryptionKey = Convert.ToBase64String(AesProvider.GenerateKey(AesKeySize.AES256Bits).Key) }; Console.WriteLine("Select one of the available providers:"); ConsoleHelper.DisplayEnum <DatabaseProvider>(); Console.Write("Database provider: "); dbConfiguration.Provider = ConsoleHelper.ReadEnum <DatabaseProvider>(); if (dbConfiguration.Provider == DatabaseProvider.MySql) { Console.Write("Port (3306): "); dbConfiguration.Port = ConsoleHelper.ReadIntegerOrDefault(3306); } Console.Write("Host (localhost): "); dbConfiguration.Host = ConsoleHelper.ReadStringOrDefault("localhost"); Console.Write("Username (root): "); dbConfiguration.Username = ConsoleHelper.ReadStringOrDefault("root"); Console.Write("Password: "******"Database name (rhisis): "); dbConfiguration.Database = ConsoleHelper.ReadStringOrDefault("rhisis"); Console.WriteLine("--------------------------------"); Console.WriteLine("Configuration:"); Console.WriteLine($"Database Provider: {dbConfiguration.Provider.ToString()}"); Console.WriteLine($"Host: {dbConfiguration.Host}"); Console.WriteLine($"Username: {dbConfiguration.Username}"); Console.WriteLine($"Database name: {dbConfiguration.Database}"); if (dbConfiguration.Provider == DatabaseProvider.MySql) { Console.WriteLine($"Port: {dbConfiguration.Port}"); } Console.WriteLine("--------------------------------"); bool response = ConsoleHelper.AskConfirmation("Save this configuration?"); if (response) { ConfigurationHelper.Save(DatabaseConfigurationFile, dbConfiguration); Console.WriteLine($"Database configuration saved in '{DatabaseConfigurationFile}'."); } }
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); } } }
private T Decrypt <T>(byte[] cipherText) { var aes = new AesProvider(this.sessionService.SessionKey); var decrypted = aes.Decrypt(cipherText); var json = Encoding.UTF8.GetString(decrypted); var result = JsonConvert.DeserializeObject <T>(json); return(result); }
public void BadKeyOrIVTest(int keyLen, int ivLen) { byte[] key = new byte[keyLen]; byte[] iv = new byte[ivLen]; AesProvider aes; Exception ex = Assert.Throws <ArgumentException>(() => aes = new AesProvider(key, iv)); Assert.Contains(" must be ", ex.Message); }
private Block GenerateS0Block() { var resultBlock = Block.WithCopiedBytes(inputVector); using (var aesEcb = new AesProvider(CipherMode.ECB, PaddingMode.None, GetSelectedKey())) { aesEcb.EncryptBlockInSitu(resultBlock); } return(resultBlock); }
private void HandleCbc(int length) { using (var aes = AesProvider.GetCbcProvider(GetSelectedKey(), inputVector)) { var processor = direction.Value == Direction.Encryption ? (Action <Block>)aes.EncryptBlockInSitu : aes.DecryptBlockInSitu; ProcessDataInMemory(dmaInputAddress.Value, dmaOutputAddress.Value, length, processor); } }
public async Task InvokeAsync(HttpContext httpContext) { if (!httpContext.Request.Headers.ContainsKey(requestKey) || !httpContext.Request.Headers.ContainsKey(clientSecretHeader)) { await WriteToReponseAsync(); return; } var requestKeyHeader = httpContext.Request.Headers[requestKey].ToString(); string clientSecret = httpContext.Request.Headers[clientSecretHeader].ToString(); if (string.IsNullOrEmpty(requestKeyHeader) || string.IsNullOrEmpty(clientSecret)) { await WriteToReponseAsync(); return; } //اگر کلید در کش موجود بود یعنی کاربر از کلید تکراری استفاده کرده است if (_cache.GetString(requestKeyHeader) != null) { await WriteToReponseAsync(); return; } var dateTimeNow = DateTime.UtcNow; var expireTimeFrom = dateTimeNow.AddMinutes(-1).Ticks; var expireTimeTo = dateTimeNow.Ticks; string decryptedRequestHeader = AesProvider.Decrypt(requestKeyHeader, clientSecret); var requestKeyData = System.Text.Json.JsonSerializer.Deserialize <TOTPRequestDto>(decryptedRequestHeader); if (requestKeyData.DateTimeUtcTicks >= expireTimeFrom && requestKeyData.DateTimeUtcTicks <= expireTimeTo) { //ذخیره کلید درخواست در کش برای جلوگیری از استفاده مجدد از کلید await _cache.SetAsync(requestKeyHeader, Encoding.UTF8.GetBytes("KeyExist"), new DistributedCacheEntryOptions { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(2) }); await _next(httpContext); } else { await WriteToReponseAsync(); return; } async Task WriteToReponseAsync() { httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden; await httpContext.Response.WriteAsync("Forbidden: You don't have permission to call this api"); } }
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)); }
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); }
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); }
private void HandleEcb(int length) { var encryptedNonceCounterBlock = Block.OfSize(AesBlockSizeInBytes); using (var aes = AesProvider.GetEcbProvider(GetSelectedKey())) { var processor = direction.Value == Direction.Encryption ? (Action <Block>)aes.EncryptBlockInSitu : aes.DecryptBlockInSitu; ProcessDataInMemory(dmaInputAddress.Value, dmaOutputAddress.Value, length, processor); } }
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()); }
public UserDbContext(DbContextOptions options, IConfiguration configuration) : base(options) { // This shouldn't be necessary, but why not. var bytes = new Rfc2898DeriveBytes( configuration["ClientSecret"], ToByteArray(configuration["ClientId"])); // No two tokens will be the same, the IV isn't crucial here. provider = new AesProvider(bytes.GetBytes(32), bytes.GetBytes(16)); Database.EnsureCreated(); }
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); }
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); }
private void HandleCbcMac(int length) { if (inputVector.Any(x => x != 0)) { this.Log(LogLevel.Warning, "Input vector in CBC-MAC mode should be set to all zeros!. Ignoring this transfer"); return; } using (var aes = AesProvider.GetCbcMacProvider(GetSelectedKey())) { ProcessDataInMemory(dmaInputAddress.Value, null, length, aes.EncryptBlockInSitu); aes.LastBlock.CopyTo(tag); } }
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); }
private void HandleCtr(int length) { var ivBlock = Block.UsingBytes(inputVector); var encryptedNonceCounterBlock = Block.OfSize(AesBlockSizeInBytes); using (var aes = AesProvider.GetEcbProvider(GetSelectedKey())) { ProcessDataInMemory(dmaInputAddress.Value, dmaOutputAddress.Value, length, b => { aes.EncryptBlock(ivBlock, encryptedNonceCounterBlock); b.XorWith(encryptedNonceCounterBlock); IncrementCounter(ivBlock.Buffer, (int)counterWidth.Value); }); } }
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); }