This repository has been archived by the owner on Oct 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
MYPublicKey.m
234 lines (189 loc) · 7.68 KB
/
MYPublicKey.m
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//
// MYPublicKey.m
// MYCrypto
//
// Created by Jens Alfke on 3/21/09.
// Copyright 2009 Jens Alfke. All rights reserved.
//
#import "MYPublicKey.h"
#import "MYCrypto_Private.h"
#import "MYDigest.h"
#import "MYASN1Object.h"
#import "MYDEREncoder.h"
#import "MYBERParser.h"
#import "MYErrorUtils.h"
#import <CommonCrypto/CommonDigest.h>
@interface MYPublicKey ()
@property (strong) MYCertificate *certificate;
@end
#pragma mark -
@implementation MYPublicKey
- (id) initWithModulus: (NSData*)modulus exponent: (unsigned)exponent {
// An RSA key is encoded in ASN.1 as a sequence of modulus and exponent, both as integers.
MYASN1BigInteger *modulusInt = [[MYASN1BigInteger alloc] initWithUnsignedData: modulus];
id asn1 = @[ modulusInt, @(exponent) ];
NSData *keyData = [MYDEREncoder encodeRootObject: asn1 error: nil];
return [self initWithKeyData: keyData];
}
@synthesize certificate=_certificate;
- (SecExternalItemType) keyClass {
#if MYCRYPTO_USE_IPHONE_API
return kSecAttrKeyClassPublic;
#else
return kSecItemTypePublicKey;
#endif
}
#if MYCRYPTO_USE_IPHONE_API
- (SecExternalItemType) keyType {
return kSecAttrKeyTypeRSA;
}
#endif
- (NSUInteger)hash {
return self.publicKeyDigest.hash;
}
- (NSString*) description {
return $sprintf(@"%@[%@]", [self class], self.publicKeyDigest.abbreviatedHexString);
}
- (MYSHA1Digest*) publicKeyDigest {
if (!_digest)
_digest = [self _keyDigest];
return _digest;
}
#if MYCRYPTO_USE_IPHONE_API
- (NSData*) keyData {
if (_certificate) {
return _certificate.info.subjectPublicKeyData;
} else {
return [super keyData];
}
}
#endif
#if !MYCRYPTO_USE_IPHONE_API
- (SecExternalFormat) _externalFormat {
return kSecFormatBSAFE;
}
#endif
- (BOOL) getModulus: (NSData**)outModulus exponent: (unsigned*)outExponent {
Assert(outModulus!=nil);
Assert(outExponent!=nil);
NSArray *asn1 = $castIf(NSArray, MYBERParse(self.keyData, nil));
if (!asn1 || asn1.count != 2)
return NO;
*outModulus = $castIf(MYASN1BigInteger, asn1[0]).unsignedData;
*outExponent = $castIf(NSNumber, asn1[1]).unsignedIntValue;
return (*outModulus!=nil && *outExponent>=3);
}
- (NSData*) rawEncryptData: (NSData*)data {
return [self _crypt: data operation: YES];
}
#if !MYCRYPTO_USE_IPHONE_API
- (BOOL) verifySignature: (NSData*)signature
ofData: (NSData*)data
withAlgorithm:(CSSM_ALGORITHMS)algorithm
{
Assert(data);
Assert(signature);
CSSM_CC_HANDLE ccHandle = [self _createSignatureContext: algorithm];
if (!ccHandle) return NO;
CSSM_DATA original = {data.length, (void*)data.bytes};
CSSM_DATA sig = {signature.length, (void*)signature.bytes};
CSSM_RETURN cssmErr = CSSM_VerifyData(ccHandle, &original, 1, CSSM_ALGID_NONE, &sig);
CSSM_DeleteContext(ccHandle);
if (cssmErr == CSSM_OK)
return YES;
if (cssmErr != CSSMERR_CSP_VERIFY_FAILED)
Warn(@"CSSM error verifying signature: %@", MYErrorName(MYCSSMErrorDomain,cssmErr));
return NO;
}
#endif
- (BOOL) verifySignature: (NSData*)signature ofData: (NSData*)data {
#if MYCRYPTO_USE_IPHONE_API
Assert(data);
Assert(signature);
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes,data.length, digest);
OSStatus err = SecKeyRawVerify(self.keyRef, kSecPaddingPKCS1SHA1,
digest,sizeof(digest),
signature.bytes, signature.length);
return err==noErr;
#else
return [self verifySignature: signature ofData: data withAlgorithm: CSSM_ALGID_SHA1WithRSA];
#endif
}
#if !TARGET_OS_IPHONE
- (CSSM_WRAP_KEY*) _unwrappedCSSMKey {
const CSSM_KEY *key = self.cssmKey;
if (key->KeyHeader.BlobType == CSSM_KEYBLOB_WRAPPED) {
Warn(@"Key is already wrapped.\n");
return NULL;
}
if (key->KeyHeader.KeyClass != CSSM_KEYCLASS_PUBLIC_KEY)
Warn(@"Warning: Null wrapping a non-public key - this is a dangerous operation.\n");
const CSSM_ACCESS_CREDENTIALS* credentials;
credentials = [self cssmCredentialsForOperation: CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED
type: kSecCredentialTypeDefault error: nil];
CSSM_CC_HANDLE ccHandle;
if (!checkcssm(CSSM_CSP_CreateSymmetricContext(self.cssmCSPHandle,
CSSM_ALGID_NONE, CSSM_ALGMODE_WRAP,
NULL, NULL, NULL,
CSSM_PADDING_NONE, NULL,
&ccHandle),
@"CSSM_CSP_CreateSymmetricContext"))
return NULL;
CSSM_WRAP_KEY *result = malloc(sizeof(CSSM_WRAP_KEY));
if (!checkcssm(CSSM_WrapKey(ccHandle, credentials, key, NULL, result),
@"CSSM_WrapKey")) {
free(result);
result = NULL;
}
CSSM_DeleteContext(ccHandle);
return result;
}
- (NSData*) wrapSessionKey: (MYSymmetricKey*)sessionKey {
const CSSM_ACCESS_CREDENTIALS* credentials;
credentials = [self cssmCredentialsForOperation: CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED
type: kSecCredentialTypeDefault error: nil];
CSSM_CSP_HANDLE cspHandle = self.cssmCSPHandle;
CSSM_CC_HANDLE ctx;
if (!checkcssm(CSSM_CSP_CreateAsymmetricContext(cspHandle,
self.cssmAlgorithm,
credentials,
self.cssmKey,
CSSM_PADDING_PKCS1,
&ctx),
@"CSSM_CSP_CreateAsymmetricContext"))
return nil;
// Now wrap the key:
NSData *result = nil;
CSSM_WRAP_KEY wrappedKey = {};
CSSM_DATA descriptiveData = {};
if (checkcssm(CSSM_WrapKey(ctx, credentials, sessionKey.cssmKey, &descriptiveData, &wrappedKey),
@"CSSM_WrapKey")) {
// ...and copy the wrapped key data to the result NSData:
result = [NSData dataWithBytes: wrappedKey.KeyData.Data length: wrappedKey.KeyData.Length];
CSSM_FreeKey(cspHandle, credentials, &wrappedKey, NO);
}
// Finally, delete the context
CSSM_DeleteContext(ctx);
return result;
}
#endif
@end
/*
Copyright (c) 2009, Jens Alfke <jens@mooseyard.com>. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/