Tuesday, 18 April 2017

bytes to hexadecimal and hexadecimal to bytes in nodejs

I have a generated random 16bytes using

var crypto = require('crypto');
iv   = crypto.randomBytes(16);

If I console.log iv, it prints like this

<Buffer 54 8e 09 f7 03 56 a1 23 75 94 fb e4 89 e3 36 84>

When I user iv.toString('hex') function, it prints

548e09f70356a1237594fbe489e33684

Now again I want to convert the above string back to the original i.e convert 548e09f70356a1237594fbe489e33684 to

<Buffer 54 8e 09 f7 03 56 a1 23 75 94 fb e4 89 e3 36 84>

I try like this:-

  var buffer_data = new Buffer(res_iv);
      console.log(buffer_data);

It generates the wrong O/P <Buffer 35 34 38 65 30 39 66 37 30 33 35 36 61 31 32 33 37 35 39 34 66 62 65 34 38 39 65 33 33 36 38 34>

Also try to use

var convertHex = require('convert-hex'); 

but not able to get the required output

Any one knows how can I achieve this ?



via VIKAS KOHLI

No comments:

Post a Comment