Home > database >  Javascript - Getting null when I expect number
Javascript - Getting null when I expect number

Time:07-18

I have some Javascript that hashes. msgBuffer definitely has bytes in it after the hash, but in the following code, the nonce ends up null. What do I need to do to add the first byte of msgBuffer to the nonce?

    var msgBuffer = await crypto.subtle.digest('SHA-256', toHash); //returns ArrayBuffer
    var nonce = 0;
    nonce  = msgBuffer[0]; // results in null

CodePudding user response:

await crypto.subtle.digest('SHA-256', toHash) would return ArrayBuffer.

You should first convert it to proper type, and then get the value.

e.g. do this.

var msgBuffer = await crypto.subtle.digest('SHA-256', toHash);
var myArr = new Uint8Array(msgBuffer);
var nonce = 0;
nonce  = myArr[0];

I used Uint8Array, here because for crypto.subtle.digest this seems an appropriate choice, but for other use cases and types you expect in an ArrayBuffer in general, you should use the type array views.

  • Related