Ockam logo
Product
OverviewCloud SDKEdge SDKEmbedded SDKRegistryRouter
Contact us

Generate random bytes

Once we have an initialized vault handle of type ockam_vault_t, we can call any of the functions from ockam/vault.h using this handle.

One such function is ockam_vault_random_bytes_generate which fills a buffer with random bytes. It accepts a handle to an initialized vault, a pointer to the start of a buffer and the size of the buffer.

1const size_t random_bytes_length = 64;
2uint8_t random_bytes[random_bytes_length] = { 0 };
3
4error = ockam_vault_random_bytes_generate(&vault,
5 &random_bytes[0],
6 random_bytes_length);
7if (error) goto exit;

If the function succeeds the return value is OCKAM_ERROR_NONE.

Complete Example

1
2#include "ockam/error.h"
3
4#include "ockam/memory.h"
5#include "ockam/memory/stdlib.h"
6
7#include "ockam/random.h"
8#include "ockam/random/urandom.h"
9
10#include "ockam/vault.h"
11#include "ockam/vault/default.h"
12
13#include <stdio.h>
14
15int main(void)
16{
17 int exit_code = 0;
18
19 ockam_error_t error = OCKAM_ERROR_NONE;
20 ockam_error_t deinit_error = OCKAM_ERROR_NONE;
21
22 /* Initialize the default vault using urandom for random and stdlib for memory */
23
24 ockam_memory_t memory = { 0 };
25 ockam_random_t random = { 0 };
26 ockam_vault_t vault = { 0 };
27 ockam_vault_default_attributes_t vault_attributes = { .memory = &memory, .random = &random };
28
29 error = ockam_memory_stdlib_init(&memory);
30 if (error != OCKAM_ERROR_NONE) { goto exit; }
31
32 error = ockam_random_urandom_init(&random);
33 if (error != OCKAM_ERROR_NONE) { goto exit; }
34
35 error = ockam_vault_default_init(&vault, &vault_attributes);
36 if (error != OCKAM_ERROR_NONE) { goto exit; }
37
38 /* Fill the random bytes buffer with 64 bytes of random data */
39
40 const size_t random_bytes_length = 64;
41 uint8_t random_bytes[random_bytes_length] = { 0 };
42
43 error = ockam_vault_random_bytes_generate(&vault,
44 &random_bytes[0],
45 random_bytes_length);
46 if (error != OCKAM_ERROR_NONE) { goto exit; }
47
48 int i;
49 for (i = 0; i < random_bytes_length; i++) { printf("%02x", random_bytes[i]); }
50 printf("\n");
51
52exit:
53
54 /* Deinitialize to free resources associated with this handle. */
55
56 deinit_error = ockam_vault_deinit(&vault);
57 ockam_random_deinit(&random);
58 ockam_memory_deinit(&memory);
59
60 if (error == OCKAM_ERROR_NONE) { error = deinit_error; }
61 if (error != OCKAM_ERROR_NONE) { exit_code = -1; }
62 return exit_code;
63}
Previous

Setup a Vault

Next

SHA-256

On this page
  • Generate random bytes
  • Complete Example
Edit this page
Star Ockam repo