cc0927f11cd4fcc15661424b0c6ce711c1db83ae
[platform/upstream/libnice.git] / stun / rand.c
1 /*
2  * This file is part of the Nice GLib ICE library.
3  *
4  * (C) 2008 Collabora Ltd. All rights reserved.
5  *  Contact: Youness Alaoui
6  * (C) 2008 Nokia Corporation. All rights reserved.
7  *
8  * The contents of this file are subject to the Mozilla Public License Version
9  * 1.1 (the "License"); you may not use this file except in compliance with
10  * the License. You may obtain a copy of the License at
11  * http://www.mozilla.org/MPL/
12  *
13  * Software distributed under the License is distributed on an "AS IS" basis,
14  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
15  * for the specific language governing rights and limitations under the
16  * License.
17  *
18  * The Original Code is the Nice GLib ICE library.
19  *
20  * The Initial Developers of the Original Code are Collabora Ltd and Nokia
21  * Corporation. All Rights Reserved.
22  *
23  * Alternatively, the contents of this file may be used under the terms of the
24  * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
25  * case the provisions of LGPL are applicable instead of those above. If you
26  * wish to allow use of your version of this file only under the terms of the
27  * LGPL and not to allow others to use your version of this file under the
28  * MPL, indicate your decision by deleting the provisions above and replace
29  * them with the notice and other provisions required by the LGPL. If you do
30  * not delete the provisions above, a recipient may use your version of this
31  * file under either the MPL or the LGPL.
32  */
33
34
35
36 #ifdef HAVE_CONFIG_H
37 # include <config.h>
38 #endif
39
40 #include "rand.h"
41
42
43 #ifdef _WIN32
44
45 #include <windows.h>
46 #include <wincrypt.h>
47
48 void nice_RAND_nonce (uint8_t *dst, int len)
49 {
50   HCRYPTPROV hCryptProv;
51   LPCSTR container = "Libnice key container";
52
53   if(!CryptAcquireContext(&hCryptProv, container, NULL, PROV_RSA_FULL, 0)) {
54     /* non existing container. try to create a new one */
55     // I hope this cast here doesn't cause issues
56     // gcc was complaining about comparing signed and unsigned values
57     if (GetLastError() == (DWORD) NTE_BAD_KEYSET) {
58       if(!CryptAcquireContext(&hCryptProv, container, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
59         return;
60       }
61     }
62     return;
63   }
64
65   CryptGenRandom (hCryptProv, len, dst);
66
67   CryptReleaseContext(hCryptProv,0);
68 }
69 #else
70
71 #ifdef HAVE_OPENSSL
72
73 #include <openssl/rand.h>
74
75 void nice_RAND_nonce (uint8_t *dst, int len)
76 {
77   RAND_bytes (dst, len);
78 }
79
80 #else
81
82 #include <sys/types.h>
83 #include <gnutls/gnutls.h>
84 #include <gnutls/crypto.h>
85
86 void nice_RAND_nonce (uint8_t *dst, int len)
87 {
88   gnutls_rnd (GNUTLS_RND_NONCE, dst, len);
89 }
90
91 #endif /* HAVE_OPENSSL */
92
93 #endif /* _WIN32 */