Line data Source code
1 : /* 2 : Mosh: the mobile shell 3 : Copyright 2012 Keith Winstein 4 : 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, either version 3 of the License, or 8 : (at your option) any later version. 9 : 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. 14 : 15 : You should have received a copy of the GNU General Public License 16 : along with this program. If not, see <http://www.gnu.org/licenses/>. 17 : 18 : In addition, as a special exception, the copyright holders give 19 : permission to link the code of portions of this program with the 20 : OpenSSL library under certain conditions as described in each 21 : individual source file, and distribute linked combinations including 22 : the two. 23 : 24 : You must obey the GNU General Public License in all respects for all 25 : of the code used other than OpenSSL. If you modify file(s) with this 26 : exception, you may extend this exception to your version of the 27 : file(s), but you are not obligated to do so. If you do not wish to do 28 : so, delete this exception statement from your version. If you delete 29 : this exception statement from all source files in the program, then 30 : also delete it here. 31 : */ 32 : 33 : #ifndef PRNG_HPP 34 : #define PRNG_HPP 35 : 36 : #include <string> 37 : #include <stdint.h> 38 : #include <fstream> 39 : 40 : #include "crypto.h" 41 : 42 : /* Read random bytes from /dev/urandom. 43 : 44 : We rely on stdio buffering for efficiency. */ 45 : 46 : static const char rdev[] = "/dev/urandom"; 47 : 48 : using namespace Crypto; 49 : 50 624 : class PRNG { 51 : private: 52 : std::ifstream randfile; 53 : 54 : /* unimplemented to satisfy -Weffc++ */ 55 : PRNG( const PRNG & ); 56 : PRNG & operator=( const PRNG & ); 57 : 58 : public: 59 1524 : PRNG() : randfile( rdev, std::ifstream::in | std::ifstream::binary ) {} 60 : 61 381256 : void fill( void *dest, size_t size ) { 62 381256 : if ( 0 == size ) { 63 : return; 64 : } 65 : 66 380895 : randfile.read( static_cast<char *>( dest ), size ); 67 380895 : if ( !randfile ) { 68 0 : throw CryptoException( "Could not read from " + std::string( rdev ) ); 69 : } 70 : } 71 : 72 40785 : uint8_t uint8() { 73 40785 : uint8_t x; 74 40785 : fill( &x, 1 ); 75 40785 : return x; 76 : } 77 : 78 37489 : uint32_t uint32() { 79 37489 : uint32_t x; 80 37489 : fill( &x, 4 ); 81 37489 : return x; 82 : } 83 : 84 128 : uint64_t uint64() { 85 128 : uint64_t x; 86 128 : fill( &x, 8 ); 87 128 : return x; 88 : } 89 : }; 90 : 91 : #endif