Skip to content

Instantly share code, notes, and snippets.

@chjj
Last active February 18, 2016 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chjj/1d26c818f2e20afcc33d to your computer and use it in GitHub Desktop.
Save chjj/1d26c818f2e20afcc33d to your computer and use it in GitHub Desktop.
exports.normalize = function normalize(signature) {
var data, p, len, rlen, slen;
if (Buffer.isBuffer(signature))
signature = Array.prototype.slice.call(signature);
else if (typeof signature === 'string')
signature = utils.toArray(signature, 'hex');
data = signature.slice();
p = { place: 0 };
if (data[p.place++] !== 0x30)
return signature;
len = getLength(data, p);
if (data.length > len + p.place)
data = data.slice(0, len + p.place);
if (data[p.place++] !== 0x02)
return signature;
rlen = getLength(data, p);
p.place += rlen;
if (data[p.place++] !== 0x02)
return signature;
slen = getLength(data, p);
if (data.length > slen + p.place)
data = data.slice(0, slen + p.place);
return data;
};
function getLength(buf, p) {
var initial = buf[p.place++];
if (!(initial & 0x80)) {
return initial;
}
var octetLen = initial & 0xf;
var val = 0;
for (var i = 0, off = p.place; i < octetLen; i++, off++) {
val <<= 8;
val |= buf[off];
}
p.place = off;
return val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment