John James
John James

Reputation: 657

Cipher and decipher a number into hex in nodejs

I am looking for an efficient way to cypher and decypher a number using the same key. This is not used for cryptography or encrypting anything so it doesn't need to be secure.

I have a unique number and I always want the same result out of the cypher. The cypher shouldn't be too long (more than 6 characters). I do care about the speed as I will be making roughly 1000/millisecond cyphers.

The max number I will be looking to cypher is 100,000,000 and considering the alphanumeric = 26 lowercase letters + 26 uppercase letters and 10 numbers for 6 characters that's about 5.680 * 10^9 combinations which should suffice.

Example of pseudocode:

let num_to_cypher = 1;
let cypher = cypher_this_number(num_to_cypher); // ==> Ax53iw
let decypher = decypher_this_number(cypher); // ==> 1

let num_to_cypher_ex_2 = 12
let cypher_ex_2 = cypher_this_number(num_to_cypher_ex_2); // ==> 2R5ty6
let decypher_ex_2 = decypher_this_number(cypher_ex_2); // ==> 1

Edit 1:

I could have done something like below, but I can't define the cypher's length in this example and I don't care about encryption so I could go with something faster.

function encrypt(text){
    let cipher = crypto.createCipher('aes128','d6F3Efeq')
    let crypted = cipher.update(text,'utf8','hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text){
    let decipher = crypto.createDecipher('aes128','d6F3Efeq')
    let dec = decipher.update(text,'hex','utf8')
    dec += decipher.final('utf8');
    return dec;
}

Upvotes: 0

Views: 667

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74315

I would use a good hash function. These 2 algorithms are pretty decent hash algorithms:

[Edited to note...]

Since it seems that you want a 2-way encoding, Base-64 is probably your friend here.

This will encode and decode any 32-bit signed integer value (ranging from -2,147,483,648 through +2,147,483,647 into 6 characters.

const {Buffer} = require('buffer');

const buf = Buffer.alloc(4);
const pad = [ '' , '', '==' , '=' ];

const MIN_INT32 = -2_147_483_648; // 0x80000000
const MAX_INT32 = +2_147_483_647; // 0x7FFFFFFF

function encode(n) {

    if ( !Number.isInteger(n) || n < MIN_INT32 || n > MAX_INT32 ) {
        throw new RangeError("n must be a valid 32-bit integer such that m is -2,147,483,648 >= m <= +2,147,483,647");
    }

    buf.writeInt32BE(n) ;

    const b64 = buf.toString('base64').slice(0,-2);
    return b64;
}

function decode(s) {
    const b64 = s + pad[ s.length % 4 ];

    buf.fill(b64, 'base64');

    const n = buf.readInt32BE();
    return n;
}

With that, it's a simple matter of:

onst n0 = 123_456_789;
const b64 = encode(n0);
const n1 = decode(b64);

console.log(`original: ${n0}`  ) ;
console.log(`encoded:  ${b64}` ) ;
console.log(`decoded:  ${n1}`  ) ;

Which produces:

original: 123456789
encoded:  B1vNFQ
decoded:  123456789

Upvotes: 1

Related Questions