Use cases

  • Verifying if a string has been changed

node version

  • 8.11.2

JavaScript Version

  • ECMAScript 6 and higher

Installation

  • crypto is is a native node module, no installation is required
  • Winston logger

Example Code for JavaScript String Hashing using SHA-512, BASE64 and UTF-8 encoding

/**
 * An example for hashing of a String featuring:
 * - An out of the box working Example
 * - sha-512 digest
 * - Utf8 Encoding of Strings
 * - Base64 String encoding of digest
 * - Logging of exceptions
 */

var crypto = require("crypto"),
  winston = require("winston");

const logger = winston.createLogger({
  format: winston.format.combine(
    winston.format.splat(),
    winston.format.simple()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.simple(),
      handleExceptions: true
    })
  ]
});

const demonstrateHash = () => {
  try {
    // replace with your actual Strings
    let exampleString =
      "Text that should be authenticated by comparing the hash of it!";
    let exampleString2 =
      "Text that should be authenticated by comparing the hash of it! - 2";
    //create a hash object
    let hashObject = crypto.createHash("sha512");
    hashObject.setEncoding("base64");
    //update the hash object with data as often as required
    hashObject.write(exampleString);
    hashObject.write(exampleString2);
    hashObject.end();
    // create the hash values
    let digest = hashObject.read();

    logger.info("Digest of the Strings: %s", digest);
  } catch (error) {
    logger.error(error.message);
  }
};

demonstrateHash();

// for unit testing purposes
module.exports = { demonstrateHash, logger };

References

Authors

Tobias Hirzel

Reviews

Tags: