Home > Enterprise >  How do i generate random bytes and convert do hex using dart
How do i generate random bytes and convert do hex using dart

Time:08-11

I'm trying to generate a Session code based on the following code from PHP in Dart/Flutter:

private $length = 32;
substr(bin2hex(random_bytes($this->length), 0, $this->length);

the problem is that I don't know how to create these random_bytes in dart and then convert them to bin2hex, using DART language.

These functions described above are from PHP (opencart system) which I must to create a hash to specify session from each user connected.

the result expected from this conversion is something like that:

"004959d3386996b8f8b0e6180101059d"

CodePudding user response:

If your goal are just to generate such a hex-string using random numbers, you can do something like this:

import 'dart:math';

void main() {
  print(randomHexString(32)); // 1401280aa29717e4940f0845f0d43abd
}

Random _random = Random();

String randomHexString(int length) {
  StringBuffer sb = StringBuffer();
  for (var i = 0; i < length; i  ) {
    sb.write(_random.nextInt(16).toRadixString(16));
  }
  return sb.toString();
}
  •  Tags:  
  • dart
  • Related