Journeyman
Journeyman

Reputation: 10281

Base64 encoding difference between iOS and .NET

I am working on a system that is 50% iOS and 50% Microsoft.NET C#. The primary ids used within the system are Guids/NSUUIDs, and these are converted into Base64 strings from time-to-time. I have a discrepancy in how .NET and iOS perform the base64 conversion.

Here is my objective-c code to convert an NSUUID (in string format) to a Base64 string:

+(NSString*)getBase64IdFromGuidStringWithString:(NSString*)stringInGuidFormat
{
    NSLog(@"stringInGuidFormat is %@",stringInGuidFormat);

    NSUUID* nsuuid = [[NSUUID alloc] initWithUUIDString:stringInGuidFormat];
    uuid_t uuid;
    [nsuuid getUUIDBytes:uuid];
    NSData* data = [NSData dataWithBytes:uuid length:16];
    NSString* base64 = [data base64EncodedString];

    NSLog(@"base64 is %@",base64);
    return base64;

}

where [data base64EncodedString] is courtesy of Matt Gallagher

and here is a similar method in .NET C# to do the same thing:

private string convertGuidStringToBase64(string elementAsString)
{
    Guid isAsGuid = new Guid(elementAsString);
    string base64 = Convert.ToBase64String(isAsGuid.ToByteArray());
    return base64;
}

Given a starting string value of CBB2B719-D129-4051-B694-4204A6F6BE93 I have the following results: iOS thinks the base64 value is y7K3GdEpQFG2lEIEpva+kw== C# thinks the base64 value is GbeyyynRUUC2lEIEpva+kw==

Obviously I have got something wrong! Can anyone point out my error, and point me in the right direction to solve it!

Many thanks.

Upvotes: 0

Views: 1346

Answers (2)

fejesjoco
fejesjoco

Reputation: 11903

Base64 conversion cannot be the problem. It is standardized and should work on all platforms. It converts a series of bytes from/to strings, so byte endianness cannot be an issue here.

That leaves us NSUUID and Guid. It seems that they are stored differently on the two systems. They store their bytes in memory in a different order, aka. endianness. Therefore, their Base64 encoded value will be different as well.

I suggest you read about UUID and Guid, especially how they store their data in memory.

Upvotes: 0

Patrik Staehli
Patrik Staehli

Reputation: 26

This looks very much like a byte order problem. Base64 decoded, those two values are:

cb b2 b7 19 d1 29 40 51 b6 94 42 04 a6 f6 be 93

and

19 b7 b2 cb 29 d1 51 40 b6 94 42 04 a6 f6 be 93

Notice the first 4 bytes being reversed?

If you want the same values, you have to make sure to use the same byte order. I would suggest converting to network byte order for portability.

Hope this helps

Cheers Patrik

Upvotes: 1

Related Questions