Python:base64.b64decode()vs .decode?

时间:2013-11-21 14:26:39

标签: python base64 bind x509certificate

Code Furies已经将他们的恶意眩光转向我,而The Direct Project所定义的实施“安全运输”对我来说也是如此。无论我们是否在内部使用DNS而不是LDAP来共享证书,我显然需要设置前者来测试,这就是让我陷入困境的原因。显然,X509证书需要在CERT记录中使用一些按摩,我正在尝试弄清楚它是如何完成的。

我发现最清楚的是Videntity's blog上的一个脚本,但是我不熟悉python,我正在遇到绊脚石。具体来说,这一行崩溃了:

decoded_clean_pk = clean_pk.decode('base64', strict)

因为它似乎不喜欢(或者更确切地说,知道)任何'严格'应该代表什么。我正在进行半教育的猜测,该行应该解码base64数据,但是几年前我从Debian OpenSSL崩溃中了解到盲目地使用加密相关代码是Bad Thing(TM)。

所以我把SO上的杰出蟒蛇转过来询问这条线是否可以被这个替换(添加了适当的导入):

decoded_clean_pk = base64.b64decode(clean_pk)

脚本在更改后运行,并产生正确的输出,但我有足够的直觉知道我不一定相信我的直觉。 :)

1 个答案:

答案 0 :(得分:4)

如果您这样打电话,这条线应该可以工作:

decoded_clean_pk = clean_pk.decode('base64', 'strict')

请注意strict必须是string,否则python解释器会尝试搜索名为strict的变量,如果它没有找到它或者具有其他值,则:strictignorereplace,它可能会抱怨它。

看看这段代码:

>>>b=base64.b64encode('hello world')
>>>b.decode('base64')
'hello world'

>>>base64.b64decode(b)
'hello world'

decode传递b64decode参数字符串时,.decodebase64的工作方式相同。

区别在于str.decode将一串字节作为参数,并将返回它的Unicode表示形式,具体取决于您作为第一个参数传递的encoding参数。在这种情况下,你告诉它处理一个bas64字符串,这样就可以了。

要回答您的问题,两者的工作原理相同,但b64decode/encode仅适用于base64编码,而str.decode可以处理与库一样多的编码。

如需了解更多信息,请阅读以下两个文档部分:decodeb64decode

更新:实际上,这是我猜的最重要的例子:)看看encodings/base64_codec.py使用的decode()源代码:

def base64_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = base64.decodestring(input)
    return (output, len(input))

正如您所看到的,它实际上使用base64模块来执行此操作:)

希望这能以某种方式澄清你的问题。