Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2 base64 Encoding Yield Different Results

Tags:

ios

swift2

Swift 1.2

let apiLoginString = NSString(format: "%@:%@", API_USERNAME, API_PASSWORD);
let apiLoginData: NSData = apiLoginString.dataUsingEncoding(NSUTF8StringEncoding)!;
var base64ApiLoginString = apiLoginData.base64EncodedStringWithOptions(nil);

Swift 2

let apiLoginString = NSString(format: "%@:%@", API_USERNAME, API_PASSWORD);
let apiLoginData: NSData = apiLoginString.dataUsingEncoding(NSUTF8StringEncoding)!;
var base64ApiLoginString = apiLoginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions());

Those 2 approach yield different results. In Swift 2 we cannot pass in nil anymore;

apiLoginData.base64EncodedStringWithOptions(nil);

I have also tried passed in NSDataBase64EncodingOptions.Encoding64CharacterLineLength in Swift 2. But the results is still differemt

Any thoughts?

UPDATE 2: It is not the problem with Swift 1.2 or Swift 2. Oddly enough those 2 prints out different results.. What the F!!

UPDATE 3: Turns out that as Martin pointed out, I have some invisible character in my API_USERNAME variable

class RequestHelper: NSObject {
static var API_USERNAME: NSString = "⁠⁠⁠abc";
static var API_PASSWORD: NSString = "123";
static var USERNAME: NSString = "abc"
static var PASSWORD: NSString = "123"


class func signUpUser() {
    //Base64
    var loginString = NSString(format: "%@:%@", USERNAME, PASSWORD);
    var loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!;
    var base64LoginString = loginData.base64EncodedStringWithOptions([]);

    print("BASE 64 \(base64LoginString)");//RESULT YWJjOjEyMw==

    let apiLoginString = NSString(format: "%@:%@", API_USERNAME, API_PASSWORD);
    let apiLoginData: NSData = apiLoginString.dataUsingEncoding(NSUTF8StringEncoding)!;
    var base64ApiLoginString = apiLoginData.base64EncodedStringWithOptions([]);

    print("BASE 64 \(base64ApiLoginString)");// RESULT IS 4oGg4oGg4oGgYWJjOjEyMw==
}
like image 572
JayVDiyk Avatar asked Feb 09 '23 02:02

JayVDiyk


1 Answers

Similarly as in Swift 2.0 calendar components error or Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserNotificationType operands,
NSDataBase64EncodingOptions is an OptionSetType in Swift 2. It offers a set-like interface and can be initialized from an array literal.

So valid options would be for example:

base64EncodedStringWithOptions([]) // no options
base64EncodedStringWithOptions([.Encoding64CharacterLineLength])
base64EncodedStringWithOptions([.Encoding64CharacterLineLength, .EncodingEndLineWithCarriageReturn])

Full example:

let apiLoginString = NSString(format: "%@:%@", "user", "password")
let apiLoginData = apiLoginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64ApiLoginString = apiLoginData.base64EncodedStringWithOptions([])

print(base64ApiLoginString)
// dXNlcjpwYXNzd29yZA==
like image 62
Martin R Avatar answered Feb 22 '23 00:02

Martin R