简体   繁体   English

随机字节到字符串类型的转换

[英]Random bytes to string type conversion

Trying to get a random string of using urandom. 尝试获取使用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? 为什么输出的随机字节长度是16字节而解码的字符串是24字节? What getsizeof is representing? getsizeof代表什么?

Because b64encode also pads the value, as discussed in this question and as also specified in the appropriate section of RFC 3548 . 因为b64encodeb64encode该值,所以如问题所讨论以及RFC 3548的相应部分中所指定。

The output value is 4 * math.ceil(n/3) long, so, in case of n == 16 equals 24 . 输出值是4 * math.ceil(n/3)长,因此,在n == 16情况下等于24

getsizeof represents the memory size for the bytes and str object respectively. getsizeof表示bytesstr对象的内存大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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