ile
ile

Reputation: 1805

How would you encrypt/decrypt numbers in Node.js?

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:

Upvotes: 1

Views: 1798

Answers (1)

Luke Joshua Park
Luke Joshua Park

Reputation: 9806

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.

Upvotes: 0

Related Questions