const crypto = require('crypto');
// Function to generate random string
function generateRandomString(length) {
return crypto.randomBytes(length).toString('hex').substring(0, length);
}
// Function to find a partial hash collision (first few characters match)
function findPartialCollision(targetLength) {
const hashMap = new Map();
let attempts = 0;
console.log(`Searching for partial SHA-256 collisions (first ${targetLength} characters)...`);
while (true) {
attempts++;
// Generate a random input
const input = generateRandomString(8);
// Hash the input
const hash = crypto.createHash('sha256').update(input).digest('hex');
// Get the target portion of the hash
const targetPortion = hash.substring(0, targetLength);
// Check if we've seen this target portion before
if (hashMap.has(targetPortion)) {
const previousInput = hashMap.get(targetPortion);
console.log(`Found a collision after ${attempts} attempts!`);
console.log(`Input 1: "${previousInput}"`);
console.log(`Input 2: "${input}"`);
console.log(`SHA-256 (Input 1): ${crypto.createHash('sha256').update(previousInput).digest('hex')}`);
console.log(`SHA-256 (Input 2): ${hash}`);
console.log(`Both hashes start with: ${targetPortion}`);
return {
attempts,
input1: previousInput,
input2: input,
collidingPrefix: targetPortion
};
}
// Store this hash
hashMap.set(targetPortion, input);
// Show progress
if (attempts % 100000 === 0) {
console.log(`Checked ${attempts} values, ${hashMap.size} unique prefixes found...`);
}
// Safety limit
if (attempts >= 1000000) {
console.log('Reached attempt limit without finding a collision.');
break;
}
}
return { attempts, collisionFound: false };
}
// Find a collision for the first few characters (increase for more challenge)
findPartialCollision(4);
// Note: Finding a full collision for SHA-256 is computationally infeasible
// This example only demonstrates partial collisions