usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

C# Hashing Algorithms: Implementing One-Way Encryption



Understanding Hashes in C#

In modern web development, ensuring data authenticity and integrity is critical. While many developers rely on standard libraries, understanding the mechanics of a custom JS hash function allows for specialized applications like digital signatures and secure message authentication.

This guide explores a unique approach to mathematical hashing in C#, utilizing recurrence series and large-scale integer manipulation.

What is a One-Way Hash? | Explanation for C# Kids

A one-way hash is a cryptographic function that transforms an input into a unique string of characters. It is designed to be non-revertible encryption; you can easily generate a hash from a message, but it is computationally impossible to reconstruct the original message from the hash. This makes it ideal for verifying data without exposing the raw information.


The Mathematical Foundation for the C# Hash Algorithm

The core of this algorithm is based on a specific mathematical recurrence series. By applying a formula to the character codes of a string, we create a high-entropy output.

The Recurrence Equation | Maths Explanation for C# Kids

The algorithm utilizes the following series to generate the hash weight:

$$ T_n = (n-2)t_1 + 2^n $$

Where:

  • $n$ represents the position of the character.
  • $t_1$ is the initial seed or value derived from the character code.

Implementing the Custom Hash in C#

To ensure precision during complex calculations, we utilize a C# BigInteger approach. This prevents rounding errors often found in standard floating-point arithmetic when dealing with large numbers.

Key Features of the C# Hash Implementation:

  1. Character Code Processing: Using `charCodeAt`, the algorithm iterates through each string element to gather raw data.
  2. Bitwise Rotation: To increase security, the output undergoes a bitwise rotation based on the modulo of the recurrence result, ensuring that small changes in input (avalanche effect) result in vastly different hashes.
  3. Digital Signatures: The resulting hash can be used as a signature to verify that a file or message has not been altered.

Create a new C# class file;
Call it Hashes.
Type out the adjoining C# Hashing Algorithm.


Important: BigInteger is inbuilt in C#.
You only need to use the System.Numerics library.

You might have to add the above library in the reference section - Project >> Add Reference...; tick off System.Numerics - to be able to use it.


Why Use Custom Mathematical Hashing? | Explanation for C# Kids

Implementing tertiary level C# math in your security protocols offers several benefits:

  • No Dependencies: Perform secure checks without bloating your project with external libraries.
  • Educational Insight: Gain a deeper understanding of how cryptographic authenticity is calculated at a low level.
  • Performance: Tailored algorithms can be optimized for specific data types, providing faster verification for niche applications.

Hashing vs Encryption | Explanation for C# Kids

Although hashing and encryption are sometimes confused, they serve different purposes.

  • Encryption is reversible. Encrypted data can be decrypted using a key.
  • Hashing is non-reversible. Once data is hashed, it cannot be restored to its original form.

This distinction makes hashing particularly suitable for sensitive data such as passwords, where systems only need to verify correctness rather than retrieve the original value.


Properties of a Good Hash Algorithm | Explanation for C# Kids

  • Deterministic: The same input always produces the same output.
  • Collision Resistant: Different inputs should not produce the same hash.
  • Non-Reversible: Hashes cannot be converted back to the original input.
  • Efficient: Quick to compute even for large inputs.

Applications of Hashing in C#

C# hashing is commonly used in a variety of real-world scenarios:

  • Password verification: Systems store hashed passwords instead of plaintext values
  • Data integrity checks: Hashes ensure data has not been altered
  • Authentication mechanisms: Hashes help verify user credentials securely
  • Digital signatures: Hash values confirm message authenticity

In each case, hashing allows systems to confirm data validity without exposing sensitive information.


Hash Collisions and Their Implications

A hash collision occurs when two different inputs produce the same hash output. While collisions are theoretically unavoidable, good hash algorithms make them extremely rare.

In practice, collision resistance is essential for maintaining trust in systems that rely on hashes for security and verification.

Summary: C# Hashing Algorithm

Hashes in C# provide a secure and efficient way to represent data using one-way hash functions. By producing fixed-length, non-reversible outputs, hash algorithms play a critical role in data security, authentication, and integrity verification.

Understanding how C# hash functions work - and when to use them - is essential for building reliable and secure web applications.










C# Code for Hashes - Class File

using System;
using System.Numerics;
using System.Globalization;

namespace Miscellaneous
{
    class Hashes
    {

        public Hashes()
        {
        }

        public String hashWord(char[] msg)
        {
            // encoding eqn { Tn = (n-2)t1 + 2^n } - please use your own eqn
            String hash = "";
            BigInteger big_hash = 0;
            int n;
            int t1;
            BigInteger x;
            for (int i = 0; i < msg.Length; i++)
            {
                // get unicode of this character as n
                n = (int)msg[i];
                t1 = i + 1;
                // use recurrence series equation to hash
                x = BigInteger.Add(BigInteger.Multiply(n-2, t1), BigInteger.Pow(2, n));
                if (i == 0)
                {
                    hash = x.ToString();
                    big_hash = x;
                    continue;
                }

                // convert number from base 10 to base 2
                string binary = "";
                BigInteger remainder = 0;
                do
                {
                    big_hash = BigInteger.DivRem(big_hash, 2, out remainder);
                    binary = remainder.ToString() + binary;
                } while (!big_hash.Equals(BigInteger.Zero));

                // bitwise rotate left with the modulo of x
                x = BigInteger.Remainder(x, binary.Length);

                char[] slice_1 = binary.Substring((int)x).ToCharArray();
                // keep as '1' to preserve hash size
                slice_1[0] = '1';

                string slice_2 = binary.Substring(0, (int)x);

                hash = String.Join("", slice_1) + slice_2;

                // convert number from base 2 to base 10
                big_hash = 0; // not necessary; just stating the obvious
                int j = 0;
                while (j < hash.Length)
                {
                    big_hash = BigInteger.Add(BigInteger.Multiply(int.Parse(hash[j].ToString()), BigInteger.Pow(2, hash.Length - 1 - j)), big_hash);
                    j++;
                }
            }
            hash = big_hash.ToString("X");
            hash = hash.ToUpper();

            return hash;
        }
    }
}


C# Code for Hashes - Main Class

using System;
using System.Numerics;
using System.Collections.Generic;

namespace Miscellaneous
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] message = "merry xmas".ToCharArray();

            Hashes one_way = new Hashes();
            String hashed = one_way.hashWord(message);

            Console.WriteLine("Message is '" + String.Join("", message) +
                "';\nMessage hash is " + hashed);
        }
    }
}





<< PreviousNext >>