monotone

monotone Mtn Source Tree

Root/botan/util.cpp

1/*************************************************
2* Utility Functions Source File *
3* (C) 1999-2007 The Botan Project *
4*************************************************/
5
6#include <botan/util.h>
7#include <botan/bit_ops.h>
8#include <algorithm>
9#include <cmath>
10
11namespace Botan {
12
13/*************************************************
14* Round up n to multiple of align_to *
15*************************************************/
16u32bit round_up(u32bit n, u32bit align_to)
17 {
18 if(n % align_to || n == 0)
19 n += align_to - (n % align_to);
20 return n;
21 }
22
23/*************************************************
24* Round down n to multiple of align_to *
25*************************************************/
26u32bit round_down(u32bit n, u32bit align_to)
27 {
28 return (n - (n % align_to));
29 }
30
31/*************************************************
32* Return the work required for solving DL *
33*************************************************/
34u32bit dl_work_factor(u32bit n_bits)
35 {
36 const u32bit MIN_ESTIMATE = 64;
37
38 if(n_bits < 32)
39 return 0;
40
41 const double log_x = n_bits / 1.44;
42
43 const double strength =
44 2.76 * std::pow(log_x, 1.0/3.0) * std::pow(std::log(log_x), 2.0/3.0);
45
46 if(strength > MIN_ESTIMATE)
47 return static_cast<u32bit>(strength);
48 return MIN_ESTIMATE;
49 }
50
51/*************************************************
52* Estimate the entropy of the buffer *
53*************************************************/
54u32bit entropy_estimate(const byte buffer[], u32bit length)
55 {
56 if(length <= 4)
57 return 0;
58
59 u32bit estimate = 0;
60 byte last = 0, last_delta = 0, last_delta2 = 0;
61
62 for(u32bit j = 0; j != length; ++j)
63 {
64 byte delta = last ^ buffer[j];
65 last = buffer[j];
66
67 byte delta2 = delta ^ last_delta;
68 last_delta = delta;
69
70 byte delta3 = delta2 ^ last_delta2;
71 last_delta2 = delta2;
72
73 byte min_delta = delta;
74 if(min_delta > delta2) min_delta = delta2;
75 if(min_delta > delta3) min_delta = delta3;
76
77 estimate += hamming_weight(min_delta);
78 }
79
80 return (estimate / 2);
81 }
82
83}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status