1 // Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <openssl/bn.h>
16 #include <openssl/dh.h>
17
18
19 struct wrapped_callback {
20 void (*callback)(int, int, void *);
21 void *arg;
22 };
23
24 // callback_wrapper converts an “old” style generation callback to the newer
25 // |BN_GENCB| form.
callback_wrapper(int event,int n,BN_GENCB * gencb)26 static int callback_wrapper(int event, int n, BN_GENCB *gencb) {
27 struct wrapped_callback *wrapped = (struct wrapped_callback *) gencb->arg;
28 wrapped->callback(event, n, wrapped->arg);
29 return 1;
30 }
31
DH_generate_parameters(int prime_len,int generator,void (* callback)(int,int,void *),void * cb_arg)32 DH *DH_generate_parameters(int prime_len, int generator,
33 void (*callback)(int, int, void *), void *cb_arg) {
34 if (prime_len < 0 || generator < 0) {
35 return nullptr;
36 }
37
38 bssl::UniquePtr<DH> ret(DH_new());
39 if (ret == nullptr) {
40 return nullptr;
41 }
42
43 BN_GENCB gencb_storage;
44 BN_GENCB *cb = nullptr;
45 struct wrapped_callback wrapped;
46 if (callback != nullptr) {
47 wrapped.callback = callback;
48 wrapped.arg = cb_arg;
49
50 cb = &gencb_storage;
51 BN_GENCB_set(cb, callback_wrapper, &wrapped);
52 }
53
54 if (!DH_generate_parameters_ex(ret.get(), prime_len, generator, cb)) {
55 return nullptr;
56 }
57
58 return ret.release();
59 }
60