Implement PBEKeySpec Encryption on iOS

This is my java code. Now I want to implement the same functionality in Objective-C.

int dkLen = 16; int rounds = 1000; PBEKeySpec keySpec = new PBEKeySpec(hashKey.toCharArray(),salt.getBytes(), rounds, dkLen * 8); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); return factory.generateSecret(keySpec).getEncoded(); 

This is my iOS implementation.

 - (void)getHashKey { NSString * hash_key=@ "MY_HASHKEY"; NSString *saltKey = @"MY_SALTKEY"; int dkLen = 16; NSData *keyData = [hash_key dataUsingEncoding:NSUTF8StringEncoding]; NSData *salt = [saltKey dataUsingEncoding:NSUTF8StringEncoding]; uint rounds = 1000; uint keySize = kCCKeySizeAES128; NSMutableData *derivedKey = [NSMutableData dataWithLength:keySize]; CCKeyDerivationPBKDF(kCCPBKDF2, // algorithm keyData.bytes, // password keyData.length, // passwordLength salt.bytes, // salt salt.length, // saltLen kCCPRFHmacAlgSHA1, // PRF rounds, // rounds derivedKey.mutableBytes, // derivedKey dkLen*8); // derivedKeyLen NSString *myString = [[NSString alloc] initWithData:derivedKey encoding:NSASCIIStringEncoding]; NSLog(@"derivedKey: %@", myString); } 

Is there a problem with the algorithm that I use in iOS

+5
source share
1 answer

Use the Common Crypto CCKeyDerivationPBKDF with the kCCPRFHmacAlgSHA1 option.

Note PBEKeySpec keyLength is in bits, CCKeyDerivationPBKDF derivedKeyLen is in bytes.

For a more detailed answer, specify all the input data (hashKey, salt) and the output in hexadecimal dump format plus the number of rounds, the length of the output in bytes.

See this SO answer for sample code.

Update for revised question code:

CCKeyDerivationPBKDF returns 8-bit data bytes, which are essentially not characters, and many of them cannot be printed, even if forced by NSASCIIStringEncoding . Forcing NSASCIIStringEncoding , even if there is no error returned, is incorrect and not useful. Instead, use the returned NSData or convert to Base64 or HexASCII encoding.

Edit

 NSString *myString = [[NSString alloc] initWithData:derivedKey encoding:NSASCIIStringEncoding]; 

Exit: A'Γ–ΒΊ Γ· "ΓΉΓ―Γ³

to

 NSString * myString = [derivedKey base64EncodedStringWithOptions:0]; 

Output: QbTWgbr3FSL57 / MfBQAz4A ==

Note: 1000 rounds are usually considered insufficient, you need to use something in the range from 10,000 to 100,000.

Timing on iPhone 6S:

  rounds seconds
 1000 0.003  
 10000 0.032  
 100000 0.309  
 1,000,000 3,047  
+3
source

Source: https://habr.com/ru/post/1234420/


All Articles