You are reading a single comment by @Stevie and its replies. Click here to read the full conversation.
  • Hi,

    I need a random number generator for a project. Just found out that Math.random() always returns the same sequence after a reboot, making it not usable in my case. Especially because it is not possible to seed it. I want something less predictable. I guess that's the case in many applications, for example dice based games (you do not want to have the same game again and again after starting up), or for encryption when controlling something over radio.

    First question: Would it make sense to allow to seed Math.random()? That would not force everyone who wants unpredictable randomness to implement their own RNG.

    As this is not possible right now, I set out to implement something more random. After finding out that the MCU does not have the hardware random number generator some of the STM32F4 do have, I hacked together a little hardware based random number generator; similar to one which some people use on Arduinos.

    It looks like this:

    function random()
    {
      var sum = 0;
      var v1 = Math.floor(E.getAnalogVRef() * 100000000000) % 2;
      for (var s = 0; s < 32; s++)
      {
        sum *= 2;
        var v2 = Math.floor(E.getAnalogVRef() * 100000000000) % 2;
        if (v1 == v2)
          sum++;
      }
      
      return sum;
    }
    

    It uses the least significant bits of the analog reference as a source of random bits. Note that the output seemed to be a bit biased (more 0s than 1s). The "if (v1==v2) is for whitening the random bits to remove that bias. It looks pretty good after that.

    It is pretty slow but also pretty random - at least with my board when powered over USB. Have to try it with a battery to see how it behaves there. While I would not necessarily use it for hard cryptography, it is better than having to use the same sequence over and over again. It might also be interesting to couple it with the elapsed time to add more randomness.

    Is this something which should be added to Espruino? I could also make a C module out of it, would be much faster. Maybe it would also be useful to use it only as a source for a random seed for Math.random - if seeing is added.

    Any thoughts?

    Stevie

About

Avatar for Stevie @Stevie started