Reputation: 1886
How can I encode a password string and save it to a file in objective-c on a Mac? something like this:
NSString *myPasswordString = [NSString stringWithFormat:@"mypassword"];
//Encode
//Save to Preferences file
Upvotes: 0
Views: 1233
Reputation: 150605
A better way to store passwords would be to use the Keychain.
There are classes that make it easier - such as SSKeyChain on Github
Upvotes: 2
Reputation: 6985
You can write to a preferences file as follows:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[settings setObject : myPasswordString forKey : @"mypassword"];
[settings synchronize];
I'm not sure what you mean by 'encode'. If you mean 'encrypt' there are numerous questions on SO:
Even with the above, you'll still need to think carefully about the security implications. If you're storing a password that was encrypted using a key embedded in your application its possible for that password to be recovered by an attacker.
Upvotes: 0
Reputation: 9091
#import <CommonCrypto/CommonDigest.h>
...
const char *cStr = [myPasswordString UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result ); // This is the md5 call
NSString *passwordAfterEncrypt = [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]];
Upvotes: 1