4 * Copyright (c) 2010,2012 Apple Inc. All Rights Reserved.
8 #include "Security/SecPBKDF.h"
9 #include "Security/pbkdf2.h"
11 #include <CommonCrypto/CommonHMAC.h>
15 /* CC Based HMAC PRF functions */
16 void hmac_sha1_PRF(const uint8_t *key
,
20 uint8_t digest
[CC_SHA1_DIGEST_LENGTH
])
22 CCHmacContext hmac_sha1_context
;
24 CCHmacInit(&hmac_sha1_context
, kCCHmacAlgSHA1
, key
, key_len
);
25 CCHmacUpdate(&hmac_sha1_context
, text
, text_len
);
26 CCHmacFinal(&hmac_sha1_context
, digest
);
29 void hmac_sha256_PRF(const uint8_t *key
,
33 uint8_t digest
[CC_SHA256_DIGEST_LENGTH
])
35 CCHmacContext hmac_sha256_context
;
37 CCHmacInit(&hmac_sha256_context
, kCCHmacAlgSHA256
, key
, key_len
);
38 CCHmacUpdate(&hmac_sha256_context
, text
, text_len
);
39 CCHmacFinal(&hmac_sha256_context
, digest
);
43 /* This implements the HMAC SHA-1 version of pbkdf2 and allocates a local buffer for the HMAC */
44 void pbkdf2_hmac_sha1(const uint8_t *passwordPtr
, size_t passwordLen
,
45 const uint8_t *saltPtr
, size_t saltLen
,
46 uint32_t iterationCount
,
47 void *dkPtr
, size_t dkLen
)
49 // MAX(salt_length + 4, 20 /* SHA1 Digest size */) + 2 * 20;
50 // salt_length + HASH_SIZE is bigger than either salt + 4 and digestSize.
51 const size_t kBigEnoughSize
= (saltLen
+ CC_SHA1_DIGEST_LENGTH
) + 2 * CC_SHA1_DIGEST_LENGTH
;
52 uint8_t temp_data
[kBigEnoughSize
];
54 pbkdf2(hmac_sha1_PRF
, CC_SHA1_DIGEST_LENGTH
,
55 passwordPtr
, passwordLen
,
61 bzero(temp_data
, kBigEnoughSize
);
64 /* This implements the HMAC SHA-256 version of pbkdf2 and allocates a local buffer for the HMAC */
65 void pbkdf2_hmac_sha256(const uint8_t *passwordPtr
, size_t passwordLen
,
66 const uint8_t *saltPtr
, size_t saltLen
,
67 uint32_t iterationCount
,
68 void *dkPtr
, size_t dkLen
)
70 // MAX(salt_length + 4, 32 /* SHA1 Digest size */) + 2 * 32;
71 // salt_length + HASH_SIZE is bigger than either salt + 4 and digestSize.
72 const size_t kBigEnoughSize
= (saltLen
+ CC_SHA256_DIGEST_LENGTH
) + 2 * CC_SHA256_DIGEST_LENGTH
;
73 uint8_t temp_data
[kBigEnoughSize
];
75 pbkdf2(hmac_sha256_PRF
, CC_SHA256_DIGEST_LENGTH
,
76 passwordPtr
, passwordLen
,
82 bzero(temp_data
, kBigEnoughSize
);
85 void SecKeyFromPassphraseDataHMACSHA1(CFDataRef password
, CFDataRef salt
, uint32_t interationCount
, CFMutableDataRef derivedKey
)
87 pbkdf2_hmac_sha1(CFDataGetBytePtr(password
), CFDataGetLength(password
),
88 CFDataGetBytePtr(salt
), CFDataGetLength(salt
),
90 CFDataGetMutableBytePtr(derivedKey
), CFDataGetLength(derivedKey
));
94 void SecKeyFromPassphraseDataHMACSHA256(CFDataRef password
, CFDataRef salt
, uint32_t interationCount
, CFMutableDataRef derivedKey
)
96 pbkdf2_hmac_sha256(CFDataGetBytePtr(password
), CFDataGetLength(password
),
97 CFDataGetBytePtr(salt
), CFDataGetLength(salt
),
99 CFDataGetMutableBytePtr(derivedKey
), CFDataGetLength(derivedKey
));