【问题标题】:Convert base64 encoded google service account key to JSON file using Python使用 Python 将 base64 编码的谷歌服务帐户密钥转换为 JSON 文件
【发布时间】:2018-11-24 21:23:10
【问题描述】:

您好,我正在尝试将 google 服务帐户 JSON 密钥(包含在文件 foo.json 中名为 privateKeyData 的 base64 编码字段中 - 更多上下文 here )转换为实际的 JSON 文件(我只需要将该格式作为 ansible接受)

foo.json文件是使用这个google python apimethod获取的

我正在尝试做的事情(尽管我使用的是 python)也被描述为 this 线程,顺便说一句,它对我不起作用(在 OSx 和 Linux 上尝试过)。

#!/usr/bin/env python3

import json
import base64

with open('/tmp/foo.json', 'r') as f:
    ymldict = json.load(f)

b64encodedCreds = ymldict['privateKeyData']

b64decodedBytes = base64.b64decode(b64encodedCreds,validate=True)

outputStr = b64decodedBytes
print(outputStr)

#issue
outputStr = b64decodedBytes.decode('UTF-8')
print(outputStr)

产量

./test.py 
b'0\x82\t\xab\x02\x01\x030\x82\td\x06\t*\x86H\x86\xf7\r\x01\x07\x01\xa0\x82\tU\x04\x82\tQ0\x82\tM0\x82\x05q\x06\t*\x86H\x86\xf7\r\x01\x07\x01\xa0\x82\x05b\x04\x82\x05^0\x82\x05Z0\x82\x05V\x06\x0b*\x86H\x86\xf7\r\x01\x0c\n\x01\x02\xa0\x82\x#TRUNCATING HERE
    Traceback (most recent call last):
      File "./test.py", line 17, in <module>
        outputStr = b64decodedBytes.decode('UTF-8')
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 1: invalid start byte

我想我的想法已经用完了,现在花了一天多的时间:(

我做错了什么?

【问题讨论】:

    标签: python base64 google-compute-engine


    【解决方案1】:

    您的 base64 解码逻辑对我来说看起来不错。您面临的问题可能是由于字符编码不匹配。您在调用create(您的 foo.json 文件)后收到的响应正文可能未使用 UTF-8 编码。查看响应标头的 Content-Type 字段。它应该看起来像这样:

    Content-Type: text/javascript; charset=Shift_JIS
    

    尝试使用内容类型中使用的编码对您的 base64 解码字符串进行解码

    b64decodedBytes.decode('Shift_JIS')
    

    【讨论】:

    • 感谢您对 Mug4n 的帮助。我已经尝试使用 tcpdump 运行 create 方法,我可以看到 grepping(似乎无法专门过滤该连接)显示 Content-Type with charset utf-8 ... :(
    • 它现在可以正常工作而且很有趣我不知道发生了什么变化。再次感谢
    • 当我遇到问题时,privateKeyData 以“MII....”开头。现在我回来了“ewo.....”。天知道这里发生了什么
    猜你喜欢
    • 1970-01-01
    • 2016-06-26
    • 2017-09-29
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多