0

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
sunkehappy
  • 8,970
  • 5
  • 44
  • 65
atomikpanda
  • 1,845
  • 5
  • 33
  • 47
  • You probably want to encrypt the password, not encode it (encryption can't be reversed, encoding can). I guess the best option would be to use a `bcrypt` C library. – Joost Nov 04 '12 at 01:37
  • @Joost Is `bcrypt` for objective-c mac cocoa? – atomikpanda Nov 04 '12 at 01:41
  • 2
    @Joost: Encryption *can* be reversed; hashing can't. – mipadi Nov 04 '12 at 01:50
  • What are you trying to accomplish? If you need to be able to get the password back later, use the keychain. If you just need to check that someone entered it correctly, use a salted hash designed for it, like PBKDF2, bcrypt, or scrypt. – Gordon Davisson Nov 04 '12 at 04:11

3 Answers3

2

A better way to store passwords would be to use the Keychain.

There are classes that make it easier - such as SSKeyChain on Github

Abizern
  • 146,289
  • 39
  • 203
  • 257
  • SSKeychain has it's flaws though. Under the current version, it will produce an invalid username response from the underlying Sec framework and basically screw with any project with breakpoints enabled. – CodaFi Nov 04 '12 at 08:04
1
#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]];
sunkehappy
  • 8,970
  • 5
  • 44
  • 65
  • For MD5 you can't decode. You can encode the password user input and compare the two encoded password to see whether user has input the correct password. – sunkehappy Nov 04 '12 at 01:54
0

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.

Community
  • 1
  • 1
John Carter
  • 6,752
  • 2
  • 32
  • 53