1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 #if defined(__ANDROID__) || defined(__linux__)
31 uint8_t GetRandomBitRaw() {
32 return analogRead((uint8_t)ANALOG_IN) & 0x1;
35 uint8_t GetRandomBitRaw2() {
38 a = GetRandomBitRaw() | (GetRandomBitRaw()<<1);
40 return 0; // 1 to 0 transition: log a zero bit
43 return 1;// 0 to 1 transition: log a one bit
45 // For other cases, try again.
49 uint8_t GetRandomBit() {
52 a = GetRandomBitRaw2() | (GetRandomBitRaw2()<<1);
54 return 0; // 1 to 0 transition: log a zero bit
57 return 1;// 0 to 1 transition: log a one bit
59 // For other cases, try again.
64 int8_t OCSeedRandom() {
65 #if defined(__ANDROID__) || defined(__linux__)
66 int32_t fd = open("/dev/urandom", O_RDONLY);
69 uint32_t totalRead = 0; //how many integers were read
70 int32_t currentRead = 0;
71 while (totalRead < sizeof(randomSeed)) {
72 currentRead = read(fd, (uint8_t*) &randomSeed + totalRead,
73 sizeof(randomSeed) - totalRead);
75 totalRead += currentRead;
88 result += result + GetRandomBit();
96 void OCFillRandomMem(uint8_t * location, uint16_t len) {
101 *location++ = OCGetRandomByte();
105 uint32_t OCGetRandom() {
107 OCFillRandomMem((uint8_t*) &result, 4);
111 uint8_t OCGetRandomByte(void) {
112 #if defined(__ANDROID__) || defined(__linux__)
113 return rand() & 0x00FF;
114 #elif defined ARDUINO
115 return random(256) & 0x00FF;
119 uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound){
123 if(firstBound > secondBound){
125 diff = firstBound - secondBound;
126 }else if(firstBound < secondBound){
128 diff = secondBound - firstBound;
132 result = ((float)OCGetRandom()/((float)(0xFFFFFFFF))*(float)diff) + (float) base;