Reputation: 611
I have a problem with storing and reading from my keychain. First I tried to store use a char like this "account_name" in the Method SecKeychainFindInternetPassword for accountname and this runs. But now i would like to store a variable inside. But if i run this code the Programm cannot find the Keychain Item. Please Help me. (Sorry for my bad Englisch, i am a german student)
-(void)StorePasswordKeychain:(void*)password :(UInt32)passwordLength
{
char *userString;
userString = (char *)[_username UTF8String];
SecKeychainAddInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
passwordLength,
password,
NULL
);
}
-(OSStatus)GetPasswordKeychain:(void *)passwordData :(UInt32 *)passwordLength
{
OSStatus status;
char *userString;
userString = (char *)[_username UTF8String];
status = SecKeychainFindInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
passwordLength,
passwordData,
NULL
);
return status;
}
Upvotes: 3
Views: 1623
Reputation: 1145
Two suggestions.. don't pass null into itemRef (the last arg). Then you'll have a pointer to the keychain you wish to modify.
Also, you should really check the error code to see if your add function worked.
OSStatus result = SecKeychainAddInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
passwordLength,
password,
NULL
);
if(result != noErr){
NSLog(@"Error AddPassword result=:%d", result );
}
This is my sample program with the same code that you provided and it works fine.
int main(int argc, const char * argv[])
{
@autoreleasepool {
char *inputpassword = "topsecret";
UInt32 inputpassLength = strlen(inputpassword);
OSStatus status;
NSString *_username = @"account_name";
char *userString;
userString = (char *)[_username UTF8String];
status = SecKeychainAddInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
inputpassLength,
inputpassword,
NULL
);
NSLog(@"Adding Status:%d", status);
UInt32 returnpasswordLength = 0;
char *passwordData;
status = SecKeychainFindInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
&returnpasswordLength,
(void *)&passwordData,
NULL
);
NSLog(@"Retrieving status:%d", status);
NSLog(@"Password:%@", [[NSString alloc] initWithBytes:passwordData
length:returnpasswordLength
encoding:NSUTF8StringEncoding]);
}
return 0;
}
Upvotes: 2