Len_X
Len_X

Reputation: 863

Dart base64 decoding

Here is my base64 encoded String :

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uSWQiOiJkMjNiN2ViMy03MDgyLTRkZDktOGQ0OC1lMjU2YTM3OTNiOTciLCJyZWZyZXNoVG9rZW4iOiJiN2M3MTc4Yi04OWRjLTQxMDctYjUzNC1hOGZiOTNhMzEwNzAiLCJuYW1lIjoiTGVuIiwiaWF0IjoxNTczMDI4MjU2fQ

Using https://jwt.io/ it decodes correctly But When trying to use base64.decode('--Base64String--); in Flutter it gives me these errors

FormatException: Invalid character (at character 37)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uSWQiOiIzYWNiNzBjZS0wYzYxLT...

When removing the string in front of the . (I only need the info that comes after the .) I get this error

FormatException: Invalid length, must be multiple of four (at character 183)
...jLTQxMDctYjUzNC1hOGZiOTNhMzEwNzAiLCJuYW1lIjoiTGVuIiwiaWF0IjoxNTczMDI4MjU2fQ

Are there any other ways of decoding base64 encoded Strings for Dart

Upvotes: 1

Views: 10584

Answers (2)

Sobir Tojiyev
Sobir Tojiyev

Reputation: 21

try it. This will help you

Center(child: 
Image.memory(
base64Decode(image6464.substring(23).replaceAll("\n", ""))
 )
),

Upvotes: 1

clearloop
clearloop

Reputation: 711

You can use base64.normalize first.

For example:

import 'dart:convert';

void main() {
  final String b64 = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uSWQiOiJkMjNiN2ViMy03MDgyLTRkZDktOGQ0OC1lMjU2YTM3OTNiOTciLCJyZWZyZXNoVG9rZW4iOiJiN2M3MTc4Yi04OWRjLTQxMDctYjUzNC1hOGZiOTNhMzEwNzAiLCJuYW1lIjoiTGVuIiwiaWF0IjoxNTczMDI4MjU2fQ';

  String foo = b64.split('.')[0];
  List<int> res = base64.decode(base64.normalize(foo));

  print(utf8.decode(res));
}

Result:

{"alg":"HS256","typ":"JWT"}

Upvotes: 12

Related Questions