micro-ECC for mbed, ported from GCC version from Github,

Dependents:   mbed_microECC Wallet_v1

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers platform-specific.h Source File

platform-specific.h

00001 /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
00002 
00003 #ifndef _UECC_PLATFORM_SPECIFIC_H_
00004 #define _UECC_PLATFORM_SPECIFIC_H_
00005 
00006 #include "types.h"
00007 
00008 #if (defined(_WIN32) || defined(_WIN64))
00009 /* Windows */
00010 
00011 // use pragma syntax to prevent tweaking the linker script for getting CryptXYZ function
00012 #pragma comment(lib, "crypt32.lib")
00013 #pragma comment(lib, "advapi32.lib")
00014 
00015 #define WIN32_LEAN_AND_MEAN
00016 #include <windows.h>
00017 #include <wincrypt.h>
00018 
00019 static int default_RNG(uint8_t *dest, unsigned size) {
00020     HCRYPTPROV prov;
00021     if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
00022         return 0;
00023     }
00024 
00025     CryptGenRandom(prov, size, (BYTE *)dest);
00026     CryptReleaseContext(prov, 0);
00027     return 1;
00028 }
00029 #define default_RNG_defined 1
00030 
00031 #elif defined(unix) || defined(__linux__) || defined(__unix__) || defined(__unix) || \
00032     (defined(__APPLE__) && defined(__MACH__)) || defined(uECC_POSIX)
00033 
00034 /* Some POSIX-like system with /dev/urandom or /dev/random. */
00035 #include <sys/types.h>
00036 #include <fcntl.h>
00037 #include <unistd.h>
00038 
00039 #ifndef O_CLOEXEC
00040     #define O_CLOEXEC 0
00041 #endif
00042 
00043 static int default_RNG(uint8_t *dest, unsigned size) {
00044     int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
00045     if (fd == -1) {
00046         fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
00047         if (fd == -1) {
00048             return 0;
00049         }
00050     }
00051     
00052     char *ptr = (char *)dest;
00053     size_t left = size;
00054     while (left > 0) {
00055         ssize_t bytes_read = read(fd, ptr, left);
00056         if (bytes_read <= 0) { // read failed
00057             close(fd);
00058             return 0;
00059         }
00060         left -= bytes_read;
00061         ptr += bytes_read;
00062     }
00063     
00064     close(fd);
00065     return 1;
00066 }
00067 #define default_RNG_defined 1
00068 
00069 #endif /* platform */
00070 
00071 #endif /* _UECC_PLATFORM_SPECIFIC_H_ */