Mã hóa văn bản

  1. / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

  2.  *  teta.h                                                                    *

    Bạn đang đọc: Mã hóa văn bản

  3. * *

  4. * ASCII text stream integrated encryptor – authenticator *

  5. * in EtA ( Encrypt-then-Authenticate ) mode *

  6. * * * This program is only a DEMO of cryptographic algorithms. *

  7. * * * Do NOT use it for serious purposes. *

  8. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /

  9. / / see teta-docs.txt for problem specification and algorithm description

  10. / * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

  11. # #

  12. # #

  13. # SPEC #

  14. # #

  15. # #

  16. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # * /

  17. # pragma once

  18. / / msvc specifics

  19. # if defined ( _MSC_VER )

  20. # define __MSC__

  21. / / Disable throw, precedence, size_t -> int, ptrdiff -> u32 warnings

  22. # pragma warning ( disable : 4290 4554 4267 )

  23. # endif

  24. # ifdef __MSC__

  25. #include

  26. #include

  27. # endif

  28. #include

  29. #include

  30. #include

  31. #include

  32. #include

  33. #include

  34. #include

  35. #include

  36. #include

  37. #include

  38. # if defined ( __INTEL_COMPILER )

  39. #include

  40. # elif defined ( _MSC_VER )

  41. #include

  42. # define round ( x ) double ( int ( ( x ) ) )

  43. # else

  44. #include

  45. # endif

  46. using namespace std;

  47. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  48. / / Basics

  49. typedef unsigned char       U8;  / / PROBLEM : char may have more than 8 bits

  50. typedef unsigned short      U16; / / PROBLEM : short may have more than 16 bits

  51. typedef unsigned long       U32; / / PROBLEM : long may have more than 32 bits

  52. typedef unsigned long long  U64; / / PROBLEM : long long may have more than 64 bits

  53. # define V64LEN 2 / / 32 – bit words

  54. # define V96LEN 3 / / 32 – bit words

  55. # define V128LEN 4 / / 32 – bit words

  56. # define V160LEN 5 / / 32 – bit words

  57. # define V256LEN 8 / / 32 – bit words

  58. # define V320LEN 10 / / 32 – bit words

  59. # define V1024LEN 32 / / 32 – bit words

  60. # define V2176LEN 68 / / 32 – bit words

  61. # define V4608LEN 144 / / 32 – bit words

  62. # define V3200LEN 100 / / 32 – bit words

  63. typedef U32                 V64  [V64LEN];

  64. typedef U32                 V96  [V96LEN];

  65. typedef U32                 V128 [V128LEN];

  66. typedef U32                 V160 [V160LEN];

  67. typedef U32                 V256 [V256LEN];

  68. typedef U32                 V320 [V320LEN];

  69. typedef U32                 V1024[V1024LEN];

  70. typedef U32                 V2176[V2176LEN];

  71. typedef U32                 V4608[V4608LEN];

  72. typedef U32                 V3200[V3200LEN];

  73. # define BASE 100

  74. inline U32 lo32  (U64 x)   { return U32(x và 0 xffffffff); }

  75. inline U32 hi32  (U64 x)   { return U32(x >> 32); }

  76. inline U64 mk64  (U32 L, U32 H)  { return (U64(H)< <32)|U64(L); }

  77. inline U32 byteswap ( U32 x )

  78.                  { U32 u = ((x và 0 xFF00FF00) >> 8) | (( x và 0x00 FF00FF) < < 8);

  79.                    return (u < < 16) | (u >> 16); }

  80. void byteswap( U32 y[], U32 const x[], int len );

  81.         / / reverse bytes of x and store result to y

  82.         / / e. g. if x = = 0x000102030405060708090 a0b, then byteswap ( y, x, 3 ) yields

  83.         / / y = = 0x0 b0a09080706050403020100

  84. / / gcc 3. x translates std :: _rotl ( ), std :: _rotr ( ) to library function calls

  85. / / instead of machine opcodes rol and ror => catastrophic performance .

  86. # ifdef __GNUC__

  87. # define _rotl ( x, r ) ( ( ( x ) < < ( r ) ) | ( ( x ) >> ( 32 – ( r ) ) ) )

  88. # define _rotr ( x, r ) ( ( ( x ) >> ( r ) ) | ( ( x ) < < ( 32 - ( r ) ) ) )

  89. # endif

  90. / / _rotl ( ), _rotl ( ) are only 32 bit, but we need 64 – bit version too

  91. inline U64  rotl64  (U64 x, int r) { return (x < < r)|(x >> (64-r)); }

  92. inline U64  rotr64  (U64 x, int r) { return (x >> r)|(x < < (64-r)); }

  93. inline double sqr   (double x) { return x*x; }

  94. # define LOG2 0.69314718055994530941723212145818 / / log ( 2 )

  95. # define ILOG2 1.4426950408889634073599246810019 / / 1 / log ( 2 )

  96. inline double log2  (double x) { return log(x)*ILOG2; } / / logarithm of x in base 2

  97. / / Conventional naming :

  98. / /

  99. / / X, Y Input, output block of the same size. For a block cipher, X is plain

  100. / / block, Y is cipherblock. For a block cipher-based hash function, X

  101. / / is the previous state of hash value, Y is the new state of hash value .

  102. / /

  103. / / Z Input block that is usually longer than of X, Y .

  104. / / For a block cipher it is primary key. For block cipher-based hash function

  105. / / it is the hashed data .

  106. / /

  107. / / S Input block, used by the keyed hash function uhash64 as the primary key .

  108. / / It changes every block hashed .

  109. / /

  110. / / T Expanded key, ie. array of subkeys. For uhash64 it is same type as Z .

  111. / /

  112. / / U Input ( plain ) stream of the b100 stream encryptor and authenticator .

  113. / /

  114. / / V Output ( cipher ) stream of the b100 stream encryptor .

  115. / /

  116. / / W 2 nd input ( key ) stream of the B100 stream encryptor and authenticator .

  117. void crypt128setup      (); / / constructs subsitution tables for

  118.                             / / the reference implementation and

  119.                             / / optimized implementation ( s ) of crypt128

  120. / / crypt128–reference implementation

  121. void crypt128encryptYXZ_ref   (V128và Y, V128 constvà X, V160 constvà Z);

  122.                               / / encrypt X to Y using key Z

  123. void crypt128decryptYXZ_ref   (V128và Y, V128 constvà X, V160 constvà Z);

  124.                               / / decrypt X to Y using key Z

  125. / / crypt128–optimized implementation

  126. void crypt128expandTZ   (V2176và T, V160 constvà Z);

  127.                         / / expands key Z into subkeys T

  128. void crypt128encryptYXT_opt   (V128và Y, V128 constvà X, V2176 constvà T);

  129.                         / / encrypt X to Y using expanded key T

  130. / / crypt160–reference implementation

  131. void crypt160expandTZ   (V4608và T, V256 constvà Z);

  132.                         / / expands key Z into subkeys T

  133. void crypt160encryptYXT_ref   (V160và Y, V160 constvà X, V4608 constvà T);

  134.                         / / encrypt X to Y using expanded key T

  135. / / crypt160–optimized implementations

  136. void crypt160encryptYXT_opt1  (V160và Y, V160 constvà X, V4608 constvà T);

  137.                         / / encrypt X to Y using expanded key T

  138. void crypt160encryptYXT_opt2  (V160và Y, V160 constvà X, V4608 constvà T);

  139.                         / / encrypt X to Y using expanded key T

  140. inline

  141. void crypt160encryptYXT (V160và Y, V160 constvà X, V4608 constvà T)

  142. {                        / / encrypts X to Y using subkeys T

  143.     crypt160encryptYXT_opt2 ( Y, X, T );

  144. }

  145. void uhash160expandTS   (V320 vàT, V160 constvà S);

  146.                         / / expands key S into subkeys T, * * updates * * T

  147. void uhash160hashYZT    (V160và Y, V256 constvà Z, V320 constvà T);

  148.                         / / hash Z to Y from previous hash Y using subkeys T ,

  149.                         / / * * updates * * Y

  150. void b100h64expandTZ    (V3200và T, V256 constvà Z);

  151.                         / / expands key Z into subkeys T

  152. void b100h64hashYXUWT   (V64và Y, V64 constvà X, U8 const U, U32 const W2, V3200 constvà T);

  153.                         / / hash U to Y from previous hash X using 2 consecutive

  154.                         / / chars ( W2 ) of a not necessarily secret random stream

  155.                         / / and a table of secret subkeys T [ ]

  156. inline U32 q32          (U32 x)   {return x*(2*x+1);}          / / used by crypt160

  157. inline U64 q64          (U64 x)   {return x*(2*x+1);}          / / used by crypt64

  158. inline U32 p32          (U32 x, U32 y) {return y*(2*x+1) + x;} / / used by b100h64

  159. inline U32 f32          (U32 x, U32 y) {return y*(2*x+0x80000001) + x;} / / unused ?

  160. inline U64 p64          (U64 x, U64 y) {return y*(2*x+1) + x;} / / unused ?

  161. U64    c128hash64       (V160 constvà Z, U64 salt);

  162.                         / / Using 160 – bit key Z, encrypts 64 – bit salt ( zero-padded to 128 – bit ) ,

  163.                         / / returns 64 – bit low half of the cipherblock .

  164. U64 muluh_shift         (U64 n, U64 m, int sh1,int sh2);

  165.                         / / Computes ( m * ( n >> sh1 ) ) >> ( sh2 + 64 ), a particular case

  166.                         / / of Granlund-Montgomery formula

  167.                         / / to perform unsigned division by multiplication

  168. class Hash160;          / / 160 – bit cryptographic hash function

  169. class B100prng;         / / Base100 keystream generator

  170. class B100mac;          / / Base100 stream MAC calculator

  171. class B100streamAuthEncryptor; / / Integrated base100 stream en – / de-cryptor

  172.                         / / and MAC calculator / verifier in an EtA mode ;

  173.                         / / Integrated plainstream substitutor, X en – / de-coder ,

  174.                         / / cipherstream en – / de-formatter and Y en – / de-coder

  175. class Keybase;          / / Manages keys, provides key-related services

  176. class Controller;       / / Controls user I / O

  177. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  178. / / Template instantiations

  179. # include ” teta-tmpl. h “

  180. template class UsgRng;

  181. typedef        UsgRng U8prng;

  182. template class UsgRng;

  183. typedef        UsgRng U16prng;

  184. template class UsgRng;

  185. typedef        UsgRng U32prng;

  186. template class UsgRng;

  187. typedef        UsgRng U64prng;

  188. template class UsgRng;

  189. typedef        UsgRng U32cipher;

  190. typedef        U32prng  U32trng;

  191. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  192. class B100prng : protected U32cipher

  193.                         / / a template Bxxprng < > would be more general, but much

  194.                         / / more complicated, with bitstream splitting etc .

  195. {

  196. public:

  197.     U8      randB100    (); / / Returns pseudo-random b100 char ( i. e. of 0 .. 99 )

  198.     U32     rand4B100   (); / / Returns 4 consecutive chars of the pseudo-random

  199.                             / / b100 stream in a 4 – byte sliding buffer ,

  200.                             / / in low-first order, i. e. if the stream is

  201.                             / / a1 a2 a3 a4 a5 … then :

  202.                             / / First call returns a1 xx xx xx ( xx = garbage )

  203.                             / / Second call returns a2 a1 xx xx

  204.                             / / Third call returns a3 a2 a1 xx

  205.                             / / Fourth call returns a4 a3 a2 a1

  206.                             / / Fifth call returns a5 a4 a3 a2

  207.                             / / k-th call returns a [ k ] a [ k-1 ] a [ k-2 ] a [ k-3 ]

  208.     / / Usage :

  209.     / / This class is used specifically by B100streamAuthEncryptor to

  210.     / / encrypt and to feed the B100mac algorithm with upto 4 keystreams

  211.     / / ( 128 – bit MAC ) .

  212.     / / Encrypt-only and 32 – bit MAC mode may use randB100 ( ) to save ~ 2 cc / char .

  213.     / / 64 -, 96 -, 128 – bit MAC modes must use rand4B100 ( ) .

  214.     / / Use either randB100 ( ) or rand4B100 ( ). If both are needed, create two

  215.     / / B100prng instances !

  216.     U8      operator()  () {return randB100();}

  217.     / / only one constructor is provided because this class is used only via

  218.     / / protected inheritance by B100streamAuthEncryptor, which does not have

  219.     / / enough infos at its construction time to call more meaningful base class

  220.     / / constructors .

  221.     B100prng();

  222.     void    seed        (V160 constvà z, U64 iv);

  223.     / / TODO : consider adding more constructors and variants of seed ( )

  224.     static

  225.     void    test        ();

  226. private:

  227.     static const int  NDIGITS   =3;       / / N ,

  228.     static const int  NBITS     =20;      / / K ,

  229.     static const U64  MAXMULT   =1000000; / / M, described in ‘ Algorithms ‘ .

  230.     U64     _bitbuf;     / / ( Secondary ) buffer of bits

  231.     int     _bitbuflen;  / / Number of bits remaining in it

  232.     U32     _digbuf;     / / ( Tertiary ) buffer of B-ary digits, 0 .. M-1

  233.     int     _digbuflen;  / / Number of digits remaining in it, 0 .. N

  234.     U32     _o4digbuf;   / / ( Quaternary ) sliding buffer of 4 consecutive output

  235.                          / / chars for rand4B100 ( )

  236. public: / / The following should be private. They are made public for testing only

  237.     U32     randU20     (); / / Splits the 160 – bit output of the underlying prng

  238.                          / / in 20 – bit nibbles and returns them, one by one ,

  239.                          / / in low-first order

  240. };

  241. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  242. class B100mac

  243. {

  244. public:

  245.     void    initialize  (V160 constvà z);/ / Initialize with primary key z

  246.     void    hashB100    (U8 u, U32 w2); / / Hash u using w2 ( 2 chars ) from a

  247.                                         / / keystream

  248.     void    finalize    (U64 nonce);    / / Computes final MAC and store it

  249.                                         / / to another internal variable that can

  250.                                         / / be read later by getMAC ( ). MACing may

  251.                                         / / continue even after finalize ( ) .

  252.     U64     getMac      () const;       / / Returns the MAC value

  253. protected:

  254.     / / only one constructor is provided because this class is used only via

  255.     / / protected inheritance by B100streamAuthEncryptor, which does not have

  256.     / / enough infos at its construction time to call more meaningful base class

  257.     / / constructors .

  258.     B100mac();

  259. private:

  260.     V3200   _tkey;      / / array of 100 subkeys derived from the key, used as

  261.                         / / the T parameter to b100h64hash ( ) .

  262.     V2176   _pdfxkey;   / / expanded key of the pad derivation function

  263.     V64     _hash;      / / Current hash value

  264.     V64     _mac;       / / Final MAC value

  265. };

  266. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  267. class B100streamAuthEncryptor: protected B100prng, protected B100mac

  268. {

  269.     / / Reemphasize : The keystream for this EtA class is seeded by a 32 – bit nonce ,

  270.     / / uses an internal 32 – bit counter. The cipherstream is MACed by a 32 – bit

  271.     / / nonce and produces 64 – bit MAC with forge probability of 2 * * – 50 ( regardless

  272.     / / of message length ). So this class may be used to encrypt + authenticate

  273.     / / upto 2 * * 32 messages, each upto 2 * * 32 chars long with the max forgeability

  274.     / / of 2 * * – 18 .

  275. public:

  276.     B100streamAuthEncryptor

    (

    Controller *c, Keybase *kb);

  277.     / / Plainstream * should * be open in binary mode because only binary mode

  278.     / / guarantee decrypt ( encrypt ( s ) ) = = s exactly regardless of environments

  279.     / / where decrypt ( ) and encrypt ( ) are executed. In text mode, the equality

  280.     / / is guaranteed only if encrypt ( ) and decrypt ( ) are executed in the same

  281.     / / environment .

  282.     / /

  283.     / / Cipherstream may be open in either mode .

  284.     void        encrypt     (istreamvà ps, ostreamvà cs);

  285.     void        decrypt     (istreamvà cs, ostreamvà ps);

  286.     static void test        ();

  287. private:

  288.     Controller  *_controller;   / / The assoc. controller. Call it if needed

  289.     Keybase     *_keybase;      / / The assoc. keybase. Call it if needed

  290. / *

  291. The substitution process shall be represented by a function P -> X, the process

  292. of deformatting the ‘ ciphertext ‘ of a ‘ ciphertext_file ‘ shall be presented by a

  293. function C -> Y :

  294. ( 1 ) Each Pchar / Cchar that is an Xchar / Ychar map to itself .

  295. ( 2 ) Each Pchar / Cchar that is not an Xchar / Ychar map to :

  296. ( 2 a ) a Xchar / Ychar substitute, i. e. Xchar / Ychar in 100 chars above ; or

  297. ( 2 b ) NUL, if it is to be deleted in the encoded Xchar / Ychar text

  298. before encoding to B100 .

  299. ( 3 ) Nothing of plaintext may be ignored ( deleted ), everything, even NUL ,

  300. must survive in the encoded Xchar text as itself or as a Xchar substitute .

  301. Notes

  302. – Xchar contains DEL so a char map to DEL if it does not have a meaningful

  303. substitute, by spec and by rule ( 3 ) .

  304. – DEL map to itself in P -> X by rule ( 1 ), and map to NUL in C -> Y by rule ( 2 b ) .

  305. – NUL map to DEL in P -> X by rule ( 3 ), and map to itself in C -> Y by rule ( 2 b ) .

  306. – Any other char of the ciphertext, including any format_effector and

  307. logcomctrl_char which were inserted by the formatter, shall be deleted by the

  308. deformatter before encoding to Ychar. ( This is not a rule, just a consequence

  309. of the fundamental requirement that ciphertext must be decryptable. ) Therefore ,

  310. every such char map to NUL in C -> Y .

  311. – The range of the function P -> X contains exactly 100 chars ; the range of

  312. the function C -> Y contains exactly 100 Ychars + NUL = = 101 chars .

  313. – The function P -> X will be used to implement ( as a single array ) an

  314. automated

  315. . P -> B100, i. e. substitutor + Xencoder ,

  316. . B100 -> P, i. e. Xdecoder .

  317. – The deformatter’s function will be used to implement ( as a single array )

  318. an automated

  319. . C -> B100, i. e. deformatter’s ciphertext-processing part + Yencoder

  320. . B100 -> C, i. e. Ydecoder + formatter’s ciphertext-generating part .

  321. * /

  322.     static void     constructCode   (U8(*PCtoXY)(U8),U8 PCtoB100[256], U8 B100toPC[BASE+1]);

  323.     static U8       ansiToX         (U8 c); / / substitutor’s map P -> X

  324.     static U8       ansiToY         (U8 c); / / deformatter’s map C -> Y

  325.     U8              encryptChar     (U8 x); / / return encrypted char or NUL

  326.     U8              decryptChar     (U8 y); / / return decrypted char or NUL

  327. / / the following should be private. They are public only for testing

  328. public:

  329.     void            encryptString   (char *cs, char const* ps, int len);

  330.     void            decryptString   (stringvà p, string constvà c);

  331.     using           B100prng::seed;

  332. };

  333. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  334. class Hash160

  335. {

  336. public:

  337.     Hash160();

  338.     void        initialize  (U64 salt);

  339.                     / / The salt is used primarily as the key for uhash160 .

  340.     void        hashBlock   (V256 constvà Z, int len=sizeof(V256));

  341.                     / / hash block Z into internal variable

  342.                     / / although there is parameter ‘ len ‘, Z must be a

  343.                     / / zero-padded 256 – bit data block even if len <3 2 .

  344.     void        finalize    ();

  345.                     / / computes final hash value and store it to another

  346.                     / / internal variable, which can be read by getHash ( ) .

  347.                     / / Hashing may continue even after finalize ( ) .

  348.     V160 constvà getHash     () const;

  349.                     / / returns the final hash value

  350.     V160 constvà operator()(void const *z, int len, U64 salt = 0);

  351.                     / / hash byte string z of ‘ len ‘ bytes using ‘ salt ‘ and return

  352.                     / / the hash value. Example of use :

  353.                     / / char s [ 1000 ] ;

  354.                     / / …

  355.                     / / Hash64 hash ;

  356.                     / / V160 h = hash ( s, sizeof ( s ), time ( NULL ) ) ;

  357. protected:

  358.     V160        _chash;   / / current hash val of the underlying crypt160

  359.     V160        _uhash;   / / current hash val of the accompanying uhash160

  360.     V160        _hash;    / / final ( combined ) hash value

  361.     size_t      _datalen; / / number of bytes hashed so far

  362.     V4608       _crypt160xkey; / / expanded key of the underlying crypt160 …

  363.     V320        _uhash160xkey; / / … and the accompanying uhash160

  364. };

  365. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  366. struct Keyinfo

  367. {

  368.     V160            key;

  369.     U64             keyid;  / / The hash value of the key

  370.     U64             salt;   / / The salt that was used to hash the key

  371.     U64             nUsed;  / / Number of times the key is used to encrypt / create

  372.                             / / MAC. This number is used as the nonce for the next

  373.                             / / message authenticated under the key, or as the seed

  374.                             / / for the next message encrypted under the key

  375.     bool            isActive; / / Keys are never deleted and may be always used

  376.                             / / to decrypt / verify mac. Furthermore, when a key is

  377.                             / / _active_ it can be used to encrypt / create mac .

  378. };

  379. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  380. class Keybase

  381. {

  382. public:

  383.     explicit

  384.     Keybase         (string constvà keyfilename); / / Load keybase from file

  385.     ~Keybase        ();     / / Save this keybase to the original file

  386.     Keyinfo const * selectKey  (U64 constvà keyid) const;

  387.                     / / Select certain key to decrypt / verify MAC .

  388.                     / / Return NULL if such key not found in this keybase

  389.     Keyinfo obtainKey  ();

  390.                     / / Obtain a suitable key to encrypt / create MAC .

  391.                     / / If this keybase finds no suitable key, it generates one .

  392.                     / / If it finds out a key, it increment the seed and the nonce

  393.                     / / before returning the key info .

  394.     static void     test();

  395. private:

  396.     vector _keyinfos;

  397.     map    _keyidx;

  398.     string          _keyfilename;

  399.     Keyinfo constvà  genKey      ();  / / generate a key and add it to _keyinfos

  400.                                 / / returns reference to the just-added key

  401.     void            loadKeys    (string constvà keyfilename);

  402.     void            saveKeys    (string constvà keyfilename);

  403. };

  404. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  405. class Controller

  406. {

  407. public:

  408.     Controller();

  409.     ~Controller ();

  410. };

  411. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  412. / / Statistical và DSP stuffs

  413. struct Statistic

  414. {

  415.     Statistic(vector constvà data);

  416.     string image(void);

  417.     int         _n;

  418.     double      _mu;

  419.     double      _sigma;

  420.     double      _max, _min;

  421. };

  422. double quartile     (double p, vector constvà sorted_data);

  423.                         / / Determines p-quartile ( octile, decile, … ) of the

  424.                         / / sorted_data, where sorted_data is viewed as a

  425.                         / / multiset of floats ; it must be already sorted .

  426. / / Example : quartile ( 0.25, v ), is a float q dividing v into 3 partitions

  427. / / v0, v01, v1 concisting of floats smaller than q, equaling to q and

  428. / / larger than q respectively, such that | v0 | < = 0.25 | v | and | v1 | < = 0.75 | v | .

  429. / / If v01 = = empty, then every number in ( max v0, min v1 ) can be the q .

  430. void    haardwt     (int y[], int const x[], int len);

  431.     / / Haar discrete wavelet transform of signal x [ ] to spectrum y [ ] ,

  432.     / / len must be 2 * * n

  433. double  entropy     ( map và f );

  434.     / / ( Shannon ) entropy [ bits ] of * * each * * symbol given its frequency

  435.     / / distribution, f [ ]

  436. double  entropy     ( int const s[], int len );

  437.     / / entropy [ bits ] of the array ‘ s ‘ of length ‘ len ‘

  438. double  entropy     ( U8 ss[], int len );

  439.     / / entropy [ bits ] of the signal sample ‘ ss ‘ of length ‘ len ‘ ,

  440.     / / consisting of 2 nd differential of the usclock ( ) values ,

  441.     / / i. e. jitters of latency of usclock ( ) .

  442. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  443. / / Microsecond clock

  444. / /

  445. / / Implemented by high-resolution performance counter ( HRPC )

  446. / / which is available on Win32 only

  447. #include

  448. / / ——————————————————————————

  449. extern double HRPC_FRQ;         / / [ Hz ] HRPC frequency

  450. extern double HRPC_PRD;         / / [ s ] HRPC period, ie. span of 1 tick

  451. extern double MACH_FRQ;         / / [ Hz ] Machine ( CPU ) frequency

  452. extern double MACH_PRD;         / / [ s ] Machine ( CPU ) period, ie. span of 1 cc

  453. extern double CC_PER_TICK;      / / [ cc / ct ] # CPU cc per HRPC tick

  454. extern double UCLK_LATENCY;     / / [ s ] ( mean of ) uclock latency

  455. LONGLONG    usclock ();         / / [ ct ] current value of the HRPC counter

  456. void        hrpcInit();         / / initialization, call it once at the begining

  457. void        rampup  ( float t );/ / Ramping up for about t seconds .

  458.     / / There’re many reasons to do so, including :

  459.     / / – initial page faults ,

  460.     / / – initial cache misses ,

  461.     / / – initial CPU’s frequency which may not be the full MACH_FRQ .

  462. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  463. / / Global variables

  464. extern U32trng      g_u32trng;

  465. extern U8prng       g_u8prng;

  466. extern U16prng      g_u16prng;

  467. extern U32prng      g_u32prng;

  468. extern U64prng      g_u64prng;

  469. extern Crypt128prng g_crypt128prng;

  470. extern Crypt160prng g_crypt160prng;

  471. extern U8 const     P_AESsbox    [256];

  472. extern U8 const     P_affineSqrt2[256];

  473. extern U8 const     P_affineSqrt3[256];

  474. / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

  475. / / Inlines

  476. / / ——————————————————————————

  477. inline U32 B100prng::randU20() / / Inline saves only 1-2 cc / char and even makes it slower

  478.                         / / in some previous versions. Be careful !

  479. {

  480.     / / Performance : brutto 70 cc / char

  481.     / / ( each U20 is equivalent to 3 chars )

  482.     if(_bitbuflen < NBITS)

  483.         / / if _bitbuf is U64, it can load 32 bits once so if ( … ) will suffice .

  484.         / / But if _bitbuf was U32 then it could load 8 bits once and there would

  485.         / / be while ( … ) .

  486.     {

  487.         / / dequeue a U32 from the low end of the primary buffer and enqueue the

  488.         / / 32 bits to the high end of _bitbuf

  489.         _bitbuf |= U64(U32cipher::rand()) < < _bitbuflen;

  490.         _bitbuflen += 32;

  491.     }

  492.     / / dequeue 20 bits from the low end of _bitbuf

  493.     _bitbuflen -= NBITS;

  494.     U32 r = U32( _bitbuf ) và ((1<

  495.     _bitbuf >> = NBITS;

  496.     return r;

  497. }

  498. / / ——————————————————————————

  499. inline

  500. U8 B100prng::randB100()

  501. {

  502.     / / Performance :

  503.     / /

  504.     / / – The result is extremely sensitive to benchmark parameters ,

  505.     / / i. e. number of repetitions etc. Use consistent parameters or the results

  506.     / / won’t be comparable !

  507.     / /

  508.     / / – All benchmarks are made with crypt128encryptYXT_opt ( ) .

  509.     / /

  510.     / / – The unit is [ cc / char ]. Throughput of crypt128 must be converted from

  511.     / / cc / byte to cc / char ; e. g. 73.5 cc / byte is equivalent to

  512.     / / 73.5 * ( 20/8 ) * 2 * * 20 / ( 3 * 1E6 ) = 73.5 * 0.874 = 64 cc / char

  513.     / /

  514.     / / Item ICC MSVC GCC

  515.     / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

  516.     / / 1. Unoptimized : 1 div + 1 mod

  517.     / / brutto : —- —- —-

  518.     / / 2. Optimized : 2 mul

  519.     / / brutto : 86 —- 106

  520.     / / crypt128, converted 64 80

  521.     / / netto : 22 —- 26

  522.     / /

  523.     / / => For 32 – bit arithmetic MSVC, GCC may have already optimized code .

  524.     / / The trick of replacing div-mod with multiplication is effective with 64 – bit

  525.     / / arithmetics only

  526.     if(!_digbuflen)

  527.     {

  528.         while((_digbuf = randU20()) > = MAXMULT);

  529.         _digbuflen = NDIGITS;

  530.     }

  531.     / / U32 d = _digbuf / BASE ; / / unoptimized

  532.     U32 d = hi32(U64(_digbuf)*0x51 EB851F) >> 5; / / optimized

  533.     / / The following line is to divide by 100 using 64 – bit arithmetic .

  534.     / / Do NOT delete ! Reserved for future use :

  535.     / / U64 d = muluh_shift ( _buffer, 2951479051793528259ULL, 2,2 ) ; / / optimized

  536.     / / U32 c = _digbuf % BASE ; / / unoptimized

  537.     U32 c = _digbuf – d*BASE; / / half-optimized

  538.     _digbuf = d;

  539.     _digbuflen–;

  540.     return U8(c);

  541. }

  542. / / ——————————————————————————

  543. inline

  544. U32 B100prng::rand4B100()

  545. {

  546.     / / Performance = = randB100 ( ) + 2 cc / char

  547.     if(!_digbuflen)

  548.     {

  549.         while((_digbuf = randU20()) > = MAXMULT);

  550.         _digbuflen = NDIGITS;

  551.     }

  552.     / / U32 d = _digbuf / BASE ; / / unoptimized

  553.     U32 d = hi32(U64(_digbuf)*0x51 EB851F) >> 5; / / optimized

  554.     / / U32 c = _digbuf % BASE ; / / unoptimized

  555.     U32 c = _digbuf – d*BASE; / / half-optimized

  556.     _digbuf = d;

  557.     _digbuflen–;

  558.     _o4digbuf = (_o4digbuf >> 8) | (c < < 24);

  559.     return _o4digbuf;

  560. }

  561. / / ——————————————————————————

  562. inline

  563. void b100h64hashYXUWT (V64và Y, V64 constvà X, U8 const U, U32 const W2,

  564.                               V3200 constvà T)

  565.                         / / hash U to Y from previous hash X using 2 bytes W2

  566.                         / / from a random stream and a table of subkeys T [ ]

  567. {

  568.     Y[0] = p32(X[0] + U32(U),T[ W2     và0 xFF]);

  569.     Y[1] = p32(X[1] + U32(U),T[(W2>> 8)và0 xFF]);

  570. }

  571. / / ——————————————————————————

  572. inline

  573. void B100mac::hashB100    ( U8 u, U32 w2 )

  574. {

  575.     b100h64hashYXUWT ( _hash, _hash, u, w2, _tkey

    )

    ;

  576. }

Mã hóa văn bản

Bài viết liên quan
Hotline 24/7: O984.666.352
Alternate Text Gọi ngay