DEV Community

Jennifer Tieu
Jennifer Tieu

Posted on • Edited on

7 1

Cryptographic Hashes: Find A Favorite Color

Alchemy University Ethereum Developer Bootcamp Week one course continued with a cryptographic hashes exercise to find a favorite color.

Disclaimer: Most of the content below is a general summary and retelling of the information from the course.

Brute Force Hashing

"Cryptographic Hash Functions like SHA256 are one-way functions." This means it's easy to generate (or "find") the output from the input, but almost impossible to find the input from the output.

However, you can brute-force guess the output if you know the hashes of common inputs or create a "Rainbow Table" to determine what that input is.

Note: For security purposes, it's important to remember to use a random salt which you can add to your input to make it unguessable via the methods mentioned above!

Exercise Goal: Find the Color

Given a SHA256 hash, find the color input that would generate that hash. You can assume that all the hashes be generated only from colors provided in the COLORS array.

  1. To take the hash of a color, first use utf8ToBytes to translate the string to bytes. Then, use sha256 to hash it.
  2. When you want to compare two hashes, first use toHex to turn each hash from a Uint8Array to a string of hexadecimal characters.

My Solution:

const { sha256 } = require("ethereum-cryptography/sha256");
const { toHex, utf8ToBytes } = require("ethereum-cryptography/utils");

// the possible colors that the hash could represent
const COLORS = ['red', 'green', 'blue', 'yellow', 'pink', 'orange'];

// given a hash, return the color that created the hash
function findColor(hash) {
    for (let i=0; i < COLORS.length;i++){
        let color = COLORS[i];
        // translate string to bytes
        let colorBytes = utf8ToBytes(color);
        // hash string
        let colorHash = sha256(colorBytes);
        // compare hashes
        if (toHex(hash) === toHex(colorHash)){
            return color;
        }
    }
}

module.exports = findColor;
Enter fullscreen mode Exit fullscreen mode

Resource:

Alchemy University: Ethereum Developer Bootcamp

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
devdepinto profile image
devde pinto

I think this much advanced for me, I'm just started and I need basic knowncements first. But ty

Collapse
 
shrenath1903 profile image
Shrenath1903

It Works and Thank You Bro !

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post