1. /**
  2. * Verifies the integrity of a string with defensive checks.
  3. *
  4. * @param {string} str The string to verify.
  5. * @param {string} expected The expected string.
  6. * @param {string} [hashAlgorithm='sha256'] The hashing algorithm to use (e.g., 'sha256', 'md5'). Defaults to sha256.
  7. * @returns {boolean} True if the string is valid, false otherwise. Returns false if input is invalid.
  8. */
  9. function verifyStringIntegrity(str, expected, hashAlgorithm = 'sha256') {
  10. // Defensive checks: Input validation
  11. if (typeof str !== 'string' || typeof expected !== 'string') {
  12. console.error("Invalid input: Both arguments must be strings.");
  13. return false;
  14. }
  15. if (str.length !== expected.length) {
  16. console.error("String lengths do not match.");
  17. return false;
  18. }
  19. // Hash the input string using the specified algorithm
  20. let hash;
  21. try {
  22. hash = crypto.createHash(hashAlgorithm).update(str).digest('hex');
  23. } catch (error) {
  24. console.error(`Error creating hash: ${error.message}`);
  25. return false;
  26. }
  27. // Compare the hash of the input string with the expected hash
  28. return hash === expected;
  29. }
  30. //Example Usage (uncomment to test)
  31. /*
  32. const originalString = "This is a test string.";
  33. const expectedHash = 'a1b2c3d4e5f678901234567890abcdef'; // Example SHA256 hash
  34. const isValid = verifyStringIntegrity(originalString, expectedHash);
  35. if (isValid) {
  36. console.log("String integrity verified.");
  37. } else {
  38. console.log("String integrity verification failed.");
  39. }
  40. //Example with invalid input
  41. const invalidInput = verifyStringIntegrity(123, "test");
  42. */

Add your comment