1

Using Node.js crypto module it is quite easy to encrypt/decrypt strings, as string are readily supported. For numbers you would need to use Buffer/TypeArray or DataView types.

How would you encrypt/decrypt JavaScript numbers the most robust/efficient way possible?

Using:

  • crypto.createCipheriv(algorithm, key, iv[, options])
  • 'aes-256-cbc'
  • cipher.update(data[, inputEncoding][, outputEncoding])

1 Answer 1

0

It depends how robust/efficient it needs to be.

Your easiest option would be to just .toString() any numbers and encrypt them as you would a string.

An arguably "faster" way would be to create a buffer of bytes to represent the number. Assuming we have a 16-bit integer (for simplicity):

function toBytes(n) {
    const b1 = n >> 8;
    const b2 = n << 8 >> 8;
    return Buffer.from([b1, b2]);
}

function toNumber(buf) {
    let n = buf[0] << 8;
    n += buf[1];
    return n;
}

for (let i = 254; i < 258; i++) {
    const buf = toBytes(i);
    const n = toNumber(buf);
    console.log(n, "=", buf);
}

This is likely faster, but you'd need to be encrypting a lot of data for it to make a meaningful difference.

6
  • Thanks for the answer. A couple of questions:
    – ile
    Dec 7, 2019 at 20:10
  • .toString() would need a corresponding function to get back to number. Would parseFloat() work in every case?
    – ile
    Dec 7, 2019 at 20:14
  • That buffer example: I'm not sure what type the JS numbers are (64 bit of something maybe, and I'm not sure about endianness, maybe platform dependent). I was looking for an example that would work in every case for JavaScript numbers. Seems like that answer would need to take into account some bigger numbers?
    – ile
    Dec 7, 2019 at 20:14
  • 1
    Also, Node Buffer has functions like these: - buf.writeBigInt64BE(value[, offset]) - buf.writeBigInt64LE(value[, offset]) Wouldn't they help? nodejs.org/api/…
    – ile
    Dec 7, 2019 at 20:19
  • @ile "numbers" in javascript are mostly just 64bit floats. you'd also need to do more bit-fiddling if you want more than 2**16 values
    – Sam Mason
    Dec 11, 2019 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.