2 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 #include <CoreFoundation/CoreFoundation.h>
26 #include "corecrypto/ccsha1.h"
27 #include "corecrypto/ccrsa_priv.h"
28 #include "corecrypto/ccrng_system.h"
29 #include "corecrypto/ccn.h"
33 // corecrypto headers don't like C++ (on a deaper level then extern "C" {} can fix
34 // so we need a C "shim" for all our corecrypto use.
36 CFDataRef
oaep_padding_via_c(int desired_message_length
, CFDataRef dataValue
);
37 CFDataRef
oaep_padding_via_c(int desired_message_length
, CFDataRef dataValue
)
39 cc_unit paddingBuffer
[ccn_nof_size(desired_message_length
)];
40 bzero(paddingBuffer
, sizeof(cc_unit
) * ccn_nof_size(desired_message_length
)); // XXX needed??
41 static dispatch_once_t randomNumberGenneratorInitialzed
;
42 static struct ccrng_system_state rng
;
43 dispatch_once(&randomNumberGenneratorInitialzed
, ^{
44 ccrng_system_init(&rng
);
47 ccrsa_oaep_encode(ccsha1_di(),
48 (struct ccrng_state
*)&rng
,
49 sizeof(paddingBuffer
), (cc_unit
*)paddingBuffer
,
50 CFDataGetLength(dataValue
), CFDataGetBytePtr(dataValue
));
51 ccn_swap(ccn_nof_size(sizeof(paddingBuffer
)), (cc_unit
*)paddingBuffer
);
53 CFDataRef paddedValue
= CFDataCreate(NULL
, (UInt8
*)paddingBuffer
, desired_message_length
);
54 return paddedValue
? paddedValue
: (void*)GetNoMemoryErrorAndRetain();
57 CFDataRef
oaep_unpadding_via_c(CFDataRef encodedMessage
);
58 CFDataRef
oaep_unpadding_via_c(CFDataRef encodedMessage
)
60 size_t mlen
= CFDataGetLength(encodedMessage
);
61 cc_size n
= ccn_nof_size(mlen
);
62 cc_unit paddingBuffer
[n
];
63 UInt8 plainText
[mlen
];
65 ccn_read_uint(n
, paddingBuffer
, mlen
, CFDataGetBytePtr(encodedMessage
));
66 size_t plainTextLength
= mlen
;
67 int err
= ccrsa_oaep_decode(ccsha1_di(), &plainTextLength
, plainText
, mlen
, paddingBuffer
);
70 // XXX should make a CFError or something.
71 return (void*)fancy_error(CFSTR("CoreCrypto"), err
, CFSTR("OAEP decode error"));
73 CFDataRef result
= CFDataCreate(NULL
, (UInt8
*)plainText
, plainTextLength
);