mirror of
https://github.com/billbuchanan/appliedcrypto.git
synced 2026-02-22 03:37:57 +00:00
37 lines
911 B
JavaScript
37 lines
911 B
JavaScript
var crypto = require('crypto');
|
|
|
|
// Node.js has its own Crypto function that can handle this natively
|
|
var sha256 = module.exports = function(message, options) {
|
|
var c = crypto.createHash('sha256');
|
|
|
|
if (Buffer.isBuffer(message)) {
|
|
c.update(message);
|
|
} else if (Array.isArray(message)) {
|
|
// Array of byte values
|
|
c.update(new Buffer(message));
|
|
} else {
|
|
// Otherwise, treat as a binary string
|
|
c.update(new Buffer(message, 'binary'));
|
|
}
|
|
var buf = c.digest();
|
|
|
|
if (options && options.asBytes) {
|
|
// Array of bytes as decimal integers
|
|
var a = [];
|
|
for(var i = 0; i < buf.length; i++) {
|
|
a.push(buf[i]);
|
|
}
|
|
return a;
|
|
} else if (options && options.asString) {
|
|
// Binary string
|
|
return buf.toString('binary');
|
|
} else {
|
|
// String of hex characters
|
|
return buf.toString('hex');
|
|
}
|
|
}
|
|
|
|
sha256.x2 = function(message, options) {
|
|
return sha256(sha256(message, { asBytes:true }), options)
|
|
}
|