]> git.saurik.com Git - apple/security.git/blob - AppleCSP/DiffieHellman/DH_exchange.cpp
385f6490ff99c02a8d1aba31fa9399a75ee2d37a
[apple/security.git] / AppleCSP / DiffieHellman / DH_exchange.cpp
1 /*
2 * Copyright (c) 2000-2002 Apple Computer, Inc. All Rights Reserved.
3 *
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
8 * using this file.
9 *
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
16 */
17
18
19 /*
20 * DH_exchange.cp - Diffie-Hellman key exchange
21 */
22
23 #include "DH_exchange.h"
24 #include <Security/cssmerr.h>
25 #include <Security/utilities.h>
26 #include "DH_utils.h"
27 #include <strings.h>
28 #include <open_ssl/opensslUtils/opensslUtils.h>
29
30 void DeriveKey_DH (
31 const Context &context,
32 const CssmData &Param, // other's public key
33 CSSM_DATA *keyData, // mallocd by caller
34 // we fill in keyData->Length bytes
35 AppleCSPSession &session)
36 {
37 bool mallocdKey;
38 size_t privSize;
39
40 /* private DH key from context */
41 DH *privKey = contextToDhKey(context, session, CSSM_KEYUSE_DERIVE,
42 mallocdKey);
43 privSize = DH_size(privKey);
44 if(privSize < keyData->Length) {
45 /* we've been asked for more bits than this key can generate */
46 CssmError::throwMe(CSSMERR_CSP_UNSUPPORTED_KEY_SIZE);
47 }
48 BIGNUM *pubKey = BN_bin2bn(Param.Data, Param.Length, NULL);
49 if(pubKey == NULL) {
50 CssmError::throwMe(CSSMERR_CSP_MEMORY_ERROR);
51 }
52 unsigned char *buf = (unsigned char *)session.malloc(privSize);
53 int rtn = DH_compute_key(buf, pubKey, privKey);
54 if(rtn >= 0) {
55 /*
56 * FIXME : I have not found a specification describing *which*
57 * bytes of the value we just computed we are supposed to
58 * use as the actual key bytes. We use the M.S. bytes.
59 */
60 memmove(keyData->Data, buf, keyData->Length);
61 }
62 if(mallocdKey) {
63 DH_free(privKey);
64 }
65 BN_free(pubKey);
66 session.free(buf);
67 if(rtn < 0) {
68 throwRsaDsa("DH_compute_key");
69 }
70 }
71