Showing posts with label Articles. Show all posts
Showing posts with label Articles. Show all posts

Wednesday, May 28, 2025

How to Securing Passwords Against Quantum Computers

Why special care for passwords?

Passwords are stored as hashes, not encrypted, to prevent attackers from recovering the original password if the database leaks. However, with quantum computers, classical password hashing algorithms could become easier to brute force.

Quantum Threats to Password Hashing

  • Grover’s algorithm speeds up brute-force attacks quadratically on symmetric cryptography and hash functions.
  • This means attackers could try roughly the square root of password guesses in the same time compared to classical brute force.
  • Password hashing needs to be computationally expensive and memory-hard, making each guess costly on quantum hardware.

Best Practices for Quantum-Resistant Password Hashing

  1. Use slow, memory-hard hashing algorithms designed for password storage like Argon2, scrypt, or bcrypt.
  2. Always use a unique random salt per password.
  3. Use sufficiently large parameters (iterations, memory, CPU cost) to slow brute forcing.
  4. Use constant-time verification to avoid timing attacks.

C# Examples for Quantum-Resistant Password Hashing:


1. Argon2 — Recommended for quantum resistance

// Install NuGet Package: Install-Package Isopoh.Cryptography.Argon2
using Isopoh.Cryptography.Argon2;
using System;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Hash the password with Argon2id
        string hash = Argon2.Hash(password);

        Console.WriteLine($"Argon2 Hash: {hash}");

        // Verify the password
        bool valid = Argon2.Verify(hash, password);
        Console.WriteLine($"Password valid? {valid}");
    }
}

2. bcrypt — Widely used, moderately quantum-resistant

// Install NuGet Package: Install-Package BCrypt.Net-Next
using BCrypt.Net;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Generate bcrypt hash
        string hash = BCrypt.Net.BCrypt.HashPassword(password);

        Console.WriteLine($"bcrypt Hash: {hash}");

        // Verify the password
        bool valid = BCrypt.Net.BCrypt.Verify(password, hash);
        Console.WriteLine($"Password valid? {valid}");
    }
}

3. scrypt — Memory-hard, good for resisting quantum attacks

// Install NuGet Package: Install-Package CryptSharpOfficial
using CryptSharp;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Generate scrypt hash
        string hash = Crypter.Scrypt.Crypt(password);

        Console.WriteLine($"scrypt Hash: {hash}");

        // Verify the password
        bool valid = Crypter.CheckPassword(password, hash);
        Console.WriteLine($"Password valid? {valid}");
    }
}

4. PBKDF2 — Built-in, less memory-hard, but still usable with high iteration count

using System;
using System.Security.Cryptography;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Generate a 16-byte salt
        byte[] salt = new byte[16];
        using (var rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(salt);
        }

        // Derive a 256-bit key using PBKDF2 with 100,000 iterations and SHA256
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100_000, HashAlgorithmName.SHA256);
        byte[] hash = pbkdf2.GetBytes(32);

        // Convert to base64 for storage
        string saltBase64 = Convert.ToBase64String(salt);
        string hashBase64 = Convert.ToBase64String(hash);

        Console.WriteLine($"Salt: {saltBase64}");
        Console.WriteLine($"Hash: {hashBase64}");

        // Verification
        var pbkdf2Verify = new Rfc2898DeriveBytes(password, salt, 100_000, HashAlgorithmName.SHA256);
        byte[] hashToVerify = pbkdf2Verify.GetBytes(32);

        bool valid = CryptographicOperations.FixedTimeEquals(hash, hashToVerify);
        Console.WriteLine($"Password valid? {valid}");
    }
}

Friday, April 21, 2023

How to improve the performance of SQL queries ?

There are several ways to improve the performance of SQL queries:

  1. Indexing: 
    • Indexing is the process of creating a data structure that allows for faster retrieval of data. By indexing frequently used columns, queries can run much faster. You should index columns that are frequently used in WHERE, JOIN, and ORDER BY clauses.
  2. Use appropriate data types: 
    • It's important to use appropriate data types for columns in your tables. Using the wrong data type can lead to slower queries. For example, if you're storing dates as strings instead of using the DATE data type, it can slow down queries that are filtering by dates.
  3. Limit the amount of data returned: 
    • When you're writing queries, try to limit the amount of data that is returned. You can do this by using the SELECT statement to only return the columns that you need, and by using the WHERE clause to filter out rows that you don't need.
  4. Avoid using SELECT *: 
    • Using SELECT * can slow down queries because it returns all columns in the table, even if you don't need them. Instead, you should specify the columns that you need.
  5. Use JOINs wisely: 
    • JOINs can be very powerful, but they can also be very slow if not used correctly. Try to use INNER JOINs instead of OUTER JOINs whenever possible, and make sure that you're joining on columns that are indexed.
  6. Avoid subqueries: 
    • Subqueries can be slow, so try to avoid them whenever possible. You can often rewrite a subquery as a JOIN or a correlated subquery to improve performance.
  7. Optimize database design: 
    • Good database design can improve query performance. Make sure that your tables are normalized and that you're using appropriate data types for columns.
  8. Use stored procedures: 
    • Stored procedures can be precompiled and stored in memory, which can improve performance. If you have frequently used queries, consider creating stored procedures for them.
  9. Use database performance tools: 
    • Most databases have performance tools that can help you identify slow queries and optimize them. Use these tools to identify queries that need to be optimized.
  10. Keep your database software up to date: 
    • Finally, make sure that you're using the latest version of your database software. Newer versions often have performance improvements that can help speed up queries.

By following these tips, you can help ensure that your SQL queries are as fast and efficient as possible. 

Thursday, April 20, 2023

8 Ways to Improve the Performance of C# Projects

Here are top 8 ways to improve the performance of C# projects:

        1. Optimize database access: 
    • Make sure your database queries are efficient and use indexes where appropriate. Avoid using expensive queries that can slow down your application.
        2. Use asynchronous programming:
    • Asynchronous programming can help improve the performance of your application by allowing multiple tasks to be executed concurrently, rather than blocking the main thread.
        3. Cache frequently used data: 
    • Caching frequently used data can help reduce the number of database queries and improve the response time of your application.
        4. Use object pooling: 
    • Object pooling can help reduce the overhead of object creation and destruction, and improve the performance of your application.
        5. Avoid boxing and unboxing: 
    • Boxing and unboxing can cause unnecessary memory allocation and de-allocation, which can affect the performance of your application.
        6. Use value types instead of reference types: 
    • Value types are stored on the stack, whereas reference types are stored on the heap. Using value types can help reduce the memory allocation and improve the performance of your application.
        7. Optimize loops: 
    • Loops can be a performance bottleneck in your application. Consider using foreach loops instead of for loops, and use the most efficient loop construct for your specific scenario.
        8. Use code profiling tools: 
    • Use code profiling tools to identify performance bottlenecks in your application. These tools can help you identify which parts of your code are taking the most time to execute, so you can focus your optimization efforts.

By following these tips, you can improve the performance of your C# projects and ensure that your applications are running efficiently.

Top 8 New Features in C# 11

C# 11 is the latest version of the C# programming language, released in November 2021. Here are some of the top features included in C# 11:

1. Global using directives:

You can now add a global using directive to your C# files, which means you don't need to add using statements for commonly used namespaces in every file.
// Instead of adding using statements for every file, you can use a global using directive
// to import commonly used namespaces into every file in your project
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Text;
2. Improved target-typed conditional expressions:

C# 11 allows for more flexible use of target-typed conditional expressions, which can make your code more concise and readable.
// C# 11 allows for more flexible use of target-typed conditional expressions
// Here's an example that uses a target-typed conditional expression to check if a value is null
object? nullableObject = null;
string result = nullableObject is null ? "Object is null" : "Object is not null";
Console.WriteLine(result);
3. File-scoped namespaces:

With file-scoped namespaces, you can define a namespace for an entire file rather than having to include a namespace declaration for each individual class.
// With file-scoped namespaces, you can define a namespace for an entire file
// rather than having to include a namespace declaration for each individual class
namespace MyNamespace;

class MyClass
{
    // Class members go here
}
4. Interpolated string improvements:

Interpolated strings now support string interpolation for expressions that return values of any type, not just strings.
// Interpolated strings now support string interpolation for expressions that return values of any type
int x = 5;
string result = $"The value of x is {x}";
Console.WriteLine(result);
5. Extended support for lambda discard parameters:

You can now use discard parameters in lambda expressions, which can make your code more concise and easier to read.
// You can now use discard parameters in lambda expressions
List numbers = new() { 1, 2, 3, 4, 5 };
numbers.ForEach(_ => Console.WriteLine("Hello"));
6. "and" and "or" patterns:

C# 11 introduces new patterns that allow for more complex pattern matching logic, including the ability to combine patterns using "and" and "or".
// C# 11 introduces new patterns that allow for more complex pattern matching logic
// including the ability to combine patterns using "and" and "or"
object obj = "Hello, world!";
if (obj is string { Length: > 5 } or null)
{
    Console.WriteLine("The object is a string with length greater than 5, or null");
}
7. Improved support for global usings in .NET Standard 2.1 and earlier:

Global using directives are now supported in .NET Standard 2.1 and earlier, making it easier to write cross-platform code.
// Global using directives are now supported in .NET Standard 2.1 and earlier
// Here's an example of using a global using directive to import System.IO
// into every file in your project
global using System.IO;
8. Improved support for nullability:

C# 11 includes several improvements to nullability, including better support for nullable reference types and the ability to specify nullability for parameters.
// C# 11 includes several improvements to nullability
// including better support for nullable reference types and the ability to specify nullability for parameters
void MyMethod(string? nullableString)
{
    // The nullableString parameter may be null, so we need to check for null before using it
    if (nullableString is not null)
    {
        Console.WriteLine(nullableString.ToUpper());
    }
}

SOLID Software Design Principles - Brief Explanation

SOLID software principles is the set of principles put forward by Robert C. Martin, which ensures that the software developed is flexible, reusable, sustainable and understandable and prevents code repetition. So the main purpose of these principles are, in order to easily adapted to requirements in the future and easier to add new features without the need to change anything in your code and also minimal change in code despite the new requirements and minimize the loss of time caused by the problems, such as the continuous correction on the code or even re-writing to code.

We have five principles.


1. Single Responsibility Principle

A class should have only one reason to change, i.e., it should have only one responsibility or job to do. This principle helps to keep classes focused, and makes them easier to understand, test, and maintain.

Example:

2. Open Close Principal

Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. In other words, you should be able to add new functionality to a system without changing its existing code. This principle promotes the use of inheritance and polymorphism to achieve this goal.

Example:

3. Liskov Substitution Principle

Subtypes must be substitutable for their base types. This principle states that any object of a derived class should be able to replace an object of its base class without causing any problems or errors. This principle ensures that inheritance is used correctly and that objects are well-behaved in a system.

Example:

4. Interface Segregation Principle

Clients should not be forced to depend on interfaces they don't use. This principle suggests that it's better to have many smaller interfaces than one large interface. This promotes decoupling and helps to prevent changes in one part of the system from affecting other parts.

Example:

5. Dependency Inversion Principle

High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions. This principle promotes the use of interfaces and dependency injection to decouple modules and improve their flexibility and maintainability.

Example:

These are the main principles in software development and all these principles is very similar to each other.

Tuesday, April 5, 2022

What is Recursion in Programming

Recursion is calling a function itself multiple times to solve a given problem. Just like loops, you also need to specify when that function should stop calling itself. Such a condition is called as the base condition. 

For example, consider the below code which prints "Hello World" repeatedly. The showMessage function calls itself multiple times but the base condition is not defined and hence, this leads to an infinite loop.
function showMessage(n) {
    console.log("Hello world ", n);
    showMessage(n - 1);
}

showMessage(10);

Now, observe the code after adding the base condition. When n becomes 0, the recursive call stops.
function showMessage(n){
    if(n==0){
        return;
    }
    console.log("Hello world ",n);
    showMessage(n-1);
}

showMessage(10);
Let us see how to use recursion to perform some calculations. The below code calculates the sum of first n numbers.
function sum(n){
    if(n==1){
        return 1
    }
    else{
        return n+sum(n-1);
    }
}

var sumResult=sum(10);
console.log(sumResult);

Every recursion can be replaced with an equivalent iteration statement. Recursive algorithms are usually slower than iterative algorithms. In the above example which calculates the sum of first n numbers. Here, the sum of first 10 numbers is checked. If you want the sum of first 600000 numbers, the recursive code will crash. Interestingly, the below iterative algorithm to calculate the sum of n numbers has the same complexity, O(n).
function sum(n){
    var sum=0;
    while(n!=0){
        sum+=n;
        n--;
    }
    return sum;
}

var sumResult=sum(600000);
console.log(sumResult);

But the below equivalent code has a time complexity of O(1).
function sum(n){
    return n*(n+1)/2;
}

However, recursive algorithms have below advantages: 
  • Recursion adds clarity and sometimes reduces the time needed to write and debug code. 
  • Performs better in solving problems based on tree structures.

Sunday, July 21, 2019

10 Advice from Warren Buffet for Young People Who Want to Be Rich

Warren Buffet became a millionaire in 1960 at the age of 30 and ever since then, He has been one of the richest people in the world. Over the years he has given various advice to young people about how they can be rich and successful.



Advice No. 1. “I will tell you how to become rich. Close the doors. Be fearful when others are greedy. Be greedy when others are fearful.”

Advice No. 2. “No matter how great the talent or efforts, some things just take time. You can’t produce a baby in one month by getting nine women pregnant”.

Advice No. 3. “It’s better to hang out with people better than you. Pick out associates whose behavior is better than yours and you’ll drift in that direction.”

Advice No. 4. “You won’t keep control of your time, unless you can say ‘no.’ You can’t let other people set your agenda in life.”

Advice No. 5. “You don’t have to be smarter than the rest. You have to be more disciplined than the rest.”

Advice No. 6. “Risk comes from not knowing what you’re doing.”

Advice No. 7. “The chains of habit are too light to be felt until they are too heavy to be broken.”

Advice No. 8. “Enjoy your work and work for whom you admire.“

Advice No. 9. “You can’t buy what is popular and do well.”

Advice No. 10. “Never invest in a business you cannot understand.”

Wednesday, November 11, 2015

Best way to secure password using Cryptographic algorithms in C# .NET

Let me explain with some of the common ways of storing passwords in the database with its demerits. By reading this full article you will understand the best way to secure your password  using Cryptographic algorithms in C# .NET.


1. Plain text

Storing password in plain text is the worst way of password management. If the database is compromised by the hacker, with no effort he can reveal all the passwords.

2. 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.

3. 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.

4. 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. As we discussed in my previous article Cryptographic Hashing Algorithm in .NET C#, 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

Two types of attack is possible on the hashed password. They are,
  1. Brute force attack
  2. Rainbow table attack
Brute force attack

The attacker would try the different combination of passwords hash that is equivalent to the password hash you have stored. Using the latest high performance graphic processor system it is possible to generate billions of random password hash. It only the matter of time to  generate the correct password.

Rainbow table attack

A rainbow table is a listing of all possible plain text permutations of hashed passwords specific to a given hash algorithm. Which is often used for crack the password from the hashed values that we stored in the application database. It can be Giga bytes of size. Once an attacker gains access to a system’s password database, the password cracker compares the rainbow table’s precompiled list of hashes to hashed passwords in the database. The rainbow table relate plaintext possibilities with each of those hashes. Thus attacker could crack the password.

5. 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.

Salted Hash Sample Code :
using System;
using System.Security.Cryptography;
using System.Text;
static void Main()
{
    const string password = "SampleP455w0rd";
    byte[] salt = GenerateSalt();

    Console.WriteLine("Sample Password : " + password);
    Console.WriteLine("Generated Salt : " + Convert.ToBase64String(salt));
    Console.WriteLine();

    var hashedPassword = HashPasswordWithSalt(Encoding.UTF8.GetBytes(password), salt);

    Console.WriteLine("Salted Hash Password : " + Convert.ToBase64String(hashedPassword));
    Console.WriteLine();
   
    Console.ReadLine();
}
public static byte[] GenerateSalt()
{
    const int saltLength = 32;

    using (var randomNumberGenerator = new RNGCryptoServiceProvider())
    {
        var randomNumber = new byte[saltLength];
        randomNumberGenerator.GetBytes(randomNumber);

        return randomNumber;
    }
}
private static byte[] Combine(byte[] first, byte[] second)
{
    var ret = new byte[first.Length + second.Length];

    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);

    return ret;
}
public static byte[] HashPasswordWithSalt(byte[] toBeHashed, byte[] salt)
{
    using (var sha256 = SHA256.Create())
    {
        var combinedHash = Combine(toBeHashed, salt);

        return sha256.ComputeHash(combinedHash);
    }
}
Console Output



6. Password Based Key Derivation Function (PBKDF2)

Attackers can use super computers for the brute force attack as it could generate large number of random passwords within a sort period of time. To solve this PBKDF2 is used.


The PBKDF2 expect password input with salt also additionally the number of iteration the password should be hashed. It  makes password cracking much more difficult also increase the time taken to generate the hash value. You can see the delay in below sample code based on the number of iteration value u have passed.

When the standard was written in 2000, the recommended minimum number of iterations was 1000, but the parameter is intended to be increased over time as CPU speeds increase. As of 2005 a Kerberos standard recommended 4096 iterations, Apple iOS 3 used 2000, iOS 4 used 10000, while in 2011 LastPass used 5000 iterations for JavaScript clients and 100000 iterations for server-side hashing.

PBKDF2 Sample Code
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
static void Main()
{
    const string passwordToHash = "SamplePassword";

    HashPassword(passwordToHash, 100);

    HashPassword(passwordToHash, 50000);

    HashPassword(passwordToHash, 500000);

    Console.ReadLine();
}
private static void HashPassword(string passwordToHash, int numberOfRounds)
{
    var sw = new Stopwatch();

    sw.Start();
    var hashedPassword = HashPassword(Encoding.UTF8.GetBytes(passwordToHash), GenerateSalt(), numberOfRounds);
    sw.Stop();

    Console.WriteLine("Password to hash : " + passwordToHash);
    Console.WriteLine("PBKDF2 Hashed Password : " + Convert.ToBase64String(hashedPassword));
    Console.WriteLine("Iterations : " + numberOfRounds);
    Console.WriteLine("Elapsed Time : " + sw.ElapsedMilliseconds + "ms");
    Console.WriteLine();
}
public static byte[] GenerateSalt()
{
    using (var randomNumberGenerator = new RNGCryptoServiceProvider())
    {
        var randomNumber = new byte[32];
        randomNumberGenerator.GetBytes(randomNumber);

    return randomNumber;
    }
}
public static byte[] HashPassword(byte[] toBeHashed, byte[] salt, int numberOfRounds)
{
    using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(toBeHashed, salt, numberOfRounds))
    {
        return rfc2898DeriveBytes.GetBytes(32);
    }
}
Console Output



Thursday, October 15, 2015

Cryptographic Hash-based Message Authentication Code (HMAC) Algorithm in .NET C#

If we combine one way hash functions with secret cryptographic key that's called HMAC. like hash code the HMAC is used to verify the integrity of the code. It is also allow us to verify the authentication of the message. Only the person who has the key can calculate the hash. This HMAC can be used with different hashing methods like MD5 and SHA family.

So the HMAC is used to check both the integrity and authenticity. For example, assume that you are sending a message and hash. Receiver can verify it by comparing with hash he received. However we are not sure weather the message will be delivered to the person to whom you need to send. So using a private key we can secure the message. Using the same key he can recompute the HMAC and compare it with the HMAC you sent. That ensures the authenticity.

The code implementation is same as what we did in MD5 and SHA family samples in my previous post except only one change that we have to pass a private key to the hashing method. The primary key can be generated using another cryptocraphic method called RNGCryptoServiceProvider. That I have explained in my another post Generate Random numbers using RNGCryptoServiceProvider in C#.

HMAC SHA-512 Sample
using System;
using System.Security.Cryptography;
using System.Text;
static void Main()
{
    var key = GenerateKey();

    const string message1 = "The quick brown fox jumps over the lazy dog";
    const string message2 = "The quick brown fox jumps over the lazy dog.";

    Console.WriteLine("Original Message 1 : " + message1);
    Console.WriteLine("Original Message 2 : " + message2);
    Console.WriteLine();

    var hmacMessage = ComputeHmacHash(Encoding.UTF8.GetBytes(message1), key);
    var hmacMessage2 = ComputeHmacHash(Encoding.UTF8.GetBytes(message2), key);

    Console.WriteLine();
    Console.WriteLine("HMAC SHA-512 Hash");
    Console.WriteLine();
    Console.WriteLine("Message 1 hash = " + Convert.ToBase64String(hmacMessage));
    Console.WriteLine("Message 2 hash = " + Convert.ToBase64String(hmacMessage2));
    Console.ReadLine();
}
public static byte[] ComputeHmacHash(byte[] toBeHashed, byte[] key)
{
    using (var hmac = new HMACSHA512(key))
    {
        return hmac.ComputeHash(toBeHashed);
    }
}
public static byte[] GenerateKey()
{
    const int KeySize = 32;

    using (var randomNumberGenerator = new RNGCryptoServiceProvider())
    {
        var randomNumber = new byte[KeySize];
        randomNumberGenerator.GetBytes(randomNumber);

        return randomNumber;
    }
}
Output 

The same way we can implement the HMAC for HMAC MD5, HMAC SHA1, HMAC SHA-256 and HMAC SHA-512 using its corresponding class HMACMD5(key),  HMACSHA1(key) and HMACSHA256(key).

Cryptographic Hashing Algorithm in .NET C#

The idea of hashing is to generate a fixed size string from the give input data. That will be encoded ie, It can not be read. .Net has various hashing algorithms MD5, SHA1, SHA2 and SHA3 are derived from a single class called HashAlgorithm.

Hashing can be used in two different ways. With and without using Secret key. Hashing without secret key is called HMAC (Hash-based Message Authentication Code).

Hashing is one way operation. Once a data is hashed we cannot reverse and get the original message. But encryption is two way. Once a messages is encrypted using a key we can reverese it using the same key. This hashing technique is widely used to check the data integrity. Usefull to check the transfered data is corrupted or not.



From the above image, Person 1 sends a message and its hash to Person 2. Person 2 receives both and compute the hash for the received message and compare with the received hash. If both are equal means the file is not corrupted or not attacked by the viruses. So we can confirm that we got the complete file bytes.

Even a small change in the message will result in a mostly different hash, due to the avalanche effect. For example, adding a period to the end of the sentence changes some bits in the hash.

In the forthcoming samples I have used two messages to hash. Both having just slight difference that one doesn't have full stop (dot) at the end. But still the generated hash will be completely new one.

Two types of hashing method is used mostly. They are,
  1. MD5
  2. SHA (Secure Hash Algorithm)
MD5

MD5 was designed by Ronald Rivest in 1991. It produces a 160-bit hash value. First flaw found in 1996. So the recommendation was to move over to the Secure Hash Family (SHA).

SHA

Secure Hash Algorithm is published by National Institute of Standards and Technology (NIST) in USA. It has three different varients.
  1. SHA1
  2. SHA2
  3. SHA3
SHA-1

A 160-bit hash function which resembles the earlier MD5 algorithm. This was designed by the National Security Agency (NSA) to be part of the Digital Signature Algorithm. Cryptographic weaknesses were discovered in SHA-1, and the standard was no longer approved for most cryptographic uses after 2010.

SHA-2

It has two different varients.
  1. SHA 256
  2. SHA 512
SHA 256 produces a 256-bit hash computed with 32-bit words and the SHA 512 produces a 512-bit hash computed with 64-bit words. This is also designed by NSA. Both are works the same way than SHA1 but are stronger and generate a longer hash based on its bits.

SHA-3

It was designed after a public competition among non-NSA designers and released by NIST on 2015. SHA-3 is not meant to replace SHA-2, as no significant attack on SHA-2 has been demonstrated. SHA-3 is not commonly supported in .NET directly but 3rd party implementations are available. Implementation of SHA 256 and SHA 512 is straight forward in .NET as the SHA class is identical to MD5.

SHA-512 Sample
using System;
using System.Security.Cryptography;
static void Main()
{
    const string message1 = "The quick brown fox jumps over the lazy dog";
    const string message2 = "The quick brown fox jumps over the lazy dog.";

    Console.WriteLine("Original Message 1 : " + message1);
    Console.WriteLine("Original Message 2 : " + message2);
    Console.WriteLine();

    var md5HashedMessage = ComputeHashCode(Encoding.UTF8.GetBytes(message1));
    var md5HashedMessage2 = ComputeHashCode(Encoding.UTF8.GetBytes(message2));

    Console.WriteLine();
    Console.WriteLine("SHA-512 Hash");
    Console.WriteLine();
    Console.WriteLine("Hashed Message 1 :  " + Convert.ToBase64String(md5HashedMessage));
    Console.WriteLine("Hashed Message 2 :  " + Convert.ToBase64String(md5HashedMessage2));
    Console.ReadLine();
}
public static byte[] ComputeHashCode(byte[] toBeHashed)
{
    using (var md5 = SHA512.Create())
    {
        return md5.ComputeHash(toBeHashed);
    }
}
Output

The same way we can generate the hash of MD5, SHA1 and SHA-256 just by replacing its corresponding methods MD5.Create()SHA1.Create() and SHA256.Create() in the above code sample.

HMAC

Combining one way Hash function with secret Cryptographic key is called HMAC. I have explained it with sample code in my another post Cryptographic Hash-based Message Authentication Code (HMAC) in .NET

Hashing Advantages
  • 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
Ref: Wikipedia, Pluralsight

Friday, September 4, 2015

JSLint - JavaScript code quality tool

JSLint is a static code analysis tool used in software development for checking JavaScript source code complies with coding rules. It is provided primarily as an online tool http://www.jslint.com/. It is also available as a Visual Studio extension JSLint.NET for the .Net developers. It can also check HTML and CSS code qualities.

I found very useful as I am using it in my current ExtJS project. Follow the below simple steps to make it available in your Visual Studio
1. Download the Visual Studio extension by clicking here,
2. Double click and Install the downloaded extension
3. Restart the Visual Studio

It will find your JavaScript coding standard errors and display it as Warnings whenever building your .net web application. You can also manually run it by just right click a JavaScript file and clikck JS Lint. Some additional settings can be configured in the menu Tools -> JS Lint Optons

Check the below attached image to see how it actually displays errors in Visual Studio.


Thursday, September 3, 2015

15 Cool New Features in C# 6.0

The first release of the C# language was in 2002 and then in 2005 version 2 released. It gave us Generics. In 2007, the C# language gave us Linq features, including lambda expressions, implicit typing, a query syntax and var keyword. In 2010, the release of version 4 introduced the dynamic keyword and the dynamic language runtime. And then 2012 brought us version 5 of the language. It gave us the async and await keywords, which make async code much easier to read and write, and in today's world where the async programming model is used nearly everywhere from the server to the client. Compared to the previous release, the language features introduced in this version might seem underwhelming. And partly that's because C# is now over 13 years old; it's a somewhat mature language has major features that have been added over the years. They give us the ability to write less code than we had to write before.



Here is the 15 cool new features in C# 6.0 According to Roslyn some features are planned and might be available in the future.

1. Auto-Property Initializers

In early version of c# if we want to set a default value for a property in a class, we do this in the constructor. In C# 6.0 using Auto-property initializers we can assign a default value for a property as part of the property declaration itself.

// Old way
class Program
{
    public Program()
    {
        MyProperty = 10;
    }

    public int MyProperty { get; set; }
}

// New way
class Program
{
    public int MyProperty { get; set; } = 10
}

2. Using static

With static members you don't need an instance of an object to invoke a method, you just use the typename, a dot, a static method name, and apply parentheses and parameters. This feature allows us to access the static methods inside a class directly without speifying its class name. Usually we use Convert.ToInt32 to convert a value to integer. But using this feature we can just use ToInt32 to convert.

// Old way
namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var value = Convert.ToInt32("2015");
        }
    }
}

// New way
using static Convert;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var value = ToInt32("2015");
        }
    }
}

// Some more samples,
using static System.Console; 
using static System.Math;

class Program 
{ 
    static void Main() 
    { 
        WriteLine(Sqrt(25)); 
    } 
}

3. Dictionary Initializers

Ever since C# version 3 came around, we've had the ability to initialize collections like lists and dictionaries using the key value pairs are surrounded with curly braces. With C# 6.0 we can achieve the same result, using key value inside of square brackets and a sign of value using an equal sign.

// Old way
Dictionary dict = new Dictionary<int, string>
{
    {1, "Apple" },
    {2, "Microsoft" },
    {3, "IBM" }
};

// New way
Dictionary dict = new Dictionary<int, string>
{
    [1] = "Apple",
    [2] = "Microsoft",
    [3] = "IBM" 
};

4. Getter-only auto-properties
When we use auto implemented properties in old vesion of c#, we must provide both get and set. If you want the property value should not be set, you can use the private accessor on the setter, With C# 6.0, you can now omit the set accessor to achieve true readonly auto implemented properties:

// Old way
public int MyProperty { get; private set; }

// New way
public int MyProperty { get; }

5. Null-conditional operators (?.)

This is one of the cool feature in c# 6.0. Usually we use if condition before using it to execution. But using this feature we can check the value is null or not in a single line and proceed the execution if it is not null. It help us to avoid the NullReferenceException.

// Old way
public string Truncate(string value, int length)
{
    string result = value;
    if (value != null)
    {
        result = value.Substring(0, value.Length - 1);
    }

    return result;
}

// New way
public string Truncate(string value, int length)
{          
    return value?.Substring(0, value.Length - 1);
}

Some more samples,
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null 
int length = customers?.Length ?? 0; // 0 if customers is null

6. await in catch and finally block

In c# 6.0 the await keyword can be used inside catch or finally block. Usually we would write log when any exception occured inside catch block itself. In those times we no need to wait for that execution to be completed before going to next line of execution. So using the await keyword those execution will be asynchronous.

try
{

}
catch (Exception)
{
    await LogManager.Write(ex);
}
finally
{
    await LogManager.Write("Done");
}

7. Declaration expressions

Using this feature we can declare local variable in an expression itself instead of declaring globally. But the scope of that variable will be inside the loop.

// Old way
int parsed;
if (!int.TryParse("12345", out parsed))
{ 
}

// New way
if (!int.TryParse("12345", out int parsed))
{
}

8. Primary Constructor

Using this feature the property values can be initialized directly with the help of another new feature Auto-Property Initializers that we have seen in this post, without using default constructor and writing much of code to it. When using a primary constructor all other constructors must call the primary constructor using :this().

// Old way
public class StoredProcedureInfo
{

    private StoredProcedureInfo(string connectionName, string schema, string procedureName)
    {
        this.ConnectionName = connectionName;
        this.Schema = schema;
        this.ProcedureName = procedureName;
    }

    public string ConnectionName { get; set; };
    public string Schema { get; set; };
    public string ProcedureName { get; set; };
}

// New way
private class StoredProcedureInfo(string connectionName, string schema, string procedureName)
{
    public string ConnectionName { get; set; } = connectionName;
    public string Schema { get; set; } = schema;
    public string ProcedureName { get; set; } = procedureName;
}

9. Exception filters

This feature allow us to specify a condition on a catch block. Based on that condition the catch block will be executed.

try
{
}
catch (Exception ex) if (UserPermission == Permission.Administrator)
{
}
catch (Exception ex) if (UserPermission == Permission.Requester)
{
} 

10. Expression-bodied function

Expression-bodied function members allow methods, properties, operators and other function members to have bodies as lambda like expressions instead of statement blocks. It helps reducing lines of codes.

// Old way
public int Multiply(int a, int b)
{
    return a * b;
}

// New way
public int Multiply(int a, int b) = > a * b;

// Old way
public int WriteLog(string log)
{
    LogManager.Write(log);
}

// New way
public int WriteLog(string log) => LogManager.Write(log);

// Some more samples,
public double Distance => Math.Sqrt(X + Y); // property
public void Execute() => Math.Sqrt(25); // method

11. String Interpolation

This feature is one of an addition to the string format technique in c#. So far we used + sign or string.format to format a string. But in this feature we can directly use the value to be concatinate inside the string itself using \{} symbol. Any condition can be used inside the braces.

// Old way
public string FormatString(int value)
{
    return "Total # of tickets: "+ value + " tickets";
}

public string FormatString(int value)
{
    return string.Format("Total # of tickets: {0} tickets", value);
}

// New way
public string FormatString(int value)
{
    return "Total # of tickets: \{(value <= 1 ? "ticket" : "tickts")}";
}

// Some more samples,
var s = "\{person.Name} is \{person .Age} year\{(person.Age == 1 ? "" : "s")} old"; 

12. nameof

Used to obtain the simple (unqualified) string name of a variable, type, or member. When reporting errors in code instead of hard code it.

// Old way
public void SaveData()
{
    try
    {
    }
    catch (Exception ex)
    {
        this.WriteLog("SaveData", ex);
    }
}

// New way
public void SaveData()
{
    try
    {
    }
    catch (Exception ex)
    {
        this.WriteLog(nameof(SaveData), ex);
    }
}

13. Literals and Separators

When initializing fields and properties and variables with numerical values, we have a new binary literal syntax we can use, 0b. We can write binary values with a 0b prefix and then use just ones and zeros to specify which bits are on and off. This can lead to more readable code.
public byte code = 0b01011011010;
Another feature we have for numeric literals will be the ability to use an underscore as a separator. It's much easier to look at a value and see it as in the billions or the millions when we have an underscore separating the digits instead of just a long string of numbers. The C# compiler doesn't actually care where you use the separator, the separator can appear anywhere after the first leading digit.

public long value = 1_000_000_000;

14. Event Initializer

C# 6.0 will now allow us to wire up event handlers as part of an object initialization syntax. Before a version 6 of the language, this event wire up syntax would be illegal. I just always have to remember to use the += operator to wire up an event. Trying to assign directly to an event using an equal sign is still illegal. Events need to encapsulate the delegates that they hold inside, so from the outside we can only use += and -= to add and remove delegates respectively. In an initializer you'd want to be using += to add delegates and listen for an event to fire.

public class Person
{
    private int _age;
    public int Age
    {
        get
        {
            return _age;
        }
        set
        {
            _age = value;
             OnAgeChanged(EventArgs.Empty);
        }
    }

    public string Name { get; set; }

    public event EventHandler AgeChanged;

    protected virtual void OnAgeChanged(EventArgs e)
    {
        if (AgeChanged != null)
        {
            AgeChanged(this, e);
        }
    }
}

// Old way
class Program
{
    static void Main(string[] args)
    {
        var pers = new Person()
        {
            Name = "Venkat"
        };
        pers.AgeChanged += pers_AgeChanged;
 }

    static void pers_AgeChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Changed");
    }
}

// New way
class Program
{
    static void Main(string[] args)
    {
        var pers = new Person()
        {
            Name = "Venkat",
             AgeChanged += pers_AgeChanged
        };
    }

    static void pers_AgeChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Changed");
    }
}
15. params and Ienumerable

In C# version 6.0 we can use the params keyword with IEnumerable instead of using an array.

// Old way
void Foo(params int[] a) 
{
}

Foo(10,2,4,22);

// New way
void Foo(params IEnumerable<int> a) 
{
}

Foo(10,2,4,22);

Happy Coding!

Trello - Free Project Management Tool

Trello


Trello is a free web-based lighter-weight project management tool. It makes the project well organized. You can crate separate boards for your each project. A Trello board is a list of lists, filled with cards, used by you and your team. Its UI looks so cool, It makes project collaboration simple and kind of enjoyable. It has everything you need to organize projects of any size and any kind. You can create as many boards, cards, and organizations as you like and add as many people as you want. You can choose to make any number of boards or organizations private or public. Bellow image shows how a board look like. You can drag and drop cards from one list to another based on the task completion.



You can invite as many people to your board as you need, all for free. Drag and drop people to cards to divvy up tasks. Everyone sees the same board and the whole picture all at once. You can start a discussion with comments and attachments. Mention any member in a comment using @ symbol like what we using in facebook, to make sure they get notified.

You can create cards and comment via email. Trello uploads the attachments you send along, too. Also, when you get notifications via email, you can reply via email without opening Trello.

Open a card and you can add comments, upload file attachments, create checklists, add labels and due dates, and more. Add files by uploading them from your computer, Google Drive, Dropbox, Box, and OneDrive.

Whenever something important happens, you know instantly with Trello’s notification system. You’ll get notifications wherever you are: inside the app, via email, desktop notifications via the browser, or via mobile push notifications. Notifications stay in sync across all your devices. Notifications stay in sync across all your devices.

Your project may have hundreds of cards. You can easily search any card with the search and filter functionality. Search is incredible fast and powerful, with sophisticated operators that help you narrow your search. It will list out all the card related to your search with the link to the particular card. You can click there to access the card directly. Search operators refine your search to help you find specific cards and create highly tailored lists. Trello will suggest operators for you as you type, but here’s a full list to keep in mind.
  • @name - Returns cards assigned to a member
  • #label - Returns labeled cards
  • board:id - Returns cards within a specific board
  • list:name - Returns cards within the list named “name”
  • has:attachments - Returns cards with attachments. has:description, has:cover, has:members, and has:stickers also work
  • due:day -Returns cards due within 24 hours. due:week, due:month, and due:overdue also work
  • created:day -Returns cards created in the last 24 hours. created:week and created:month also work
  • edited:day - Returns cards edited in the last 24 hours. edited:week and edited:month also work
  • description:, checklist:, comment:, and name: - Returns cards matching the text of card descriptions, checklists, comments, or names
  • is:open - returns open cards. is: archived returns archived cards
  • is:starred - Only include cards on starred boards.

Trello has apps for iPhone, iPad, Android phones, tablets, and watches, Kindle Fire Tablets, and Windows 8. Useful to keep track of and get notified anything Important using the apps. Also you can create cards in the app itself no matter wherever you are. You no need to always use pc or laptop to manage your projects.

The data is private and secure. You have full control over who sees our boards. All data is sent over a secure, SSL/HTTPS connection, the same encryption technology used by banks. Trello keep encrypted, off-site backups of your data in case of disasters

Trello provides a simple RESTful web API to use Trello in your own app, plug-in, or extension where each type of resource (e.g. a card, a board, or a member) has a URI that you can interact with.
For example, if you’d like to use the API to get information about the Trello Development Board you’d use the following URI:

https://api.trello.com/1/boards/4d5ea62fd76aa1136000000c
All API requests go to https://api.trello.com
The /1 part of the URI is the API version
The /boards part means that we’re addressing Trello’s collection of boards
The /4d5ea62fd76aa1136000000c part is the id of the board that we want to interact with
to know more https://trello.com/docs/index.html

Here is a collection of boards can be used in both your personal and work life management. All of these boards can be copied and used as a jumping off point for projects of your own.

Link to access those board : https://trello.com/inspiringboards

Reference: https://trello.com