]> git.saurik.com Git - apple/security.git/blob - OSX/sec/Security/vmdh.c
Security-59754.80.3.tar.gz
[apple/security.git] / OSX / sec / Security / vmdh.c
1 /*
2 * Copyright (c) 2006-2007,2012,2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 /*!
26 @header vmdh
27 The functions provided in vmdh.h implement the crypto exchange required
28 for a Diffie-Hellman voicemail exchange.
29 */
30
31
32 #include "vmdh.h"
33 #include <CommonCrypto/CommonCryptor.h>
34 #include <utilities/debugging.h>
35 #include <string.h>
36 #include <Security/SecInternal.h>
37 #include <Security/SecDH.h>
38
39 vmdh_t vmdh_create(uint32_t g, const uint8_t *p, size_t p_len,
40 const uint8_t *recip, size_t recip_len) {
41 SecDHContext dh;
42 if (SecDHCreate(g, p, p_len, 0/*l*/, recip, recip_len, &dh))
43 return NULL;
44 return (vmdh_t)dh;
45 }
46
47 bool vmdh_generate_key(vmdh_t vmdh, uint8_t *pub_key, size_t *pub_key_len) {
48 return !SecDHGenerateKeypair((SecDHContext)vmdh, pub_key, pub_key_len);
49 }
50
51 bool vmdh_encrypt_password(vmdh_t vmdh,
52 const uint8_t *pub_key, size_t pub_key_len,
53 const uint8_t *pw, size_t pw_len, uint8_t *encpw, size_t *encpw_len) {
54 uint8_t aes_key[kCCKeySizeAES128];
55 size_t aes_key_len = kCCKeySizeAES128;
56
57 if (SecDHComputeKey((SecDHContext)vmdh, pub_key, pub_key_len,
58 aes_key, &aes_key_len)) {
59 return false;
60 }
61
62 /* Use the first 16 bytes in aes_key as an AES key. */
63 if (CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
64 kCCOptionPKCS7Padding, aes_key, kCCKeySizeAES128, NULL,
65 pw, pw_len, encpw, *encpw_len, encpw_len)) {
66 return false;
67 }
68
69 /* Zero out key material. */
70 bzero(aes_key, kCCKeySizeAES128);
71
72 return true;
73 }
74
75 void vmdh_destroy(vmdh_t vmdh) {
76 return SecDHDestroy((SecDHContext)vmdh);
77 }