Mike Owens
Mike Owens

Reputation: 936

NSData not returning bytes

Ok I have a password stored in the keychain and I am attempting to update the password in the keychain and on my server. When the user types in the new password in an UIAlertView the password is updated in the keychain and so on. The problem I am having is when you cancel or try to do it again the value retrieve from the keychain is retuned as the the string instead of in bytes.

I set the new password in the keychain like this using the keychain wrapper

[keychainItem setObject:newPassword forKey:(__bridge id)(kSecValueData)];

the first time i go through the process it works fine but if I attempt to change it again and go through the process i get

-[__NSCFString bytes]: unrecognized selector sent to instance 

it crashes in this method when NSString *keychainPassword = [[NSString alloc] initWithData:pass encoding:NSUTF8StringEncoding]; is called. in the NSLog call it is retuning the string of the password and not the bytes, any reason why?

-(BOOL)checkIfOldPasswordMatches {
NSLog(@"checkIfPasswordMatches");

 //gets password from keychain
NSData *pass = [keychainItem objectForKey:(__bridge id)(kSecValueData)];
if (pass == nil || [pass length] == 0) {
    [UIAlertView error:@"Username and Password does not exist. You must create a login."];
}

 //shows output of password which should return bytes
NSLog(@"pass %@", pass);
NSString *keychainPassword = [[NSString alloc] initWithData:pass encoding:NSUTF8StringEncoding];

NSLog(@"keychain %@", keychainPassword);
if ([oldPassword isEqualToString:keychainPassword]) {
    NSLog(@"yes");
    return YES;
} else
    NSLog(@"no");
return NO;

}

Upvotes: 0

Views: 378

Answers (1)

Paulw11
Paulw11

Reputation: 114992

kSecValueData specifies that the item is some data, not a reference to another item (kSecValueReference) or a persistent reference (kSecValuePersistentRef). It doesn't mean that the item value is stored/returned as an NSData instance.

The type of object you put in is the type of object you will get out, so if you put in an NSString you will get back an NSString.

You need to change your code to either always use an NSData instance or always use an NSString, converting as required.

Upvotes: 1

Related Questions