buffer-xor icon indicating copy to clipboard operation
buffer-xor copied to clipboard

BUG -> xor(xor(a, b), a) should be equal to b

Open folkvir opened this issue 6 years ago • 0 comments

XORing 2 Buffers should respect the two following rules:

  • xor(xor(a, b), a) = b
  • xor(xor(a, b), b) = a

When a has more characters than b the second rules is not respected. See your example

var xor = require('buffer-xor')
var a = new Buffer('00ff0f', 'hex')
var b = new Buffer('f0f0', 'hex')
console.log(xor(xor(a, b), b).equals(a)) // true -> 00ff0f
console.log(xor(xor(a, b), a).equals(b)) // false -> f0f000

In hexadecimal '00f0f0' === 'f0f0' , adding leading zeroes is ok, but not trailing zeroes ('f0f0' !== 'F0F000') and you do that here!!

b needs to be of the same length of a before processing it. Otherwise you broke the XOR rule...

It must be done before XORing them. Hence, just add a quick length check before processing them and it will be fine. Then the example need to be updated to var b = Buffer.from('00f0f0', 'hex')

This issue is related to https://github.com/crypto-browserify/buffer-xor/issues/2 But to my mind:

it should treat the shorter array as if it was padded with 0s to the longer array's length

This is correct. But should be treated beforehand! then you can apply the XOR operation

folkvir avatar Jun 19 '19 16:06 folkvir