-
-
Notifications
You must be signed in to change notification settings - Fork 198
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support for hashing Unicode data by using Buffers
Previously, all hashing algorithms were converting string data to binary using a naive approach that did not support non-ASCII input. This change converts input into a Buffer which properly handles Unicode data. This change also fixes the interface on createHash and createHmac to properly return a Buffer object by default, which the Node.js API does. * Updated tests to ensure that hash functions work with Unicode * createHash()/createHmac() now returns a Buffer to match Node.js API * Refactored index.js and hash implementations to reduce duplication
- Loading branch information
Showing
5 changed files
with
86 additions
and
380 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
var Buffer = require('buffer').Buffer; | ||
var intSize = 4; | ||
var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); | ||
var chrsz = 8; | ||
|
||
function toArray(buf, bigEndian) { | ||
if ((buf.length % intSize) !== 0) { | ||
var len = buf.length + (intSize - (buf.length % intSize)); | ||
buf = Buffer.concat([buf, zeroBuffer], len); | ||
} | ||
|
||
var arr = []; | ||
var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; | ||
for (var i = 0; i < buf.length; i += intSize) { | ||
arr.push(fn.call(buf, i)); | ||
} | ||
return arr; | ||
} | ||
|
||
function toBuffer(arr, size, bigEndian) { | ||
var buf = new Buffer(size); | ||
var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; | ||
for (var i = 0; i < arr.length; i++) { | ||
fn.call(buf, arr[i], i * 4, true); | ||
} | ||
return buf; | ||
} | ||
|
||
function hash(buf, fn, hashSize, bigEndian) { | ||
if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); | ||
var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); | ||
return toBuffer(arr, hashSize, bigEndian); | ||
} | ||
|
||
module.exports = { hash: hash }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.