Initial checkin. Passes tests on Mac and in iPhone simulator.
5 // Created by Jens Alfke on 3/22/09.
6 // Copyright 2009 Jens Alfke. All rights reserved.
11 #import "MYCrypto_Private.h"
16 @implementation MYKeyPair
19 + (MYKeyPair*) _generateKeyPairOfSize: (unsigned)keySize inKeychain: (MYKeychain*)keychain {
20 Assert( keySize == 512 || keySize == 1024 || keySize == 2048, @"Unsupported key size %u", keySize );
21 SecKeyRef pubKey=NULL, privKey=NULL;
23 NSDictionary *pubKeyAttrs = $dict({(id)kSecAttrIsPermanent, $true});
24 NSDictionary *privKeyAttrs = $dict({(id)kSecAttrIsPermanent, $true});
25 NSDictionary *keyAttrs = $dict( {(id)kSecAttrKeyType, (id)kSecAttrKeyTypeRSA},
26 {(id)kSecAttrKeySizeInBits, $object(keySize)},
27 {(id)kSecPublicKeyAttrs, pubKeyAttrs},
28 {(id)kSecPrivateKeyAttrs, privKeyAttrs} );
29 err = SecKeyGeneratePair((CFDictionaryRef)keyAttrs,&pubKey,&privKey);
31 Warn(@"Failed to create key-pair: %i", err);
34 return [[[self alloc] initWithPublicKeyRef: pubKey privateKeyRef: privKey] autorelease];
37 - (id) initWithPublicKeyRef: (SecKeyRef)publicKey privateKeyRef: (SecKeyRef)privateKey {
38 self = [super initWithKeyRef: publicKey];
40 NSParameterAssert(privateKey);
41 _privateKey = (SecKeyRef) CFRetain(privateKey);
47 - (NSArray*) _itemList {
48 return $array((id)_privateKey,(id)self.keyRef);
52 @synthesize privateKeyRef=_privateKey;
55 - (NSData*) decryptData: (NSData*)data {
56 return _crypt(_privateKey,data,kCCDecrypt);
60 - (NSData*) signData: (NSData*)data {
62 uint8_t digest[CC_SHA1_DIGEST_LENGTH];
63 CC_SHA1(data.bytes,data.length, digest);
66 uint8_t sigBuf[sigLen];
67 OSStatus err = SecKeyRawSign(_privateKey, kSecPaddingPKCS1SHA1,
68 digest,sizeof(digest), //data.bytes, data.length,
71 Warn(@"SecKeyRawSign failed: %i",err);
74 return [NSData dataWithBytes: sigBuf length: sigLen];