Search code examples
objective-ckeychainkeychainitemwrapper

iOS keychain - Different values found on subsequent reads


I'm using the keychainItemWrapper to store a token in my ios keychain. I can write successfully and read the first time successfully. However, once I read subsequent times, or run my program again, I'm getting a different value, or data in a different format. Any ideas?

Details: 1) Using KeychainItemWrapper - https://gist.github.com/dhoerl/1170641 2) Testing on simulator

Code:

NSString* mytoken = @"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIwYTVjM2U4N2FmY2I0NTNlYWEzZjI3MDBlYjgwZWE4YiIsInN1YiI6ImxpbmRzZXk0IiwiaWF0IjoxNTE5MTk5MTgxLCJuYmYiOjE1MTkxOTkxODEsImV4cCI6MTUxOTE5OTc4MX0.v10D61EE6tq6u9YG3QIQ_XefexlC22gwx-tv-HgOEsQ";

KeychainItemWrapper* keychain1 = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.test.test" accessGroup:nil];

[keychain setObject:mytoken forKey:(id)kSecValueData];

NSString* result1a = [keychain1 objectForKey:(id)kSecValueData];
NSLog(@"result1a (works!):\n %@:", result1a);

result1a (works!): eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIwYTVjM2U4N2FmY2I0NTNlYWEzZjI3MDBlYjgwZWE4YiIsInN1YiI6ImxpbmRzZXk0IiwiaWF0IjoxNTE5MTk5MTgxLCJuYmYiOjE1MTkxOTkxODEsImV4cCI6MTUxOTE5OTc4MX0.v10D61EE6tq6u9YG3QIQ_XefexlC22gwx-tv-HgOEsQ

NSString* result1b = [keychain1 objectForKey:(id)kSecValueData];
NSLog(@"result1b (works!):\n%@", result1b);

result1b (works!): eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIwYTVjM2U4N2FmY2I0NTNlYWEzZjI3MDBlYjgwZWE4YiIsInN1YiI6ImxpbmRzZXk0IiwiaWF0IjoxNTE5MTk5MTgxLCJuYmYiOjE1MTkxOTkxODEsImV4cCI6MTUxOTE5OTc4MX0.v10D61EE6tq6u9YG3QIQ_XefexlC22gwx-tv-HgOEsQ

KeychainItemWrapper* keychain2 = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.test.test" accessGroup:nil];

NSString* result2 = [keychain2 objectForKey:(id)kSecValueData];
NSLog(@"result2 (weird value!):\n%@", result2);

result2 (weird value!): <65794a68 62476369 4f694a49 557a4931 4e694a39 2e65794a 7164476b 694f6949 77595456 6a4d3255 344e3246 6d593249 304e544e 6c595745 7a5a6a49 334d4442 6c596a67 775a5745 34596949 73496e4e 31596949 36496d78 70626d52 7a5a586b 30496977 69615746 30496a6f 784e5445 354d546b 354d5467 784c434a 75596d59 694f6a45 314d546b 784f546b 784f4445 73496d56 34634349 364d5455 784f5445 354f5463 344d5830 2e763130 44363145 45367471 36753959 47335149 515f5865 6665786c 43323267 77782d74 762d4867 4f457351>


Solution

  • You are actually getting the same value, but it's in hex format. If you convert that last value in to String you'll get the same value. You can see it on this hex converter http://string-functions.com/hex-string.aspx Just paste that last result and hit convert.

    So for some reason, your first result is in String and your last result is in NSData format.