Wednesday, January 20, 2021
Monday, March 9, 2020
Cryptography in .NET - C#
Symmetric Key Encryption
One usual way to storing password is using encryption. it's a two-way process. That means the password is encrypted using the secret key when storing and decrypt using the same key for the password authentication.
It's better than storing the password as plain text. But key management is the challenge. Where do you save that key? If it is a database, It won't be difficult for the hacker who got the encrypted password by hacking the database and decrypt it using the same key.
Asymmetric Key Encryption
So instead of using symmetric key encryption algorithm. we can use asymmetric key encryption algorithm like RSA where client uses public key to encrypt the password and sends it to the server for storage. When authenticate a private key is used to decrypt the password. That private key should be kept secret. This is also not a great solution as the key management is difficult like the previous way.
Hashing
If we use Hashing there won't be any over head of key management. Also no need to decrypt the password back to plain text. Hashing is one way operation. Once a data is hashed we cannot reverse and get the original message, It has four important properties,
It's better than storing the password as plain text. But key management is the challenge. Where do you save that key? If it is a database, It won't be difficult for the hacker who got the encrypted password by hacking the database and decrypt it using the same key.
.NET provides multiple symmetric algorithms and multiple implementations for some algorithms:
AES: AESManaged, AesCng, AesCryptoServiceProvider
DES: DESCryptoServiceProvider
RC2: RC2CryptoServiceProvider
Rijndael: RijndaelManaged
TripleDES: TripleDESCng, TripleDESCryptoServiceProvider
So instead of using symmetric key encryption algorithm. we can use asymmetric key encryption algorithm like RSA where client uses public key to encrypt the password and sends it to the server for storage. When authenticate a private key is used to decrypt the password. That private key should be kept secret. This is also not a great solution as the key management is difficult like the previous way.
.NET provides multiple asymmetric algorithms and multiple implementations for some algorithms:
DSA: DSACng, DSACryptoServiceProvider, DSAOpenSsl
ECDiffieHellman: ECDiffieHellmanCng, ECDiffieHellmanOpenSsl
ECDsa: ECDsaCng, ECDsaOpenSsl
RSA: RSACng, RSACryptoServiceProvider, RSAOpenSsl
If we use Hashing there won't be any over head of key management. Also no need to decrypt the password back to plain text. Hashing is one way operation. Once a data is hashed we cannot reverse and get the original message, It has four important properties,
- Easy to compute the hash value for any given message
- Not possible to generate a message from the given hash
- Not possible to modify a message without changing the hash
- Not possible to find two different messages with the same hash
Salted Hash
It is common for a web application to store in a database the hash value of a user's password. Without a salt, a successful SQL injection attack may yield easily crackable passwords. Because many users re-use passwords for multiple sites, the use of a salt is an important component of overall web application security
If we append a random value with a hashed password, Which is difficult for the attacker to hack using brute force or rainbow table attack. The random value is called Salt. The Salted hash and the Salt will be stored in the database as the Salt is required when the password authentication.
It is common for a web application to store in a database the hash value of a user's password. Without a salt, a successful SQL injection attack may yield easily crackable passwords. Because many users re-use passwords for multiple sites, the use of a salt is an important component of overall web application security
Monday, November 18, 2019
Usefull extension methods
//
foreach with a "manual" index
int index = 0;
foreach (var item in
collection)
{
DoSomething(item,
index);
index++;
}
//
normal for loop
for (int index = 0; index <
collection.Count; index++)
{
var
item = collection[index];
DoSomething(item,
index);
}
|
It’s something that has always annoyed me;
couldn’t we have the benefits of both foreach and for?
It turns out that there’s a simple solution,
using Linq and tuples. Just write an extension method like this:
using System.Linq;
...
public static IEnumerable<(T item, int
index)> WithIndex<T>(this IEnumerable<T> source)
{
return
source.Select((item, index) => (item, index));
}
|
Do this:
foreach (var (item, index) in
collection.WithIndex())
{
DoSomething(item,
index);
}
|
Multilist collection by Tuple
IList<Tuple<string, string, string, string, string>> listOfData = new List<Tuple<string, string, string, string, string>>();
foreach (var item in
interactionDataSetInformation)
{
listOfData.Add(new Tuple<string, string, string, string, string>(item.ICNOcurs,
item.MessageType, item.Revision, item.EntityState, item.EntityStatus));
}
Multilist collection by ArrayList
ArrayList listOfData = new
ArrayList();
foreach (var item in
interactionDataSetInformation)
{
listOfData.Add(new string[] { item.ICNOcurs,
item.MessageType, item.Revision, item.EntityState, item.EntityStatus });
}
ArrayList listOfData =
interactionDataSetInformation.ToArrayList<InteractionDataSetInformation>();
Extension methods
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType)
?? prop.PropertyType);
}
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor
prop in properties)
row[prop.Name] =
prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
public static List<T> ToList<T>(this ArrayList arrayList)
{
List<T> list = new List<T>(arrayList.Count);
foreach (T instance in arrayList)
{
list.Add(instance);
}
return list;
}
public static ArrayList ToArrayList<T>(this IEnumerable<T> list)
{
ArrayList arrayList = new
ArrayList();
foreach (T item in list)
{
List<string> listString = new List<string>();
foreach (PropertyInfo
prop in typeof(T).GetProperties())
{
listString.Add((prop.GetValue(item) == null) ? string.Empty :
prop.GetValue(item).ToString());
}
string[] _item = listString.ToArray();
arrayList.Add(_item);
}
return arrayList;
}
}
-------------------------------------------------------------------------------------------------------------------------Friday, November 1, 2019
Unity Dependency Injection with N-Layer Project
Web/Web Api
-----------
public class SubProjApiProductController : ApiController
{
private readonly IWebApiBusinessFactory _webApiBusinessFactory;
public SubProjApiProductController(IWebApiBusinessFactory webApiBusinessFactory)
{
_webApiBusinessFactory = webApiBusinessFactory;
}
[Route("api/products")]
[HttpPost]
public async Task<IHttpActionResult> GetProducts([FromBody] IDictionary<string, string> data)
{
try
{
return Ok(await _webApiBusinessFactory.QueryProductService().GetProductsAsync(data).ConfigureAwait(false));
}
catch (Exception ex)
{
return Content(HttpStatusCode.NotFound, ex.Message);
//return NotFound();
}
}
[Route("api/addproduct")]
[HttpPost]
public async Task<IHttpActionResult> AddProduct([FromBody] Product product)
{
try
{
await _webApiBusinessFactory.CommandProductService().InsertAsync(product).ConfigureAwait(false);
return Ok();
}
catch (Exception ex)
{
return Content(HttpStatusCode.NotFound, ex.Message);
//return NotFound();
}
}
}
public static class UnityConfig
{
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below.
// Make sure to add a Unity.Configuration to the using statements.
// container.LoadConfiguration();
// container.AddNewExtension<BusinessUnityContainerExtension>(); //for non-parameter
container.AddExtension(new BusinessUnityContainerExtension(_connectionString, _connectionTimeout));
//Product Api
container.RegisterType<SubProjApiProductController>(new InjectionConstructor(new ResolvedParameter<IWebApiBusinessFactory>()));
}
}
Business Layer
--------------
public class BusinessUnityContainerExtension : UnityContainerExtension
{
#region Fields
private readonly string _connectionString;
private readonly int? _connectionTimeout;
#endregion Fields
public BusinessUnityContainerExtension(string connectionString, int? connectionTimeout)
{
_connectionString = connectionString;
_connectionTimeout = connectionTimeout ?? 0;
}
protected override void Initialize()
{
Container.RegisterType<IUnitOfWorkFactory, UnitOfWorkFactory>(new HierarchicalLifetimeManager());
Container.RegisterType<IWebApiBusinessFactory, WebApiBusinessFactory>(new HierarchicalLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IUnitOfWorkFactory>()));
}
}
Friday, October 11, 2019
Class diagram, Entity relationship diagram ,Layer Diagrams, Code Maps
Class Diagram
- Goto Class View and right-click --> View --> view class diagram
- Select all typeson the diagram by pressing Ctrl+A
- Expand all types by pressiong the “+” key on the numeric keypad
- Right-click on the diagram and select Adust shapes width
- Right-click on the diagram and select Layout Diagram
- Right-click on the diagram and select Export diagram as image
Entity Relationship Diagram
entity relationship diagram. It was tested in
VS2012- Open
Visual Studio - Create a project or open an existing project (must be Visual Basic, Visual C# project, or Console Application)
- Right-click the project and choose
Add->New Item… - Under Visual C# Items select
“Data” - Select the template
“ADO.NET Entity Data Model” - Give it a name and click
“Add” - Select
“Generate from database”or“Empty model” - If
“Generate from database”selected enter connection info, choose the database objects and done!
The model is stored as a
“.edmx” file.Layer Diagram
Create and drag projects
Code Maps
Create and drag projects
Sequence Diagram
Removed from newer version of visual studio
Subscribe to:
Posts (Atom)
Encrypt/Decrypt the App.Config
Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig { internal class Program { pr...
-
Overview of .NET Framework release history Version number CLR version Release date Suppor...
-
Setting up SQL Server Service Broker for secure communication --------------------------------------------------------------------------...
-
SQL Server Maintenance Plan Best Practices Check Database Integrity Shrink Database Rebuild Index Reorganize Index Update...



