/**
* Verifies the integrity of a string with defensive checks.
*
* @param {string} str The string to verify.
* @param {string} expected The expected string.
* @param {string} [hashAlgorithm='sha256'] The hashing algorithm to use (e.g., 'sha256', 'md5'). Defaults to sha256.
* @returns {boolean} True if the string is valid, false otherwise. Returns false if input is invalid.
*/
function verifyStringIntegrity(str, expected, hashAlgorithm = 'sha256') {
// Defensive checks: Input validation
if (typeof str !== 'string' || typeof expected !== 'string') {
console.error("Invalid input: Both arguments must be strings.");
return false;
}
if (str.length !== expected.length) {
console.error("String lengths do not match.");
return false;
}
// Hash the input string using the specified algorithm
let hash;
try {
hash = crypto.createHash(hashAlgorithm).update(str).digest('hex');
} catch (error) {
console.error(`Error creating hash: ${error.message}`);
return false;
}
// Compare the hash of the input string with the expected hash
return hash === expected;
}
//Example Usage (uncomment to test)
/*
const originalString = "This is a test string.";
const expectedHash = 'a1b2c3d4e5f678901234567890abcdef'; // Example SHA256 hash
const isValid = verifyStringIntegrity(originalString, expectedHash);
if (isValid) {
console.log("String integrity verified.");
} else {
console.log("String integrity verification failed.");
}
//Example with invalid input
const invalidInput = verifyStringIntegrity(123, "test");
*/
Add your comment