Skip to content

Commit 9531b24

Browse files
author
kmeow
committed
Move system dependency on /dev/urandom out of totp.c
1 parent dbe0754 commit 9531b24

File tree

3 files changed

+20
-14
lines changed

3 files changed

+20
-14
lines changed

totp.c

+2-11
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ static time_t flip_ts_endianness(time_t timestamp)
101101
return output;
102102
}
103103

104-
int generate_random_secret(char* out, size_t outlen)
104+
int generate_random_secret(char* out, size_t outlen, int32_t (*rgen)(uint8_t*, size_t))
105105
{
106106
//Generate a 160-bit random value encoded in a 32 character long base32
107107
//encoded ASCII string
@@ -112,16 +112,7 @@ int generate_random_secret(char* out, size_t outlen)
112112

113113
uint8_t secret[20] = {0};
114114

115-
FILE* fpurandom = fopen("/dev/urandom", "r");
116-
if(!fpurandom)
117-
{
118-
return -1;
119-
}
120-
121-
int bread = fread(secret, 1, 20, fpurandom);
122-
fclose(fpurandom);
123-
124-
if(bread < 20)
115+
if(rgen(secret, 20) < 0)
125116
{
126117
return -1;
127118
}

totp.h

+3-2
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,13 @@ int32_t compute_totp(const char* secret, size_t secretlen,
6060
* timestep - how many seconds OTP should remain valid; almost always 30
6161
* digits - how many digits (1 - 8) should be in the OTP. 6 is common
6262
*/
63-
64-
int generate_random_secret(char* out, size_t outlen);
63+
int generate_random_secret(char* out, size_t outlen, int32_t (*rgen)(uint8_t*, size_t));
6564
/* generate_random_secret: generates a random secret encoded in base32.
6665
*
6766
* out - pointer to output buffer
6867
* outlen - size of buffer in bytes. Must be at least 33 bytes long.
68+
* rgen - a function that fills the buffer pointed to by the first argument, of length equal to the 2nd argument, with random bytes
69+
* and which returns -1 on failure and anything else on success
6970
*/
7071

7172
void hmacsha1(char* output, const char* key,

totp_demo.c

+15-1
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,25 @@
2525
#include "totp.h"
2626
#include "base32codec.h"
2727

28+
int32_t FillFromURANDOM(uint8_t* out, size_t outlen)
29+
{
30+
FILE* fpurandom = fopen("/dev/urandom", "r");
31+
if(!fpurandom)
32+
{
33+
return -1;
34+
}
35+
36+
int32_t bread = fread(out, 1, outlen, fpurandom);
37+
fclose(fpurandom);
38+
39+
return bread < outlen ? -1 : bread;
40+
}
41+
2842
void demo_ansi_qrcode()
2943
{
3044
char secret[33] = {0};
3145
//Create a base32 encoded secret in an ascii string
32-
generate_random_secret(secret, 33);
46+
generate_random_secret(secret, 33, FillFromURANDOM);
3347
printf("Secret: %s\n", secret);
3448

3549
//Create an ANSI QR code graphic. qrcodeansi owns the new heap memory.

0 commit comments

Comments
 (0)