Rani
Rani

Reputation: 3453

Encrypt passwords in SQLite database?

I have 2 two text fields, one for username and password: when the user enters a username and password and click on the "save" button the username and password is getting save in the SQLite database.

I want to save to username and password in encrypted format for more security.

Upvotes: 1

Views: 2979

Answers (4)

Sudesh Kumar
Sudesh Kumar

Reputation: 569

I think you can use SecKeyWrapper class. You can find it on developer site:

http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Listings/Classes_SecKeyWrapper_h.html

Upvotes: 0

martineno
martineno

Reputation: 2635

If you are storing a user's credentials, the best way to do that is to use the Keychain APIs. The iOS Secure Coding How-Tos on Apple's site are a great place to start. In particular you want to look at How do I store information securely in the keychain or retrieve the information when needed?.

Using the Keychain APIs will ensure that the user's password is properly encrypted and protected.

Upvotes: 0

Ram
Ram

Reputation: 406

Use this MD5 hash algorithm to save the password

const char *cStr = [self UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result ); // This is the md5 call
return [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]
    ];

While retrieving also u have to first convert the string to MD5 and then compare that hash with the password field stored in the database.

Upvotes: 0

vijay gupta
vijay gupta

Reputation: 242

I am defining 2 ways to encrypt and decrypt your string, chose which ever u like easy.

Way 1

- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}

- (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
    return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
                                  encoding:NSUTF8StringEncoding] autorelease];
}

way 2

NSString *plainString = @"This string will be encrypted";
NSString *key = @"YourEncryptionKey"; // should be provided by a user

NSLog( @"Original String: %@", plainString );

NSString *encryptedString = [plainString AES256EncryptWithKey:key];
NSLog( @"Encrypted String: %@", encryptedString );

NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );

Upvotes: 1

Related Questions