|
| 1 | +/** |
| 2 | + * Copyright (c) 2018 rxi |
| 3 | + * |
| 4 | + * This library is free software; you can redistribute it and/or modify it |
| 5 | + * under the terms of the MIT license. See LICENSE for details. |
| 6 | + */ |
| 7 | + |
| 8 | +#include <stdio.h> |
| 9 | +#include <stdint.h> |
| 10 | + |
| 11 | +#if defined(_WIN32) |
| 12 | +#include <windows.h> |
| 13 | +#include <wincrypt.h> |
| 14 | +#endif |
| 15 | + |
| 16 | +#include "uuid4.h" |
| 17 | + |
| 18 | + |
| 19 | +static uint64_t seed[2]; |
| 20 | + |
| 21 | + |
| 22 | +static uint64_t xorshift128plus(uint64_t *s) { |
| 23 | + /* http://xorshift.di.unimi.it/xorshift128plus.c */ |
| 24 | + uint64_t s1 = s[0]; |
| 25 | + const uint64_t s0 = s[1]; |
| 26 | + s[0] = s0; |
| 27 | + s1 ^= s1 << 23; |
| 28 | + s[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); |
| 29 | + return s[1] + s0; |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +int uuid4_init(void) { |
| 34 | +#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) |
| 35 | + int res; |
| 36 | + FILE *fp = fopen("/dev/urandom", "rb"); |
| 37 | + if (!fp) { |
| 38 | + return UUID4_EFAILURE; |
| 39 | + } |
| 40 | + res = fread(seed, 1, sizeof(seed), fp); |
| 41 | + fclose(fp); |
| 42 | + if ( res != sizeof(seed) ) { |
| 43 | + return UUID4_EFAILURE; |
| 44 | + } |
| 45 | + |
| 46 | +#elif defined(_WIN32) |
| 47 | + int res; |
| 48 | + HCRYPTPROV hCryptProv; |
| 49 | + res = CryptAcquireContext( |
| 50 | + &hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); |
| 51 | + if (!res) { |
| 52 | + return UUID4_EFAILURE; |
| 53 | + } |
| 54 | + res = CryptGenRandom(hCryptProv, (DWORD) sizeof(seed), (PBYTE) seed); |
| 55 | + CryptReleaseContext(hCryptProv, 0); |
| 56 | + if (!res) { |
| 57 | + return UUID4_EFAILURE; |
| 58 | + } |
| 59 | + |
| 60 | +#else |
| 61 | + #error "unsupported platform" |
| 62 | +#endif |
| 63 | + return UUID4_ESUCCESS; |
| 64 | +} |
| 65 | + |
| 66 | + |
| 67 | +void uuid4_generate(char *dst) { |
| 68 | + static const char *template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"; |
| 69 | + static const char *chars = "0123456789abcdef"; |
| 70 | + union { unsigned char b[16]; uint64_t word[2]; } s; |
| 71 | + const char *p; |
| 72 | + int i, n; |
| 73 | + /* get random */ |
| 74 | + s.word[0] = xorshift128plus(seed); |
| 75 | + s.word[1] = xorshift128plus(seed); |
| 76 | + /* build string */ |
| 77 | + p = template; |
| 78 | + i = 0; |
| 79 | + while (*p) { |
| 80 | + n = s.b[i >> 1]; |
| 81 | + n = (i & 1) ? (n >> 4) : (n & 0xf); |
| 82 | + switch (*p) { |
| 83 | + case 'x' : *dst = chars[n]; i++; break; |
| 84 | + case 'y' : *dst = chars[(n & 0x3) + 8]; i++; break; |
| 85 | + default : *dst = *p; |
| 86 | + } |
| 87 | + dst++, p++; |
| 88 | + } |
| 89 | + *dst = '\0'; |
| 90 | +} |
0 commit comments