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.

.NET provides multiple symmetric algorithms and multiple implementations for some algorithms:

AES: AESManaged, AesCng, AesCryptoServiceProvider
DES: DESCryptoServiceProvider
RC2: RC2CryptoServiceProvider
Rijndael: RijndaelManaged
TripleDES: TripleDESCng, TripleDESCryptoServiceProvider

 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.

.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

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,
  • 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.


No comments:

Post a Comment

Encrypt/Decrypt the App.Config

Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig {     internal class Program     {         pr...