Logo

dev-resources.site

for different kinds of informations.

Securing Plain Text using SHA hashing: SHA-256 Sorcery

Published at
10/21/2024
Categories
powerautomate
powerfuldevs
csharp
security
Author
balagmadhu
Author
10 person written this
balagmadhu
open
Securing Plain Text using SHA hashing: SHA-256 Sorcery

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.

powerfuldevs Article's
30 articles in total
Favicon
The Rise of AI Agents: Understanding the Revolution and Adapting to Change
Favicon
Google and Anthropic are working on AI agents - so I made an open source alternative
Favicon
Power BI vs Tableau vs Looker vs Qlik: A detailed comparison between top data visualization tools
Favicon
Finding the Right Microsoft Platform for Your Applications
Favicon
Top Advanced Power BI Features for Your Business
Favicon
Decoding Microsoft Integration Tools:Which One is Right for You?
Favicon
For A Despicably Good Cause : Small Steps, Big Impact!
Favicon
From Template to Tailored:The Power Platform Way
Favicon
Why You Should Hire a Power BI Developer for Your Business
Favicon
Never code lines on the HTML canvas again
Favicon
From Vanar Sena to Low Code Champions: Lessons from the Ramayana for Digital Transformation
Favicon
From Scribbles to Spells: Perfecting Instructions in Copilot Studio
Favicon
Securing Plain Text using SHA hashing: SHA-256 Sorcery
Favicon
Transforming Inventory Management with Power BI Dashboards in 2024
Favicon
Guรญa Paso a Paso para Realizar una Portabilidad Telefรณnica Empresarial
Favicon
Low-Code, Big Risks: Why Security Awareness is Crucial for Citizen Developers
Favicon
How to Build an AI Agent to Automate Mobile Auto Repair Task Scheduling
Favicon
๐Ÿ’ธ Make Money with Your AI Agent
Favicon
Writing Clean Code in Ruby on Rails Applications ๐Ÿงผ๐Ÿ’ป
Favicon
ALWAYS A DATA NERD
Favicon
Dataverse Solution Checker doesn't like PCFs
Favicon
Permission and Data Security in No-Code: Why it matters and How to control
Favicon
Best Tool for Query anything with SQL
Favicon
Unveiling the Mysteries: Dataverse API
Favicon
Guide: How to add Write-Back capabilities to Power BI reports with Power Apps โ€” Part 2
Favicon
Guide: How to add Write-Back capabilities to your Power BI reports with Power Appsโ€Š-โ€ŠPartย 1
Favicon
Draw on the HTML canvas without code
Favicon
The Impact of Low-Code/No-Code Tools on Traditional Software Development
Favicon
Microsoft Power BI Consulting & Development Services
Favicon
๐Ÿš€ Embed Formbricks Forms in Webflow in Minutes โ€” No Code, Just Magic! ๐Ÿ’ปโœจ

Featured ones: