Added CCM and CCM_8 cipher suites.
[BoarSSL] / Crypto / RNG.cs
1 /*
2 * Copyright (c) 2017 Thomas Pornin <pornin@bolet.org>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25 using System;
26 using System.Text;
27
28 using NC = System.Security.Cryptography;
29
30 namespace Crypto {
31
32 /*
33 * Random generator.
34 */
35
36 public sealed class RNG {
37
38 /*
39 * To ensure efficient generation of random numbers, we use
40 * our own PRNG, seeded with a strong value (from the operating
41 * system), and based on AES-CTR. We obtain a random 128-bit
42 * key from the OS (RNGCryptoServiceProvider); then we use it
43 * to encrypt successive values for a 128-bit counter (also
44 * initialized from RNGCryptoServiceProvider). This is AES-CTR
45 * mode and thus provably as strong as AES-128 encryption as it
46 * is practiced in SSL/TLS.
47 *
48 * A mutex is used to ensure safe access in a multi-threaded
49 * context. Once initialized, random generation proceeds at
50 * the same speed as AES encryption, i.e. fast enough for
51 * our purposes.
52 *
53 * As a special action for debugging, it is possible to reset
54 * the state to an explicit seed value. Of course, this tends
55 * to kill security, so it should be used only to make actions
56 * reproducible, as part of systematic tests.
57 */
58
59 static object rngMutex = new object();
60 static IBlockCipher rngAES = null;
61 static byte[] counter, rblock;
62
63 static void Init()
64 {
65 if (rngAES == null) {
66 NC.RNGCryptoServiceProvider srng =
67 new NC.RNGCryptoServiceProvider();
68 byte[] key = new byte[16];
69 byte[] iv = new byte[16];
70 srng.GetBytes(key);
71 srng.GetBytes(iv);
72 Init(key, iv);
73 }
74 }
75
76 static void Init(byte[] key, byte[] iv)
77 {
78 if (rngAES == null) {
79 rngAES = new AES();
80 counter = new byte[16];
81 rblock = new byte[16];
82 }
83 rngAES.SetKey(key);
84 Array.Copy(iv, 0, rblock, 0, 16);
85 }
86
87 static void NextBlock()
88 {
89 int len = counter.Length;
90 int carry = 1;
91 for (int i = 0; i < len; i ++) {
92 int v = counter[i] + carry;
93 counter[i] = (byte)v;
94 carry = v >> 8;
95 }
96 Array.Copy(counter, 0, rblock, 0, len);
97 rngAES.BlockEncrypt(rblock);
98 }
99
100 /*
101 * Set or reset the state to the provided seed. All subsequent
102 * output will depend only on that seed value. This function shall
103 * be used ONLY for debug/test purposes, since it replaces the
104 * automatic seeding that uses OS-provided entropy.
105 */
106 public static void SetSeed(byte[] seed)
107 {
108 byte[] s32 = new SHA256().Hash(seed);
109 byte[] key = new byte[16];
110 byte[] iv = new byte[16];
111 Array.Copy(s32, 0, key, 0, 16);
112 Array.Copy(s32, 16, iv, 0, 16);
113 lock (rngMutex) {
114 Init(key, iv);
115 }
116 }
117
118 /*
119 * Fill the provided array with random bytes.
120 */
121 public static void GetBytes(byte[] buf)
122 {
123 GetBytes(buf, 0, buf.Length);
124 }
125
126 /*
127 * Fill the provided array chunk with random bytes.
128 */
129 public static void GetBytes(byte[] buf, int off, int len)
130 {
131 lock (rngMutex) {
132 Init();
133 while (len > 0) {
134 NextBlock();
135 int clen = Math.Min(len, rblock.Length);
136 Array.Copy(rblock, 0, buf, off, clen);
137 off += clen;
138 len -= clen;
139 }
140 }
141 }
142
143 /*
144 * Get a new random 32-bit integer (uniform generation).
145 */
146 public static uint U32()
147 {
148 lock (rngMutex) {
149 Init();
150 NextBlock();
151 return (uint)rblock[0]
152 | ((uint)rblock[1] << 8)
153 | ((uint)rblock[2] << 16)
154 | ((uint)rblock[3] << 24);
155 }
156 }
157
158 /*
159 * Convert integer value x (0 to 15) to an hexadecimal character
160 * (lowercase).
161 */
162 static char ToHex(int x)
163 {
164 int hi = -(((x + 6) >> 4) & 1);
165 return (char)(x + 48 + (hi & 39));
166 }
167
168 /*
169 * Get a string of random hexadecimal characters. The 'len'
170 * parameter specifies the string length in characters (it
171 * may be odd).
172 */
173 public static string GetHex(int len)
174 {
175 byte[] buf = new byte[(len + 1) >> 1];
176 GetBytes(buf);
177 StringBuilder sb = new StringBuilder();
178 foreach (byte b in buf) {
179 sb.Append(b >> 4);
180 sb.Append(b & 15);
181 }
182 string s = sb.ToString();
183 if (s.Length > len) {
184 s = s.Substring(0, len);
185 }
186 return s;
187 }
188
189 /*
190 * Get a sequence of random non-zero bytes.
191 */
192 public static void GetBytesNonZero(byte[] buf)
193 {
194 GetBytesNonZero(buf, 0, buf.Length);
195 }
196
197 /*
198 * Get a sequence of random non-zero bytes.
199 */
200 public static void GetBytesNonZero(byte[] buf, int off, int len)
201 {
202 if (len <= 0) {
203 return;
204 }
205 lock (rngMutex) {
206 Init();
207 for (;;) {
208 NextBlock();
209 for (int i = 0; i < rblock.Length; i ++) {
210 byte x = rblock[i];
211 if (x == 0) {
212 continue;
213 }
214 buf[off ++] = x;
215 if (-- len == 0) {
216 return;
217 }
218 }
219 }
220 }
221 }
222 }
223
224 }