-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
pal_keyderivation.c
80 lines (68 loc) · 2.21 KB
/
pal_keyderivation.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_keyderivation.h"
static int32_t PrfAlgorithmFromHashAlgorithm(PAL_HashAlgorithm hashAlgorithm, CCPseudoRandomAlgorithm* algorithm)
{
if (algorithm == NULL)
return 0;
switch (hashAlgorithm)
{
case PAL_SHA1:
*algorithm = kCCPRFHmacAlgSHA1;
return 1;
case PAL_SHA256:
*algorithm = kCCPRFHmacAlgSHA256;
return 1;
case PAL_SHA384:
*algorithm = kCCPRFHmacAlgSHA384;
return 1;
case PAL_SHA512:
*algorithm = kCCPRFHmacAlgSHA512;
return 1;
default:
*algorithm = 0;
return 0;
}
}
int32_t AppleCryptoNative_Pbkdf2(PAL_HashAlgorithm prfAlgorithm,
const char* password,
int32_t passwordLen,
const uint8_t* salt,
int32_t saltLen,
int32_t iterations,
uint8_t* derivedKey,
int32_t derivedKeyLen,
int32_t* errorCode)
{
if (errorCode != NULL)
*errorCode = noErr;
if (passwordLen < 0 || saltLen < 0 || iterations < 0 || derivedKey == NULL ||
derivedKeyLen < 0 || errorCode == NULL)
{
return -1;
}
if (salt == NULL && saltLen != 0)
{
return -1;
}
const char* empty = "";
if (password == NULL)
{
if (passwordLen != 0)
{
return -1;
}
// macOS will not accept a null password, but it will accept a zero-length
// password with a valid pointer.
password = empty;
}
CCPseudoRandomAlgorithm prf;
if (!PrfAlgorithmFromHashAlgorithm(prfAlgorithm, &prf))
{
return -2;
}
CCStatus result = CCKeyDerivationPBKDF(kCCPBKDF2, password, (size_t)passwordLen, salt,
(size_t)saltLen, prf, (uint32_t)iterations, derivedKey, (size_t)derivedKeyLen);
*errorCode = result;
return result == kCCSuccess ? 1 : 0;
}