diff --git a/src/util.js b/src/util.js index 78394ad4..f2d8bdef 100644 --- a/src/util.js +++ b/src/util.js @@ -85,12 +85,9 @@ export default { readNumber: function (bytes) { var n = 0; - for (var i = 0; i < bytes.length; i++) { - n <<= 8; - n += bytes[i]; + n += Math.pow(256, i) * bytes[bytes.length - 1 - i]; } - return n; }, diff --git a/test/general/util.js b/test/general/util.js index d805eef1..06d75bb6 100644 --- a/test/general/util.js +++ b/test/general/util.js @@ -185,6 +185,12 @@ describe('Util unit tests', function() { var test = openpgp.util.decode_utf8.bind(null, {chameleon: true}); expect(test).to.throw(Error, /Parameter "utf8" is not of type string/); }); + it('util.readNumber should not overflow until full range of uint32', function () { + var ints = [Math.pow(2, 20), Math.pow(2, 25), Math.pow(2, 30), Math.pow(2, 32) - 1]; + for(var i = 0; i < ints.length; i++) { + expect(openpgp.util.readNumber(openpgp.util.writeNumber(ints[i], 4))).to.equal(ints[i]); + } + }); }); });