How to encrypt string using lib-sodium in iOS

1.5k Views Asked by At

I have scanned a QR Code image using ZXingWidget lib, received a string as response. Now I want to encrypt that string using lib-sodium in iOS.

Any suggestion how to do string encryption in iOS using lib-sodium library.... Thanks in advance...

1

There are 1 best solutions below

0
On

As requested: Sample code on implementing PBKDF

Note, this is an example, not production code.

#import <CommonCrypto/CommonKeyDerivation.h>
+ (NSData *)doKeyForPassword:(NSString *)password
                        salt:(NSData *)salt
                     keySize:(NSUInteger)keySize
                      rounds:(NSUInteger)rounds {
    NSMutableData *derivedKey = [NSMutableData dataWithLength:keySize];

    NSData *passwordData = [password dataUsingEncoding: NSUTF8StringEncoding];

    CCKeyDerivationPBKDF(kCCPBKDF2, // algorithm
        passwordData,               // password
         passwordData,              // passwordLength
         salt.bytes,                // salt
         salt.length,               // saltLen
         kCCPRFHmacAlgSHA1,         // PRF
         rounds,                    // rounds
         derivedKey.mutableBytes,   // derivedKey
         derivedKey.length);        // derivedKeyLen

    return derivedKey;
}

Very simple test, use a better salt and a better rounds count, possible using CCCalibratePBKDF.

- (void)test_doKeyForPassword {
    NSData *key = [Crypto doKeyForPassword:@"password"
                                      salt:[@"salt" dataUsingEncoding:NSUTF8StringEncoding]
                                   keySize:kCCKeySizeAES128
                                    rounds:1000];
    NSLog(@"doKeyForPassword: %@",key);
}

If you are copying this code to use in a production app: Don't. This is just example code. Basically if one needs this code they should not be doing cryptography. Hire a domain expert, at a minimum have the code vetted by a domain expert.