简体   繁体   中英

Random bytes to string type conversion

Trying to get a random string of using urandom.

#! python3

from os import urandom
from base64 import b64encode
from sys import getsizeof

random_bytes = urandom(16)
salt = b64encode(random_bytes).decode('utf-8')

print("Random Bytes:", random_bytes)
print(type(random_bytes))
print(getsizeof(random_bytes))
print(len(random_bytes))

print("")
print("Salt:", salt)
print(type(salt))
print(getsizeof(salt))
print(len(salt))

Below is the instance of output which I'm unable to understand.

Random Bytes: b'.v\x9c\xa0\xda\xa4\x92@d\xfc>\xb1\xccZ)\xff'
<class 'bytes'>
33
16

Salt: LnacoNqkkkBk/D6xzFop/w==
<class 'str'>
49
24

Why the lenght of output in random bytes is 16-bytes whereas decoded string is 24-bytes? What getsizeof is representing?

Because b64encode also pads the value, as discussed in this question and as also specified in the appropriate section of RFC 3548 .

The output value is 4 * math.ceil(n/3) long, so, in case of n == 16 equals 24 .

getsizeof represents the memory size for the bytes and str object respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM