Skip to content

Instantly share code, notes, and snippets.

@ansemjo
Created January 6, 2017 14:39
Show Gist options
  • Save ansemjo/13ab7315878f23bd92264d380ad79af8 to your computer and use it in GitHub Desktop.
Save ansemjo/13ab7315878f23bd92264d380ad79af8 to your computer and use it in GitHub Desktop.
Hashing wrapper in TypeScript, which can use stable-stringify to convert any object to a UUID or just make hashing a little easier.
/** For use in node.js environments.
* Requires npm packages:
* "@types/json-stable-stringify": "^1.0.29"
* "json-stable-stringify": "^1.0.1"
* "@types/uuid": "^2.0.29"
* "uuid": "^3.0.1"
*/
import * as uuid from 'uuid';
import * as crypto from 'crypto';
import * as stringify from 'json-stable-stringify';
type Data = string | Buffer;
type Algorithm = 'sha224' | 'sha256' | 'sha384' | 'sha512';
type Encoding = 'hex' | 'base64' | 'latin1';
/** Create a SHA384 digest from a string or Buffer.
* @param data String or Buffer to be hashed.
*/
export function hash(data: Data): Buffer;
/** Create a hash digest from a string or Buffer.
* @param data String or Buffer to be hashed.
* @param algorithm Hashing algorithm.
*/
export function hash(data: Data, algorithm: Algorithm): Buffer;
/** Create a SHA384 digest from a string or Buffer.
* @param data String or Buffer to be hashed.
* @param encoding Output encoding.
*/
export function hash(data: Data, encoding: Encoding): string;
/** Create a hash digest from a string or Buffer.
* @param data String or Buffer to be hashed.
* @param algorithm Hashing algorithm.
* @param encoding Output encoding.
*/
export function hash(data: Data, algorithm: Algorithm, encoding: Encoding): string;
/** Create a SHA384 digest from any data and convert to a UUID.
* @param data Hashable data.
* @param encoding Output encoding (UUID).
*/
export function hash(data: any, encoding: 'uuid'): string;
/** Create a hash digest from any data and convert to a UUID.
* @param data Hashable data.
* @param algorithm Hashing algorithm.
* @param encoding Output encoding (UUID).
*/
export function hash(data: any, algorithm: Algorithm, encoding: 'uuid'): string;
/** Implementation of the above. */
export function hash (data: any, algorithm?: Algorithm | Encoding | 'uuid', encoding?: Encoding | 'uuid'): any {
if (algorithm !== undefined &&
['hex', 'base64', 'latin1', 'uuid'].indexOf(algorithm) !== -1) {
encoding = <Encoding>algorithm;
algorithm = 'sha384';
} else if (algorithm === undefined) {
algorithm = 'sha384';
}
if (encoding === 'uuid') {
const json = stringify(data);
const digest = hash(json, <Algorithm>algorithm);
return uuid.v4({ random: Array.from(digest.slice(0, 16)) });
} else {
return crypto.createHash(algorithm).update(data).digest(encoding);
};
};
export default hash;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment