【问题标题】:Dart - Base64 string is not equal to pythonDart - Base64 字符串不等于 python
【发布时间】:2018-05-04 14:03:18
【问题描述】:

当我使用 Python 生成将在raw key { 'raw': value } GMAIL API 中使用的base64 字符串时,发送电子邮件非常完美。

但是当我使用 Dart 生成相同的base64 字符串时,该字符串与 python 不同,因此我无法发送电子邮件,因为 GMAIL API 告诉我message: Invalid value for ByteString

要转成base64的字符串是:

var message = '''<html><meta http-equiv="content-type" content="text/html; charset=utf-8"/><head></head><body>Test</body></html>'''

Python 代码:

import base64

e = base64.urlsafe_b64encode('''<html><meta http-equiv="content-type" content="text/html; charset=utf-8"/><head></head><body>Test</body></html>''')
print(e)

结果:

PGh0bWw-PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiLz48aGVhZD48L2hlYWQ-PGJvZHk-VGVzdDwvYm9keT48L2h0bWw-

飞镖代码:

import 'dart:convert';
var _bytes = utf8.encode('''<html><meta http-equiv="content-type" content="text/html; charset=utf-8"/><head></head><body>Test</body></html>''');
var _base64 = base64Encode(_bytes);
print(_base64);

结果:

PGh0bWw+PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiLz48aGVhZD48L2hlYWQ+PGJvZHk+VGVzdDwvYm9keT48L2h0bWw+

请注意,唯一的区别是 Dart 的 base64 字符串中的 + 符号和 Python 的 base64 字符串中的 - 符号

如何生成相同的 base64 python 代码,以便在 GMAIL API 中发送电子邮件

【问题讨论】:

    标签: python dart


    【解决方案1】:

    明确要求 Python 用 - 替换 base64 编码字符串中的所有 + 字符,因为你使用了 urlsafe_b64encode 变体!文档说:

    base64.urlsafe_b64encode(s)

    使用 URL 和文件系统安全字母对字节类对象 s 进行编码,在标准 Base64 字母表中用 - 代替 + 和 _ 代替 /,并返回编码后的字节。结果仍然可以包含 =。

    如果您想要与 Dart 生成的字符串相同,只需将 encodebytes 用于 Python3 或 encode 用于 Python 2。

    【讨论】:

    • 您好,感谢您的帮助。我喜欢与 Dart 有相同的字符串 Python
    【解决方案2】:

    Dart 有一个 URL 安全版本的 Base 64 编码,如 Python。

    改变

    var _base64 = base64Encode(_bytes);

    var _base64 = base64UrlEncode(_bytes);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多