3

in python i'm using the Crypto package to generate a random number of length 256 bit. The function for doing so is

import Crypto.Random.random as rand
key = rand.getrandbits(256)  

This gives something like:

112699108505435943726051051450940377552177626778909564691673845134467691053980

Now my is question how do i transform this number to a string of all ascii characters? Is there a build in function for doing so or do i need to convert it to binary and split it up in blocks of eight ones and zeros and do it myself?

Thans in advance.

DoubleDouble
  • 49
  • 1
  • 4

1 Answers1

0

I don't know if it's built in, but I doubt it.

But doing it yourself is not as easy as reinterpreting your data as bytes. This is because Ascii is a 7-bit encoding scheme. The most significant bit is always zero.

The easiest way to do this is to convert your int to a packed array of bytes (to_bytes)[1] and then discard a bit from each byte, e.g. by right shifting. This wastes 1/8 of your entropy but makes for a cleaner program.

This only works because you're using a cryptographically secure source of random number generation. This means that each bit has an equal probability of being a one or zero - that is, each bit is uniformly distributed and independent of all others. [2]

[1]http://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types [2]https://crypto.stackexchange.com/questions/10300/recasting-randomly-generated-numbers-to-other-widths

Community
  • 1
  • 1
masonk
  • 9,176
  • 2
  • 47
  • 58
  • 1
    After some more research i found this [link](http://stackoverflow.com/questions/7396849/convert-binary-to-ascii-and-vice-versa-python) this code dit the job. Thanks a lot for your answers. I didn't knew anything about how many bits ascii used. This was a really helpful description. – DoubleDouble Nov 16 '13 at 00:51