Swift: How to Call Cckeyderivationpbkdf from Swift

Swift: How to call CCKeyDerivationPBKDF from Swift

Swift 3:

Password Based Key Derivation can be used both for deriving an encryption key from password text and saving a password for authentication purposes.

There are several hash algorithms that can be used including SHA1, SHA256, SHA512 which are provided by this example code.

The rounds parameter is used to make the calculation slow so that an attacker will have to spend substantial time on each attempt. Typical delay values fall in the 100ms to 500ms, shorter values can be used if there is unacceptable performance.

This example requires Common Crypto

It is necessary to have a bridging header to the project:

#import <CommonCrypto/CommonCrypto.h>

Add the Security.framework to the project.

Parameters:

password     password String  
salt salt Data
keyByteCount number of key bytes to generate
rounds Iteration rounds

returns Derived key


func pbkdf2SHA1(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA1), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA512(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA512), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2(hash :CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
let passwordData = password.data(using:String.Encoding.utf8)!
var derivedKeyData = Data(repeating:0, count:keyByteCount)

let derivationStatus = derivedKeyData.withUnsafeMutableBytes {derivedKeyBytes in
salt.withUnsafeBytes { saltBytes in

CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password, passwordData.count,
saltBytes, salt.count,
hash,
UInt32(rounds),
derivedKeyBytes, derivedKeyData.count)
}
}
if (derivationStatus != 0) {
print("Error: \(derivationStatus)")
return nil;
}

return derivedKeyData
}

Example usage:

let password     = "password"
//let salt = "saltData".data(using: String.Encoding.utf8)!
let salt = Data(bytes: [0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let keyByteCount = 16
let rounds = 100000

let derivedKey = pbkdf2SHA1(password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
print("derivedKey (SHA1): \(derivedKey! as NSData)")

Example Output:

derivedKey (SHA1): <6b9d4fa3 0385d128 f6d196ee 3f1d6dbf>

Swift 2.x:

Minor changes of argument type and class to instance method for testing.

func generateAesKeyForPassword(password: String, salt: NSData, roundCount: Int?, error: NSErrorPointer) -> (key: NSData, actualRoundCount: UInt32)?
{
let nsDerivedKey = NSMutableData(length: kCCKeySizeAES256)
var actualRoundCount: UInt32

// Create Swift intermediates for clarity in function calls
let algorithm: CCPBKDFAlgorithm = CCPBKDFAlgorithm(kCCPBKDF2)
let prf: CCPseudoRandomAlgorithm = CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256)
let saltBytes = UnsafePointer<UInt8>(salt.bytes)
let saltLength = size_t(salt.length)
let nsPassword = password as NSString
let nsPasswordPointer = UnsafePointer<Int8>(nsPassword.cStringUsingEncoding(NSUTF8StringEncoding))
let nsPasswordLength = size_t(nsPassword.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
var nsDerivedKeyPointer = UnsafeMutablePointer<UInt8>(nsDerivedKey.mutableBytes)
let nsDerivedKeyLength = size_t(nsDerivedKey.length)
let msec: UInt32 = 300

if roundCount != nil {
actualRoundCount = UInt32(roundCount!)
}
else {
actualRoundCount = CCCalibratePBKDF(
algorithm,
nsPasswordLength,
saltLength,
prf,
nsDerivedKeyLength,
msec);
}

let result = CCKeyDerivationPBKDF(
algorithm,
nsPasswordPointer, nsPasswordLength,
saltBytes, saltLength,
prf, actualRoundCount,
nsDerivedKeyPointer, nsDerivedKeyLength)

if result != 0 {
let errorDescription = "CCKeyDerivationPBKDF failed with error: '\(result)'"
// error.memory = MyError(domain: ClientErrorType.errorDomain, code: Int(result), descriptionText: errorDescription)
return nil
}

return (nsDerivedKey, actualRoundCount)
}

// Added bonus:

func salt(#length:UInt) -> NSData {
let salt = NSMutableData(length: Int(length))
var saltPointer = UnsafeMutablePointer<UInt8>(salt.mutableBytes)
SecRandomCopyBytes(kSecRandomDefault, length, saltPointer);
return salt
}

// Test call:

let password   = "test pass"
let salt = self.salt(length:32)
let roundCount = 300
var error: NSError?

let result = self.generateAesKeyForPassword(password, salt:salt, roundCount:roundCount, error:&error)
println("result: \(result)")

Output:

result: Optional((<d279ab8d 8ace67b7 abec844c b9979d20 f2bb0a7f 5af70502 085bf1e4 1016b20c>, 300))

CCKeyDerivationPBKDF using HMAC SHA1 often return -1

I notice you are using kCCHmacAlgSHA1 instead of kCCPRFHmacAlgSHA1, that is probably the error.

This works for me:

NSData *keyData = [@"password" dataUsingEncoding:NSUTF8StringEncoding];
NSData *salt = [@"salt" dataUsingEncoding:NSUTF8StringEncoding];
uint rounds = 2048;
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
derivedKey.length); // derivedKeyLen

NSLog(@"derivedKey: %@", derivedKey);

Output:

derivedKey: <2c13cb7a d3468748 5c3f3d4f 18ebddbd>

Swift 3

let password = "TestPassword"
let salt = Data("salt" .utf8);
let keySize = kCCKeySizeAES128;
let rounds = 2048

var derivedKeyData = Data(repeating:0, count:keySize)

let derivationStatus = derivedKeyData.withUnsafeMutableBytes {derivedKeyBytes in
salt.withUnsafeBytes { saltBytes in

CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password, password.utf8.count,
saltBytes, salt.count,
UInt32(kCCPRFHmacAlgSHA1),
UInt32(rounds),
derivedKeyBytes,
derivedKeyData.count)
}
}

print("derivedKeyData: \(derivedKeyData.map { String(format: "%02hhx", $0) }.joined())")

Output:

derivedKeyData: 75d1f85fd64d170b3ffe66c7f1d1519a

A more general solution from the sunsetted documentation section:

Password Based Key Derivation 2 (Swift 3+)

Password Based Key Derivation can be used both for deriving an encryption key from password text and saving a password for authentication purposes.

There are several hash algorithms that can be used including SHA1, SHA256, SHA512 which are provided by this example code.

The rounds parameter is used to make the calculation slow so that an attacker will have to spend substantial time on each attempt. Typical delay values fall in the 100ms to 500ms, shorter values can be used if there is unacceptable performance.

This example requires Common Crypto

It is necessary to have a bridging header to the project:

#import <CommonCrypto/CommonCrypto.h>

Add the Security.framework to the project.

Parameters:

password     password String  
salt salt Data
keyByteCount number of key bytes to generate
rounds Iteration rounds

returns Derived key


func pbkdf2SHA1(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA1), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA512(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA512), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2(hash :CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
let passwordData = password.data(using:String.Encoding.utf8)!
var derivedKeyData = Data(repeating:0, count:keyByteCount)

let derivationStatus = derivedKeyData.withUnsafeMutableBytes {derivedKeyBytes in
salt.withUnsafeBytes { saltBytes in

CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password, passwordData.count,
saltBytes, salt.count,
hash,
UInt32(rounds),
derivedKeyBytes, derivedKeyData.count)
}
}
if (derivationStatus != 0) {
print("Error: \(derivationStatus)")
return nil;
}

return derivedKeyData
}

Example usage:

let password     = "password"
//let salt = "saltData".data(using: String.Encoding.utf8)!
let salt = Data(bytes: [0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let keyByteCount = 16
let rounds = 100000

let derivedKey = pbkdf2SHA1(password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
print("derivedKey (SHA1): \(derivedKey! as NSData)")

Example Output:

derivedKey (SHA1): <6b9d4fa3 0385d128 f6d196ee 3f1d6dbf>

Password Based Key Derivation Calibration (Swift 3+)

Determine the number of PRF rounds to use for a specific delay on the current platform.

Several parameters are defaulted to representative values that should not materially affect the round count.

password Sample password.  
salt Sample salt.
msec Targeted duration we want to achieve for a key derivation.

returns The number of iterations to use for the desired processing time.


func pbkdf2SHA1Calibrate(password: String, salt: Data, msec: Int) -> UInt32 {
let actualRoundCount: UInt32 = CCCalibratePBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password.utf8.count,
salt.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1),
kCCKeySizeAES256,
UInt32(msec));
return actualRoundCount
}

Example usage:

let saltData       = Data(bytes: [0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let passwordString = "password"
let delayMsec = 100

let rounds = pbkdf2SHA1Calibrate(password:passwordString, salt:saltData, msec:delayMsec)
print("For \(delayMsec) msec delay, rounds: \(rounds)")

Example Output:

For 100 msec delay, rounds: 93457

How to use CommonCrypto for PBKDF2 in Swift 2 & 3

func pbkdf2(hash :CCPBKDFAlgorithm, password: String, salt: [UInt8], keyCount: Int, rounds: UInt32!) -> [UInt8]! {
let derivedKey = [UInt8](count:keyCount, repeatedValue:0)
let passwordData = password.dataUsingEncoding(NSUTF8StringEncoding)!

let derivationStatus = CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
UnsafePointer<Int8>(passwordData.bytes), passwordData.length,
UnsafePointer<UInt8>(salt), salt.count,
CCPseudoRandomAlgorithm(hash),
rounds,
UnsafeMutablePointer<UInt8>(derivedKey),
derivedKey.count)


if (derivationStatus != 0) {
print("Error: \(derivationStatus)")
return nil;
}

return derivedKey
}

hash is the hash type such as kCCPRFHmacAlgSHA1, kCCPRFHmacAlgSHA256, kCCPRFHmacAlgSHA512.

Example from sunsetted documentation section:

Password Based Key Derivation 2 (Swift 3+)

Password Based Key Derivation can be used both for deriving an encryption key from password text and saving a password for authentication purposes.

There are several hash algorithms that can be used including SHA1, SHA256, SHA512 which are provided by this example code.

The rounds parameter is used to make the calculation slow so that an attacker will have to spend substantial time on each attempt. Typical delay values fall in the 100ms to 500ms, shorter values can be used if there is unacceptable performance.

This example requires Common Crypto

It is necessary to have a bridging header to the project:

#import <CommonCrypto/CommonCrypto.h>

Add the Security.framework to the project.

Parameters:

password     password String  
salt salt Data
keyByteCount number of key bytes to generate
rounds Iteration rounds

returns Derived key


func pbkdf2SHA1(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA1), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA512(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA512), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2(hash :CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
let passwordData = password.data(using:String.Encoding.utf8)!
var derivedKeyData = Data(repeating:0, count:keyByteCount)

let derivationStatus = derivedKeyData.withUnsafeMutableBytes {derivedKeyBytes in
salt.withUnsafeBytes { saltBytes in

CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password, passwordData.count,
saltBytes, salt.count,
hash,
UInt32(rounds),
derivedKeyBytes, derivedKeyData.count)
}
}
if (derivationStatus != 0) {
print("Error: \(derivationStatus)")
return nil;
}

return derivedKeyData
}

Example usage:

let password     = "password"
//let salt = "saltData".data(using: String.Encoding.utf8)!
let salt = Data(bytes: [0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let keyByteCount = 16
let rounds = 100000

let derivedKey = pbkdf2SHA1(password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
print("derivedKey (SHA1): \(derivedKey! as NSData)")

Example Output:

derivedKey (SHA1): <6b9d4fa3 0385d128 f6d196ee 3f1d6dbf>

Password Based Key Derivation Calibration

This example requires Common Crypto
It is necessary to have a bridging header to the project:

#import <CommonCrypto/CommonCrypto.h>

Add the Security.framework to the project.


Determine the number of PRF rounds to use for a specific delay on the current platform.

Several parameters are defaulted to representative values that should not materially affect the round count.

password Sample password.  
salt Sample salt.
msec Targeted duration we want to achieve for a key derivation.

returns The number of iterations to use for the desired processing time.

Password Based Key Derivation Calibration (Swift 3)

func pbkdf2SHA1Calibrate(password: String, salt: Data, msec: Int) -> UInt32 {
let actualRoundCount: UInt32 = CCCalibratePBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password.utf8.count,
salt.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1),
kCCKeySizeAES256,
UInt32(msec));
return actualRoundCount
}

Example usage:

let saltData       = Data(bytes: [0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let passwordString = "password"
let delayMsec = 100

let rounds = pbkdf2SHA1Calibrate(password:passwordString, salt:saltData, msec:delayMsec)
print("For \(delayMsec) msec delay, rounds: \(rounds)")

Example Output:

For 100 msec delay, rounds: 93457

Password Based Key Derivation Calibration (Swift 2.3)

func pbkdf2SHA1Calibrate(password:String, salt:[UInt8], msec:Int) -> UInt32 {
let actualRoundCount: UInt32 = CCCalibratePBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password.utf8.count,
salt.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1),
kCCKeySizeAES256,
UInt32(msec));
return actualRoundCount
}

Example usage:

let saltData       = [UInt8]([0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let passwordString = "password"
let delayMsec = 100

let rounds = pbkdf2SHA1Calibrate(passwordString, salt:saltData, msec:delayMsec)
print("For \(delayMsec) msec delay, rounds: \(rounds)")

How to adjust Key Derivation Iterations on iOS Key generation?

As stated in comment, your question is a bit too broad. I am guessing that you are asking about PBKDF2.

You can use CommonCrypto to do that. I used it with Objective-C and it was relatively easy. I think there might be some difficulties to use it with Swift, but Google search has a lot of info how to do that.

You will need to use CommonCrypto function CCKeyDerivationPBKDF - link to docs. There is a round parameter which I think is what you are looking for.

This question might help too.

Converted NSData to Data in Swift, and now when I try to cast bytes to [UInt] I get a crash

The reason you are crashing is this expression:

bytes : UnsafePointer<[UInt]>

You are assuming that the data represents a series of UInt. So a pointer to the start of the data is not as unsafe pointer to a [UInt], an array of UInt; it is an unsafe pointer to a UInt, i.e. the first in the series. You should be saying:

bytes : UnsafePointer<UInt>

So much for the crash. Now let's talk about the thing you are mostly trying to do here.

I'm uncertain what the string format is supposed to do, but I do grasp that the idea of ntohl is to guarantee the endianity of some C long ints (32 bits). So I'll omit the string format part and just talk about how you would take a stream of C long int received into a Data and reverse the endianity of the long ints.

Suppose d is a mutable Data (i.e. declared with var). Then, assuming it represents a sequence of UInt32 little-endian values and you want to convert those to big-endian, you would say:

let ct = d.count/4
d.withUnsafeMutableBytes{
(ptr:UnsafeMutablePointer<UInt32>) in
for ix in 0..<ct {
ptr[ix] = ptr[ix].bigEndian
}
}

Decrypting iOS with Objective c and SwiftUI

the method given in the example you mentioned refers Rob Napiers Github Repo.
Just testet it with your given password, salt, etc.. and it just works!

Yes understood, you want to throw out password: and iv: as well the salt: parameter when decrypting and go only with key:. Well you need at least iv: to do that. But again as Rob commented to your other question, don't re-invent the wheel.

The method i linked above is just working fine with your parameters for decrypting. The only difference to your code is that password, iv and salt are given to decrypt.

apart from the idea you want to develop something that can decrypt without a password you will have to digg deeper into how CCKeyDerivationPBKDF() (CommonKeyDerivation.h) is working.

Edit: As you asked to have a way to pack and unpack your salt, iv and cypher thats pretty simple with NSData.

+ (NSData *)packWithSalt:(NSData*)salt IV:(NSData*)iv Cypher:(NSData*)tocypher {

//adding Salt + IV + Cipher text
NSMutableData *combi = [NSMutableData data];

//[combi appendBytes:salt.bytes length:16];
//[combi appendBytes:iv.bytes length:16]; //16
//[combi appendBytes:tocypher.bytes length:tocypher.length];

[combi appendData:salt];
[combi appendData:iv];
[combi appendData:tocypher];

return combi;
}

+ (NSData*)cypherUnpackToSalt:(NSMutableData**)salt andIV:(NSMutableData**)iv fromPackData:(NSData*)pack {

void *sBuff[16] = {};
void *iBuff[16] = {};
NSUInteger len = pack.length - 16 - 16; //keep length flexible
void *pBuff = malloc(sizeof(Byte)*len); //needs dynamically size of buff
[pack getBytes:sBuff range:NSMakeRange(0, 16)];
[pack getBytes:iBuff range:NSMakeRange(16, 32)];
[pack getBytes:pBuff range:NSMakeRange(32, len)];

[(*salt) replaceBytesInRange:NSMakeRange(0, 16) withBytes:sBuff];
[(*iv) replaceBytesInRange:NSMakeRange(0, 16) withBytes:iBuff];

NSMutableData *unpack = [NSMutableData dataWithLength:len];
[unpack replaceBytesInRange:NSMakeRange(0, len) withBytes:pBuff];
free(pBuff);
return unpack;
}

it should be pretty simple to integrate the encryption and decryption from these two methods.

Proof of concept: Can we pack all together? and Unpack again?

NSData *salt = [CryptAES randomDataOfLength:16];
NSData *iv = [CryptAES randomDataOfLength:16];
NSData *chunk = [CryptAES packWithSalt:salt IV:iv Cypher:plaintextData];
NSLog(@"salt=%@ iv=%@ pack=%@ ",[salt base64EncodedStringWithOptions:0], [iv base64EncodedStringWithOptions:0], [chunk base64EncodedStringWithOptions:0] );

NSMutableData *unSalt = [NSMutableData dataWithLength:16];
NSMutableData *unIv = [NSMutableData dataWithLength:16];
NSData *unchunk = [CryptAES cypherUnpackToSalt:&unSalt andIV:&unIv fromPackData:chunk];
NSString *plainAgain = [[NSString alloc] initWithData:unchunk encoding:NSUTF8StringEncoding];
NSLog(@"salt=%@ iv=%@ unpack=%@",[unSalt base64EncodedStringWithOptions:0], [unIv base64EncodedStringWithOptions:0], plainAgain );

So your decryption method will still need parameters for a password.
Which is not perfect but as you should never throw around encrypted data together with its password - that should be ok - you just keep the handling of a password on the user side. I mean otherwise the whole encryption is useless!

iOS - Password Encryption in Swift

See this question. You should understand the implications of hashing on the client side:

  • Pro: You can use a higher number of rounds, creating a stronger hash.

    For reference, 1Password uses a minimum of 25,000 rounds of PBKDF2-HMAC-SHA512. Your users likely won't be using diceware, so you'll want a higher count if possible.

  • Con: You're locking yourself into a specific algorithm & round count.

    The hash output will in effect become the user's password. You won't be able to tweak things later. This means a weaker hash over time, as computing power increases.

    Also, since the hash grants access to your website, it should be stored in the Keychain.

    Using a salt (appname + username for example) should prevent a server breach from affecting any other sites.

    As the link mentions, you would probably still want to use a "fast" hash (SHA-512 for example) on the server. This limits the damage if only the database is compromised.

    On the server, hashes should be compared in constant time with hash_equals. password_compat has code for earlier versions of PHP.

    defuse recommends a random salt on the server-side when using client-side hashing.

The alternative & more common scenario is to do all hashing on the server.

For PHP, see password_hash, password_verify, and password_needs_rehash.

If you're using an older version of PHP, there's password_compat.



Related Topics



Leave a reply



Submit