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.

powerautomate Article's
30 articles in total
Favicon
Building a Smart Feedback Agent with Copilot Studio, Adaptive cards and Power Automate
Favicon
How to Publish a Power Platform Connector
Favicon
Looking for a mentor who could lead me to a right way for RPA developers
Favicon
How to Shutdown Azure VM
Favicon
The Art of Over Engineering on the Power Platform
Favicon
Invoke an HTTP request without a premium license: connectors summary
Favicon
What is Power Automate: A Complete Guide
Favicon
Get SharePoint library info from Teams context
Favicon
Think You Know Teams Chats? Discover the Workflows
Favicon
AWS Resource Listing Script: A DevOps Shell Scripting Project
Favicon
From Template to Tailored:The Power Platform Way
Favicon
Power Automate vs UiPath: Choosing the right automation tool
Favicon
Hacking Excel Files in Power Automate
Favicon
My Power Platform - Your Year in a Dashboard
Favicon
Power Automate - Handling XML
Favicon
Let's Talk About the Power Platform Dataverse For Teams
Favicon
Securing Plain Text using SHA hashing: SHA-256 Sorcery
Favicon
Mastering Tiered Pricing for Business Growth: A Detailed Guide
Favicon
Dataverse Security Roles
Favicon
Becoming a Power Platform Developer: A Beginner’s Guide
Favicon
Power Platform - Direct to Prod?
Favicon
Power Automate - How to Fix Missing Dependencies
Favicon
Power Automate - Expressions
Favicon
Updating SharePoint items without modifying System columns
Favicon
Power Automate - The Code Review Onion
Favicon
Use Client API Object model in Power Apps
Favicon
Power Up Your SharePoint Embedded Solutions with the Starter Kit
Favicon
Data Source Environment Variables in Power Automate actions
Favicon
Simplify Workflows Using Microsoft Power Automate and Syntex
Favicon
Extract table data from Documents using Azure AI Document Intelligence

Featured ones: