Search code examples
javascriptxorcryptojs

XOR with crypto's randomBytes


I want to create a master key where I XOR 3 random keys (generated with crypto.randomBytes).

A,B,C = crypto.randomBytes(32)
MASTER_KEY = A ^ B ^ C;

I am not sure how to make this work in Javascript. randomBytes returns a Buffer. I'm not sure if I have to do a .toString() on it or just perform the XOR as a Buffer?


Solution

  • This should do:

    const BUF_LEN = 32
    const result = Buffer.alloc(BUF_LEN)
    
    for (let i = 0; i < BUF_LEN; i++) {
      const [a, b, c] = [A.readUInt8(i), B.readUInt8(i), C.readUInt8(i)]
      result.writeUInt8(a ^ b ^ c, i)
    }
    
    console.log(result.toString('hex'))