-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
pal_seckey.c
107 lines (85 loc) · 3.13 KB
/
pal_seckey.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_seckey.h"
#include "pal_utilities.h"
uint64_t AppleCryptoNative_SecKeyGetSimpleKeySizeInBytes(SecKeyRef publicKey)
{
if (publicKey == NULL)
{
return 0;
}
return SecKeyGetBlockSize(publicKey);
}
static CFStringRef GetKeyAlgorithmIdentifier(PAL_KeyAlgorithm keyAlgorithm)
{
if (keyAlgorithm == PAL_KeyAlgorithm_EC)
return kSecAttrKeyTypeECSECPrimeRandom;
if (keyAlgorithm == PAL_KeyAlgorithm_RSA)
return kSecAttrKeyTypeRSA;
return NULL;
}
int32_t AppleCryptoNative_SecKeyCreateWithData(uint8_t* pKey,
int32_t cbKey,
PAL_KeyAlgorithm keyAlgorithm,
int32_t isPublic,
SecKeyRef* pKeyOut,
CFErrorRef* pErrorOut)
{
assert(pKey != NULL);
assert(cbKey > 0);
assert(pKeyOut != NULL);
assert(pErrorOut != NULL);
*pKeyOut = NULL;
*pErrorOut = NULL;
CFMutableDictionaryRef dataAttributes = CFDictionaryCreateMutable(
kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (dataAttributes == NULL)
{
return kErrorUnknownState;
}
CFStringRef keyClass = isPublic == 0 ? kSecAttrKeyClassPrivate : kSecAttrKeyClassPublic;
CFStringRef keyType = GetKeyAlgorithmIdentifier(keyAlgorithm);
assert(keyType != NULL);
CFDictionarySetValue(dataAttributes, kSecAttrKeyType, keyType);
CFDictionarySetValue(dataAttributes, kSecAttrKeyClass, keyClass);
CFDataRef cfData = CFDataCreateWithBytesNoCopy(NULL, pKey, cbKey, kCFAllocatorNull);
*pKeyOut = SecKeyCreateWithData(cfData, dataAttributes, pErrorOut);
CFRelease(cfData);
CFRelease(dataAttributes);
return *pKeyOut != NULL ? 1 : kErrorSeeError;
}
int32_t AppleCryptoNative_SecKeyCopyExternalRepresentation(SecKeyRef pKey,
CFDataRef* ppDataOut,
CFErrorRef* pErrorOut)
{
assert(pKey != NULL);
assert(ppDataOut != NULL);
assert(pErrorOut != NULL);
*pErrorOut = NULL;
*ppDataOut = NULL;
int32_t ret = 0;
CFDictionaryRef attributes = SecKeyCopyAttributes(pKey);
if (attributes != NULL)
{
if (CFDictionaryGetValue(attributes, kSecAttrIsExtractable) == kCFBooleanFalse)
{
ret = kKeyIsNotExtractable;
}
else if (CFDictionaryGetValue(attributes, kSecAttrIsSensitive) == kCFBooleanTrue)
{
ret = kKeyIsSensitive;
}
CFRelease(attributes);
}
if (ret == 0)
{
*ppDataOut = SecKeyCopyExternalRepresentation(pKey, pErrorOut);
ret = *ppDataOut == NULL ? kErrorSeeError : 1;
}
return ret;
}
SecKeyRef AppleCryptoNative_SecKeyCopyPublicKey(SecKeyRef privateKey)
{
assert(privateKey != NULL);
return SecKeyCopyPublicKey(privateKey);
}