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.
- To take the hash of a color, first use utf8ToBytes to translate the string to bytes. Then, use sha256 to hash it.
- 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;
Resource:
Alchemy University: Ethereum Developer Bootcamp
Top comments (1)
It Works and Thank You Bro !