Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - Base64 string is not equal to python

Tags:

python

dart

When I use Python to generate a base64 string that will be used in the raw key { 'raw': value } GMAIL API, sending the email occurs perfectly.

But when I use Dart to generate the same base64 string, the string is not the same as python and because of that I can not send the email because the GMAIL API tells me message: Invalid value for ByteString

The string that will be converted to base64 is:

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

Python code:

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)

result:

PGh0bWw-PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiLz48aGVhZD48L2hlYWQ-PGJvZHk-VGVzdDwvYm9keT48L2h0bWw-

Dart code:

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);

result:

PGh0bWw+PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiLz48aGVhZD48L2hlYWQ+PGJvZHk+VGVzdDwvYm9keT48L2h0bWw+

Note that the only difference is the + sign in the base64 string of the Dart, and the - sign in the base64 string of Python

How can I generate the same base64 python code, so I can send the email in the GMAIL API

like image 323
rafaelcb21 Avatar asked May 04 '18 14:05

rafaelcb21


1 Answers

You explicit asked Python for replacing all + characters with - in the base64 encoded string, because you have used the urlsafe_b64encode variant! The documentation says:

base64.urlsafe_b64encode(s)

Encode bytes-like object s using the URL- and filesystem-safe alphabet, which substitutes - instead of + and _ instead of / in the standard Base64 alphabet, and return the encoded bytes. The result can still contain =.

If you want the same string as Dart produces, just use simply encodebytes for Python3 or encode for Python 2.

like image 156
Serge Ballesta Avatar answered Sep 28 '22 15:09

Serge Ballesta