~zooko/cryptopp/trunk

« back to all changes in this revision

Viewing changes to osrng.cpp

  • Committer: weidai
  • Date: 2007-05-04 15:04:58 UTC
  • Revision ID: svn-v4:57ff6487-cd31-0410-9ec3-f628ee90f5f0:trunk/c5:328
reduce risk of random number reuse after VM rollback

Show diffs side-by-side

added added

removed removed

Lines of Context:
74
74
#endif
75
75
}
76
76
 
77
 
byte NonblockingRng::GenerateByte()
78
 
{
79
 
        byte b;
80
 
        GenerateBlock(&b, 1);
81
 
        return b;
82
 
}
83
 
 
84
77
void NonblockingRng::GenerateBlock(byte *output, size_t size)
85
78
{
86
79
#ifdef CRYPTOPP_WIN32_AVAILABLE
87
80
#       ifdef WORKAROUND_MS_BUG_Q258000
88
 
                static MicrosoftCryptoProvider m_Provider;
 
81
                const MicrosoftCryptoProvider &m_Provider = Singleton<MicrosoftCryptoProvider>().Ref();
89
82
#       endif
90
83
        if (!CryptGenRandom(m_Provider.GetProviderHandle(), (DWORD)size, output))
91
84
                throw OS_RNG_Err("CryptGenRandom");
101
94
 
102
95
#ifdef BLOCKING_RNG_AVAILABLE
103
96
 
 
97
#ifndef CRYPTOPP_BLOCKING_RNG_FILENAME
 
98
#ifdef __OpenBSD__
 
99
#define CRYPTOPP_BLOCKING_RNG_FILENAME "/dev/srandom"
 
100
#else
 
101
#define CRYPTOPP_BLOCKING_RNG_FILENAME "/dev/random"
 
102
#endif
 
103
#endif
 
104
 
104
105
BlockingRng::BlockingRng()
105
106
{
106
 
        m_fd = open("/dev/random",O_RDONLY);
 
107
        m_fd = open(CRYPTOPP_BLOCKING_RNG_FILENAME,O_RDONLY);
107
108
        if (m_fd == -1)
108
 
                throw OS_RNG_Err("open /dev/random");
 
109
                throw OS_RNG_Err("open " CRYPTOPP_BLOCKING_RNG_FILENAME);
109
110
}
110
111
 
111
112
BlockingRng::~BlockingRng()
113
114
        close(m_fd);
114
115
}
115
116
 
116
 
byte BlockingRng::GenerateByte()
117
 
{
118
 
        byte b;
119
 
        GenerateBlock(&b, 1);
120
 
        return b;
121
 
}
122
 
 
123
117
void BlockingRng::GenerateBlock(byte *output, size_t size)
124
118
{
125
119
        while (size)
128
122
                // are available, on others it will returns immediately
129
123
                ssize_t len = read(m_fd, output, size);
130
124
                if (len < 0)
131
 
                        throw OS_RNG_Err("read /dev/random");
 
125
                        throw OS_RNG_Err("read " CRYPTOPP_BLOCKING_RNG_FILENAME);
132
126
                size -= len;
133
127
                output += len;
134
128
                if (size)
167
161
{
168
162
        SecByteBlock seed(seedSize);
169
163
        OS_GenerateRandomBlock(blocking, seed, seedSize);
170
 
        Put(seed, seedSize);
 
164
        IncorporateEntropy(seed, seedSize);
171
165
}
172
166
 
173
167
NAMESPACE_END