0

I don't know what the php method equivalent python that i should use in python. I tried to generate some code but it wrong and doesn’t work. Can anyone help me convert this code php to python

PHP:

tracking = base64_encode(openssl_random_pseudo_bytes(40));
id = substr(md5(tracking), 16);

Python

tracking = os.urandom(40)
print(tracking)

>>> YidceGM1XHhjZVx4MTBceGVkX1x4OGFxXHhkN0NcdFhQU1x4ZTdceDA0Mip7KVx4OGRceDFjXHhhYlx4ODdAcFpceGVmXHg4ZXVcdFZHdFdceGM2OnZceGUyXFxceDFlJw==

But correctly code length must be 56 but in python generated so long

example correct tracking :

PldikuqQF1/acrFfnfkBr6pIFjRZ9eLzsgQf6hpRVm/e8s1kmOrqjw==
X2g1P0ORzhlyDCUzSrS2o2n8EgZYpXvzBkNMMdEyNegqjr8GbTlOGA==

example correct id :

a3c6b613c95f4ea9
Dake
  • 71
  • 2
  • 10

1 Answers1

0

os.urandom() provides no guarantee the bytes it produces are compatible with base64. (Props to you for using something so secure!) In order to convert the bytestream, you need to first use base64.b64encode(). It can then be decoded to utf-8 for printing or other use.

>>> import base64, os
>>> print(base64.b64encode(os.urandom(40)).decode('utf-8'))
h0nsWdcU6rYw3BJD3NLbq5MuqF6n7btAZuT14TipHOA9RYRZEuqj2g==

For md5 encoding, this answer recommends hashlib.md5() to encode.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37