Search code examples
swiftbase64swift4decodeswift5

Swift base64 decode non alphabetic and non utf-8 strings


Is it possible to correctly decode using Swift language base64 encoded string which contains a string in non-utf8 encoding (ie. Windows-1252 or ISO-8859-1)?

Every snippet of code that can be found here on stackoverflow fails and return nil.

For example let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.IgnoreUnknownCharacters)

gives empty as it ignores bad characters and if I don't use this option it gives nil like dozens of other gist code

This is test base64 string containing part of cryptographic key which I need to decode. If I use some other language like Python, PHP or Java it is decoding correctly but using Swift I can't do that.

FkXKDAAAAAAAAAAAvMBAYFk1JADmiwHAz+rNFy93faklHL7MW3Hhlf1Bo7/hpZ3j1GmdySyIpJ4YlRH65mleumYqsgUgYLlQY/jQq2YykMPUwZQ4jTgU7Q== should be EʼÀ@`Y5$æ‹ÀÏêÍ/w}©%¾Ì[qá•ýA£¿á¥ãÔiÉ,ˆ¤ž•úæi^ºf*² `¹PcøЫf2ÃÔÁ”88í

as it can be decoded with online tool like this

Here is another one:

FgdhDAAAAAAABwAAOJAiYMxlJQAMbwHAWrYq59+po4WdMS4R+EHV4hBKzWn8oZYpTFdFQ33usZUa19d+umkWcL2g4mmVeUOwUG2dZGWIrxlTWJA+s/RTTQ==

Please advise is there any way to decode base64 strings like this locally on iOS device or I really need to send it to server to do that?


Solution

  • You're looking a fairly old examples. The syntax changed to this:

    let decodedData = Data(base64Encoded: base64String)
    

    I've tested with your examples, and they work fine. Keep in mind that the output is raw Data, this isn't a String in any encoding (Windows-1252 or ISO-8859-1, etc). It's just a sequence of random bytes, and that's what it is expected to be. The online tool you're using is just trying to decode it as ISO-8859-1, but that's gibberish, and is in fact corrupted in the output you've shown. It's not displaying the first byte (which is 0x16, and unprintable).