Software APIs
random_order.c
1
// Copyright lowRISC contributors (OpenTitan project).
2
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3
// SPDX-License-Identifier: Apache-2.0
4
5
#include "
sw/device/lib/base/random_order.h
"
6
7
#include "
sw/device/lib/base/bitfield.h
"
8
#include "
sw/device/lib/base/hardened.h
"
9
#include "sw/device/lib/crypto/drivers/rv_core_ibex.h"
10
11
void
random_order_init(
random_order_t
*ctx,
size_t
min_len) {
12
ctx->
ctr
= 0;
13
if
(min_len > 0) {
14
ctx->
state
=
random_order_random_word
() % min_len;
15
}
else
{
16
ctx->
state
= 0;
17
}
18
ctx->
max
= min_len;
19
}
20
21
size_t
random_order_len(
const
random_order_t
*ctx) {
return
ctx->
max
; }
22
23
size_t
random_order_advance(
random_order_t
*ctx) {
24
size_t
out = ctx->
state
;
25
// Compute the next value and next value if we overflow max.
26
size_t
next = ctx->
state
+ 1;
27
size_t
next_overflow = next - ctx->
max
;
28
29
// Is next strictly less than max?
30
ct_bool32_t
which = ct_sltu32(next, ctx->
max
);
31
// If yes, choose next, else next_overflow.
32
ctx->
state
= ct_cmov32(which, next, next_overflow);
33
34
ctx->
ctr
= launder32(ctx->
ctr
) + 1;
35
HARDENED_CHECK_LE(ctx->
state
, ctx->
max
);
36
return
out;
37
}
sw
device
lib
base
random_order.c
Return to
OpenTitan Documentation