From 4bacf39790df9ff21479858ce92b361a28fc9b4b Mon Sep 17 00:00:00 2001 From: Zhi Guan Date: Thu, 22 Dec 2022 21:32:06 +0800 Subject: [PATCH] Fix rand_bytes in Android --- CMakeLists.txt | 2 ++ src/rand.c | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/rand.c diff --git a/CMakeLists.txt b/CMakeLists.txt index aae0633a..fe42143a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -113,6 +113,8 @@ if (WIN32) list(APPEND src src/rand_win.c) elseif (APPLE) list(APPEND src src/rand_apple.c) +elseif (ANDROID) + list(APPEND src src/rand.c) else() list(APPEND src src/rand_unix.c) endif() diff --git a/src/rand.c b/src/rand.c new file mode 100644 index 00000000..e155aef5 --- /dev/null +++ b/src/rand.c @@ -0,0 +1,45 @@ +/* + * Copyright 2014-2022 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ + + +#include +#include +#include +#include +#include + +#define RAND_MAX_BUF_SIZE 4096 + +int rand_bytes(uint8_t *buf, size_t len) +{ + FILE *fp; + if (!buf) { + error_print(); + return -1; + } + if (len > RAND_MAX_BUF_SIZE) { + error_print(); + return -1; + } + if (!len) { + return 0; + } + + if (!(fp = fopen("/dev/urandom", "rb"))) { + error_print(); + return -1; + } + if (fread(buf, 1, len, fp) != len) { + error_print(); + fclose(fp); + return -1; + } + fclose(fp); + return 1; +}