KamilloPL
KamilloPL

Reputation: 34

Swift String and base64Encode Confusion

I have problem with encoding data. My token has 1228 characters and

let data = Data(base64Encoded: tokenString)! 

works fine, but when i add to token some information and my token has 1263 characters Data(base64Encoded:) returns nil.

Problem in my opinion is in the string length or Data(base64Encoded:).

Does Data(base64Encoded:) have any restrictions on the length of characters? Please give me some info about this problem.

Upvotes: 0

Views: 450

Answers (1)

Gleb A.
Gleb A.

Reputation: 1180

Not sure how you encode the modified token, but looks like the encoded Base64 string doesn't include padding characters. Appending = to the modified token seems to fix the decoding issue:

// original token -> 57 bytes
let data1 = Data(base64Encoded: "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyMTF9")

// modified token -> nil
let data2 = Data(base64Encoded: "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyMX0")

// modified token with '=' for padding -> 56 bytes
let data2Fixed = Data(base64Encoded: "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyMX0=")

// decodes correctly: "{"sub":"1234567890","name":"John Doe","iat":15162390221}"
let string = String(data: data2Fixed!, encoding: .utf8)

So to solve it properly you probably need to look into the encoder. Hope that helps!

Upvotes: 2

Related Questions