Search code examples
javascriptnode.jsbase32

npm base32 not working. Is it my code?


I was having problems with the base32 npm package. I constructed a minimal script to test the functions ins general but I still get mistakes. Am I blindly missing something here or is the npm package broken?

'use strict';
        
const base32 = require('base32');
const crypto = require('crypto');
        
let val = "";
let encoded = "";
let decoded = "";

for(let i = 0; i < 3; i++) {
  //Generate a random string
  val = crypto.randomBytes(64).toString('hex'); //or base64 instead of hex
  //endode it in base32
  encoded = base32.encode(val);
  //decode it again.
  decoded = base32.decode(val);
          
  //val and decoded should be equal now
  if(decoded !== val)  {
    console.log('FATAL ERROR ' + i);
    console.log('val: ' + val);
    console.log('enc: ' + encoded);
    //The console output of decoded looks like binary rubbish
    console.log('dec: ' + decoded);
  }     
}

Now all the random values result in "val" and "decoded" being different. Shouldn't they be the same? Where is the mistake?


Solution

  • You have to decode the encoded value.

     decoded = base32.decode(encoded);