/
lwe_secret_key.rs
84 lines (70 loc) · 2 KB
/
lwe_secret_key.rs
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
use super::CsprngMut;
use crate::implementation::{Container, ContainerMut, Split};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[readonly::make]
pub struct LweSecretKey<C: Container> {
pub data: C,
pub lwe_dimension: usize,
}
impl<C: Container> LweSecretKey<C> {
pub fn data_len(lwe_dimension: usize) -> usize {
lwe_dimension
}
pub fn new(data: C, lwe_dimension: usize) -> Self {
debug_assert_eq!(data.len(), Self::data_len(lwe_dimension));
Self {
data,
lwe_dimension,
}
}
pub unsafe fn from_raw_parts(data: C::Pointer, lwe_dimension: usize) -> Self
where
C: Split,
{
Self {
data: C::from_raw_parts(data, Self::data_len(lwe_dimension)),
lwe_dimension,
}
}
pub fn as_view(&self) -> LweSecretKey<&[C::Item]> {
LweSecretKey {
data: self.data.as_ref(),
lwe_dimension: self.lwe_dimension,
}
}
pub fn as_mut_view(&mut self) -> LweSecretKey<&mut [C::Item]>
where
C: ContainerMut,
{
LweSecretKey {
data: self.data.as_mut(),
lwe_dimension: self.lwe_dimension,
}
}
pub fn into_data(self) -> C {
self.data
}
}
impl LweSecretKey<&mut [u64]> {
pub fn fill_with_new_key(self, mut csprng: CsprngMut<'_, '_>) {
for sk_bit in self.data {
let mut bytes = [0_u8; 1];
let success_count = csprng.as_mut().next_bytes(&mut bytes);
if success_count == 0 {
panic!("Csprng failed to generate random bytes");
}
*sk_bit = (bytes[0] & 1) as u64;
}
}
}
pub mod test {
use super::*;
use crate::implementation::types::CsprngMut;
impl LweSecretKey<Vec<u64>> {
pub fn new_random(csprng: CsprngMut, dim: usize) -> Self {
let mut sk = LweSecretKey::new(vec![0; dim], dim);
sk.as_mut_view().fill_with_new_key(csprng);
sk
}
}
}