Tuesday, October 27, 2015

Steve Jobs explains what Object Oriented Programming is in Rolling Stone interview 1994

Interviewer: Would you explain, in simple terms, exactly what object-oriented software is?


Steve Jobs: Objects are like people. They're living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things. And rather than interacting with them at a very low level, you interact with them at a very high level of abstraction, like we're doing right here.

Here's an example: If I'm your laundry object, you can give me your dirty clothes and send me a message that says, "Can you get my clothes laundered, please." I happen to know where the best laundry place in San Francisco is. And I speak English, and I have dollars in my pockets. So I go out and hail a taxicab and tell the driver to take me to this place in San Francisco. I go get your clothes laundered, I jump back in the cab, I get back here. I give you your clean clothes and say, "Here are your clean clothes."

You have no idea how I did that. You have no knowledge of the laundry place. Maybe you speak French, and you can't even hail a taxi. You can't pay for one, you don't have dollars in your pocket. Yet I knew how to do all of that. And you didn't have to know any of it. All that complexity was hidden inside of me, and we were able to interact at a very high level of abstraction. That's what objects are. They encapsulate complexity, and the interfaces to that complexity are high level.

Monday, October 26, 2015

Project Euler Solution using C#: Problem 29 : Distinct powers

Problem:

Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?

Solution:
static void Main(string[] args)
{
    var aMin = 2;
    var aMax = 100;

    var bMin = 2;
    var bMax = 100;

    List lst = new List();

    for (int a = aMin; a <= aMax; a++)
    {
        for (int b = bMin; b <= bMax; b++)
        {
            lst.Add(Math.Pow(a, b));
        }
    }

    var distinctRslt = lst.Distinct().ToList();
    distinctRslt.Sort();

    Console.WriteLine("Result : " + distinctRslt.Count());
    Console.ReadLine();
}

Output :

Wednesday, October 21, 2015

(Solved) Error: Unable to make the session state request to the session state server

Error:

Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.  If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.

Solution:

1. Go to Run command, type services.msc



2. Right click over the ASP.NET State Service and click Start or Restart if it is already Started.




Note:
You could set the service to automatic so that it will work after a reboot.

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

Thursday, October 8, 2015

(Solved) Error: Memory gates checking failed because the free memory (201310208 bytes) is less than 5% of total memory

Error:
Memory gates checking failed because the free memory (201310208 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Solution:
To solve the above error, Add or update the below line in the Web.Config file.
<system.serviceModel>
    <serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0"/>
</system.serviceModel>
Read more about serviceHostingEnvironment
https://msdn.microsoft.com/en-us/library/ms731336(v=vs.110).aspx