00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include "stdafx.h"
00021
00022 #include "gul_types.h"
00023 #include "guma_random.h"
00024
00025 #include <sys/types.h>
00026 #include <sys/stat.h>
00027 #include <fcntl.h>
00028 #ifdef _MSC_VER
00029 #include <io.h>
00030 #else
00031 #include <unistd.h>
00032 #endif
00033 #include <time.h>
00034
00035 #include <iostream>
00036
00037
00038 #if defined(__MINGW32__) || defined(_MSC_VER)
00039
00040
00041
00042
00043
00044
00045 static long random_lastx;
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056 GULAPI long random()
00057 {
00058 long hi, lo, x;
00059
00060 x = random_lastx;
00061 hi = x / 127773;
00062 lo = x % 127773;
00063 x = 16807 * lo - 2836 * hi;
00064 if (x <= 0)
00065 x += 0x7fffffff;
00066 random_lastx = x = (x & 0x7fffffff);
00067 return x;
00068 }
00069
00070 GULAPI void srandom( long x )
00071 {
00072 random_lastx = x;
00073 }
00074
00075 #endif
00076
00077
00078 namespace guma {
00079
00080 using gul::uint32;
00081 using std::cout;
00082
00083 GULAPI bool random_des::initialized = false;
00084 GULAPI uint32 random_des::sequence = 1;
00085 GULAPI uint32 random_des::cycle = 1;
00086
00087
00088
00089
00090
00091 GULAPI uint32 GetSeed()
00092 {
00093 uint32 seed;
00094 int fd,n;
00095
00096 fd = open( "/dev/random", O_RDONLY );
00097 if( fd < 0 )
00098 {
00099 cout << "GetSeed: Couldn't open \"/dev/random\"\n";
00100 return (uint32)time(0);
00101 }
00102 n = read( fd, &seed, sizeof(seed) );
00103 if( n != sizeof(seed) )
00104 {
00105 close(fd);
00106
00107 cout << "GetSeed: Couldn't read " << sizeof(seed) << "bytes\n";
00108 return (uint32)time(0);
00109 }
00110
00111 close(fd);
00112 return seed;
00113 }
00114
00115
00116
00117
00118
00119 GULAPI void PseudoDes( uint32 *lword, uint32 *irword )
00120 {
00121 static uint32 c1[4] = {
00122 0xbaa96887L, 0x1e17d32cL, 0x03bcdc3cL, 0x0f33d1b2L };
00123 static uint32 c2[4] = {
00124 0x4b0f3b58L, 0xe874f0c3L, 0x6955c5a6L, 0x55a7ca46L };
00125
00126 uint32 i,ia,ib,iswap,itmph=0,itmpl=0;
00127
00128 for( i = 0; i < 4; i++ )
00129 {
00130 ia = (iswap=(*irword)) ^ c1[i];
00131 itmpl = ia & 0xffff;
00132 itmph = ia >> 16;
00133 ib = itmpl*itmpl + ~(itmph*itmph);
00134 ia = (ib>>16) | ((ib&0xffff)<<16);
00135 *irword = (*lword) ^ ((ia ^ c2[i]) + itmpl*itmph);
00136 *lword = iswap;
00137 }
00138 }
00139
00140 }
00141