1 /***************************************************************************
2 * Copyright (C) 2005 by Tarek Saidi *
3 * mail@tarek-saidi.de *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; version 2 of the License. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
24 #if defined(Q_WS_X11) || defined(Q_WS_MAC)
26 #elif defined(Q_WS_WIN)
32 #include <QCryptographicHash>
34 #include <QDataStream>
38 bool getNativeEntropy(quint8* buffer, int length);
40 void getEntropy(quint8* buffer, int length){
41 if (!getNativeEntropy(buffer, length)) {
42 qWarning("Entropy collection failed, using fallback");
44 for(int i=0;i<length;i++){
45 ((quint8*)buffer)[i] = (quint8) (qrand()%256);
50 quint32 randint(quint32 limit){
53 return (rand % limit);
56 quint32 randintRange(quint32 min, quint32 max){
57 return min + randint(max-min+1);
60 #if defined(Q_WS_X11) || defined(Q_WS_MAC)
62 extern bool getNativeEntropy(quint8* buffer, int length) {
63 QFile dev_urandom("/dev/urandom");
64 if (!dev_urandom.open(QIODevice::ReadOnly|QIODevice::Unbuffered))
66 return (dev_urandom.read((char*)buffer,length) == length);
69 #elif defined(Q_WS_WIN)
71 extern bool getNativeEntropy(quint8* buffer, int length) {
73 if (!CryptAcquireContext(&handle, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
76 CryptGenRandom(handle, length, buffer);
77 CryptReleaseContext(handle, 0);
84 extern void initStdRand(){
85 static bool initalized = false;
90 QDataStream stream(&buffer, QIODevice::WriteOnly);
92 stream << QCursor::pos();
93 stream << QDateTime::currentDateTime().toTime_t();
94 stream << QTime::currentTime().msec();
96 stream << (quint32) GetCurrentProcessId();
100 /* On a modern OS code, stack and heap base are randomized */
101 quint64 code_value = (quint64)initStdRand;
102 stream << code_value;
103 stream << (quint64)&code_value;
105 QByteArray hash = QCryptographicHash::hash(buffer, QCryptographicHash::Sha1);
107 qsrand( *((uint*) hash.data()) );