【问题标题】:Random bytes to string type conversion随机字节到字符串类型的转换
【发布时间】:2016-12-20 22:57:32
【问题描述】:

试图得到一个随机的字符串 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))

以下是我无法理解的输出实例。

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

为什么随机字节的输出长度是 16 字节,而解码后的字符串是 24 字节? getsizeof 代表什么?

【问题讨论】:

    标签: python string python-3.x base64


    【解决方案1】:

    因为b64encode 也填充了值,正如在in this 问题中所讨论的以及在the appropriate section of RFC 3548 中所指定的那样。

    输出值为4 * math.ceil(n/3) long,所以,如果n == 16等于24

    getsizeof 分别代表bytesstr 对象的内存大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 2016-05-26
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 2017-05-20
      相关资源
      最近更新 更多