1

I am a little lost on this one...

I have a special key i need to send to a device in a specified format, and i know that what i am doing is wrong - obviously, because i lack the basic understanding of bit stuff in Javascript, i think.

The first step is to generate a random 128 bit number. Since afaik JS characters are 16 bit, the following code should generate a 128 bit string, doesn't it?

private generateSeed()
{
  let result = '';

  for(let i = 0; i < 8; i++)
    result += ((Math.random() * 10) - 1).toString();

  return result;
}

After that i need to concatenate the seed and the key, calculate the SHA1 of that and padd that SHA1 to 192 bit with zeroes.

enter image description here

private generateAKey(seed: string)
  {
    const Provided_KEY = '[32 random characters are in here]';
    let concat = seed + Provided_KEY;

    let sha1 = crypto.SHA1(concat).toString();
    console.log(`SHA1: ${sha1} , Length: ${sha1.length}`);

    // Padd to 192 bit/24 bytes
    while(sha1.length < 12)
      sha1 += '0';

    return sha1;
  }

But i am totally lost here. I am pretty sure i am wrong with that. Also since the SHA1 i calculate with crypto-js is already 40 characters long this makes no sense for me.

How do i correctly do this?

Velulian
  • 313
  • 5
  • 15
  • 1
    `((Math.random() * 10) - 1).toString()` doesn't really make sense. – Bergi Jul 11 '19 at 21:39
  • Usually with the crypto libraries, you need to make use of Uint8Arrays. To generate exactly 16 bytes (or 16 bytes * 8 bits/byte = 128 bits) of random data, you can use something along the lines of... `x = new Uint8Array(16); for (let i = 0; i < x.length; i++) { x[i] = Math.floor(Math.random() * 256)} console.log(x);` – Trentium Jul 12 '19 at 19:14
  • BTW, if you need to convert the Uint8Array to a utf-8 string, you can apply the following... `var str = new TextDecoder("utf-8").decode(x);` See https://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript for more examples. – Trentium Jul 12 '19 at 19:27
  • 1
    Sorry about the peppering of comments... Regarding sha1, it is a 20 byte hash. If you're seeing 40 bytes, it likely due to the hash value being converted into the hexadecimal representation. Eg, a byte value of 255 is equivalent to "FF" hex. If the key your sending requires a 192 bit (24 byte) padded sha1 hash, then it's looking for the byte-by-byte value of the hash as opposed to the hex representation. – Trentium Jul 13 '19 at 00:00
  • 1
    Don't use Math.random for cryptography. Use a secure RNG instead: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues. – Peter Jul 13 '19 at 13:38

0 Answers0