1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use libc::{size_t, c_int, c_void};
use libc::{EINVAL, E2BIG, EOVERFLOW};
use libc::memset;
use sgx_types::sgx_status_t;
use rand_core::RngCore;
use rdrand;
use std::ptr::copy_nonoverlapping;
use std::slice;
type errno_t = c_int;
const SIZE_MAX: size_t = std::usize::MAX;
#[allow(clippy::absurd_extreme_comparisons)]
#[no_mangle]
pub unsafe extern "C"
fn memset_s(p: *mut c_void,
destsz: size_t,
ch: c_int,
count: size_t) -> errno_t {
if p.is_null() {
return EINVAL;
}
if destsz > SIZE_MAX || count > SIZE_MAX {
return E2BIG;
}
if count > destsz {
return EOVERFLOW;
}
memset(p, ch, count);
0
}
#[no_mangle]
pub unsafe extern "C"
fn consttime_memequal(b1: *const u8,
b2: *const u8,
l: usize) -> i32 {
let mut res: u32 = 0;
let mut len = l;
let p1 = slice::from_raw_parts(b1, l);
let p2 = slice::from_raw_parts(b2, l);
while len > 0 {
len -= 1;
res |= (p1[len] ^ p2[len]) as u32;
}
(1 & ((res - 1) >> 8)) as i32
}
#[no_mangle]
pub unsafe extern "C"
fn sgx_read_rand(rand: *mut u8, len: size_t) -> sgx_status_t {
if rand.is_null() || len == 0 || len > std::u32::MAX as usize {
return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
}
let mut tmp = vec![0; len];
let mut rnd = rdrand::RdRand::new().unwrap();
rnd.fill_bytes(&mut tmp);
copy_nonoverlapping(tmp.as_ptr(), rand, len);
sgx_status_t::SGX_SUCCESS
}
pub fn hex_to_bytes(hex_string: &str) -> Vec<u8> {
let input_chars: Vec<_> = hex_string.chars().collect();
input_chars.chunks(2).map(|chunk| {
let first_byte = chunk[0].to_digit(16).unwrap();
let second_byte = chunk[1].to_digit(16).unwrap();
((first_byte << 4) | second_byte) as u8
}).collect()
}