The standard password derivation method these days is: PBKDF2
(Password-Based Key Derivation Function 2)
NSMutableData *derivedKey = [NSMutableData dataWithLength:keySize];
int result = CCKeyDerivationPBKDF(
kCCPBKDF2, // algorithm
password.UTF8String, // password
password.length, // passwordLength
salt.bytes, // salt
salt.length, // saltLen
kCCPRFHmacAlgSHA1, // PRF
rounds, // rounds
derivedKey.mutableBytes, // derivedKey
derivedKey.length); // derivedKeyLen
Now the big question is exactly what is the Java StandardStringDigester
doing?
I would not be comfortable just assuming it iterates the hash function (SHA1). There also seems to be a salt.
Best practice is to use PBKDF2 which Java does seem to support.
Here is a take on your code with an #if for utf8 or utf16
static const int iterations = 50000;
+ (NSString *) digestPassword:(NSString *)inputPassword {
NSMutableData *dataOut = [NSMutableData dataWithLength:CC_SHA1_DIGEST_LENGTH];
#if 1 // UTF16
NSData *data = [inputPassword dataUsingEncoding:NSUTF16StringEncoding];
data = [data subdataWithRange:NSMakeRange(2, data.length-2)];
#else // UTF8
NSData *data = [inputPassword dataUsingEncoding:NSUTF8StringEncoding];
#endif
for (int iteration = 0; iteration < iterations; iteration++) {
if (CC_SHA1([data bytes], [data length], dataOut.mutableBytes)) {
data = dataOut;
}
else {
NSLog(@"treta %i", iteration);
}
}
unsigned char *digest = (unsigned char *)data.bytes;
NSMutableString *result = [NSMutableString new];
for (int index = 0 ; index < CC_SHA1_DIGEST_LENGTH ; index++) {
[result appendFormat: @"%02x", digest[index]];
}
return result;
}