Securing Plain Text using SHA hashing: SHA-256 Sorcery

Bala Madhusoodhanan - Oct 21 - - Dev Community

Intro

SHA-256 (Secure Hash Algorithm 256-bit) is a widely-used cryptographic hash function that generates a unique, fixed-size 256-bit hash for any given input. It is commonly used to ensure data integrity and security by producing a unique hash value that can be compared to detect any changes in the data.

Keyed hashing with SHA-256 adds an extra layer of security by incorporating a secret key into the hashing process. This method, often referred to as HMAC (Hash-based Message Authentication Code), ensures that only those who possess the secret key can generate or verify the hash, making it significantly more secure against tampering and forgery.

How does Keyed Hashing works:

Image description

Custom Code plugin for custom connector:

using System.IO;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;

public class Script : ScriptBase
{
    public override async Task<HttpResponseMessage> ExecuteAsync()
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

        // Read the request body
        string requestBody = await this.Context.Request.Content.ReadAsStringAsync();
        Console.WriteLine($"Request Body: {requestBody}");
        var input = JsonConvert.DeserializeObject<InputPayload>(requestBody);

        // Check if plainText is provided
        if (string.IsNullOrEmpty(input.PlainText))
        {
            response.StatusCode = HttpStatusCode.BadRequest;
            response.Content = CreateJsonContent("{\"error\": \"String parameter is required.\"}");
            return response;
        }

        // Encrypt the plain text using SHA-256
        string encryptedText = CreateSHA256(input.PlainText, input.Key);

        // Log the plain text and encrypted text
        Console.WriteLine($"Plain Text: {input.PlainText}");
        Console.WriteLine($"Encrypted Text: {encryptedText}");

        // Create JSON response
        var jsonResponse = new
        {
            message = "The text has been encrypted using SHA-256.",
            encryptedText = encryptedText
        };

        response.Content = CreateJsonContent(JsonConvert.SerializeObject(jsonResponse));
        return response;
    }

    public static string CreateSHA256(string input, string key)
    {
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] combinedBytes = new byte[keyBytes.Length + inputBytes.Length];

            Buffer.BlockCopy(keyBytes, 0, combinedBytes, 0, keyBytes.Length);
            Buffer.BlockCopy(inputBytes, 0, combinedBytes, keyBytes.Length, inputBytes.Length);

            byte[] hashBytes = sha256.ComputeHash(combinedBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2")); // Use "x2" for lowercase
            }

            return sb.ToString();
        }
    }

    private static StringContent CreateJsonContent(string json)
    {
        return new StringContent(json, Encoding.UTF8, "application/json");
    }
}

public class InputPayload
{
    public string PlainText { get; set; }
    public string Key { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

Magic show

Demo

Keyed hashing with SHA-256 is particularly useful in scenarios where data integrity and authenticity are critical, such as in secure communications, digital signatures, and authentication systems. By using a secret key, it ensures that even if the data is intercepted, it cannot be altered without detection.

Further Read:

Cryptool Portal is an interactive way to understand SHA-256. You can input text and see the hash generated, along with explanations of the process.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .