Initialize Tizen 2.3
[external/nettle.git] / yarrow_key_event.c
1 /* yarrow_key_event.c
2  *
3  * Exampel entropy estimator for key-like input events. */
4
5 /* nettle, low-level cryptographics library
6  *
7  * Copyright (C) 2001 Niels Möller
8  *  
9  * The nettle library is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or (at your
12  * option) any later version.
13  * 
14  * The nettle library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17  * License for more details.
18  * 
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with the nettle library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22  * MA 02111-1307, USA.
23  */
24
25 #if HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include "yarrow.h"
30
31 void
32 yarrow_key_event_init(struct yarrow_key_event_ctx *ctx)
33 {
34   unsigned i;
35   
36   ctx->index = 0;
37   ctx->previous = 0;
38   
39   for (i = 0; i < YARROW_KEY_EVENT_BUFFER; i++)
40     ctx->chars[i] = 0;  
41 }
42
43 unsigned
44 yarrow_key_event_estimate(struct yarrow_key_event_ctx *ctx,
45                           unsigned key, unsigned time)
46 {
47   unsigned entropy = 0;
48   unsigned i;
49
50   /* Look at timing first. */
51   if (ctx->previous && (time > ctx->previous) )
52     {
53       if ( (time - ctx->previous) >= 256)
54         entropy++;
55     }
56   ctx->previous = time;
57
58   if (!key)
59     return entropy;
60   
61   for (i = 0; i < YARROW_KEY_EVENT_BUFFER; i++)
62     if (key == ctx->chars[i])
63       /* This is a recent character. Ignore it. */
64       return entropy;
65
66   /* Count one bit of entropy, unless this was one of the initial 16
67    * characters. */
68   if (ctx->chars[ctx->index])
69     entropy++;
70   
71   /* Remember the character. */
72   
73   ctx->chars[ctx->index] = key;
74   ctx->index = (ctx->index + 1) % YARROW_KEY_EVENT_BUFFER;
75
76   return entropy;
77 }
78