/
forward_secure.rs
211 lines (188 loc) · 7.39 KB
/
forward_secure.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! Types for forward-secure encryption used for distributed key generation
use crate::curves::bls12_381;
use ic_protobuf::registry::crypto::v1::AlgorithmId as AlgorithmIdProto;
use ic_protobuf::registry::crypto::v1::PublicKey as PublicKeyProto;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fmt;
use strum_macros::IntoStaticStr;
#[cfg(test)]
mod tests;
/// Forward secure encryption public key
#[derive(Copy, Clone, Debug, Eq, IntoStaticStr, PartialEq, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub enum CspFsEncryptionPublicKey {
Groth20_Bls12_381(groth20_bls12_381::FsEncryptionPublicKey),
}
/// Forward secure encryption proof of possession.
#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoStaticStr, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub enum CspFsEncryptionPop {
Groth20_Bls12_381(groth20_bls12_381::FsEncryptionPok),
Groth20WithPop_Bls12_381(groth20_bls12_381::FsEncryptionPop),
}
impl TryFrom<PublicKeyProto> for CspFsEncryptionPublicKey {
type Error = MalformedFsEncryptionPublicKeyError;
fn try_from(pk_proto: PublicKeyProto) -> Result<Self, MalformedFsEncryptionPublicKeyError> {
Self::try_from(&pk_proto)
}
}
impl TryFrom<&PublicKeyProto> for CspFsEncryptionPublicKey {
type Error = MalformedFsEncryptionPublicKeyError;
fn try_from(pk_proto: &PublicKeyProto) -> Result<Self, MalformedFsEncryptionPublicKeyError> {
if pk_proto.algorithm != AlgorithmIdProto::Groth20Bls12381 as i32 {
return Err(MalformedFsEncryptionPublicKeyError {
key_bytes: pk_proto.clone().key_value,
internal_error: format!("Unknown algorithm: {}", pk_proto.algorithm),
});
}
if pk_proto.key_value.len() != groth20_bls12_381::FsEncryptionPublicKey::SIZE {
return Err(MalformedFsEncryptionPublicKeyError {
key_bytes: pk_proto.clone().key_value,
internal_error: format!(
"Wrong data length {}, expected length {}.",
pk_proto.key_value.len(),
bls12_381::G1Bytes::SIZE
),
});
}
let mut pk_array = [0u8; bls12_381::G1Bytes::SIZE];
pk_array[..].copy_from_slice(&pk_proto.key_value);
Ok(CspFsEncryptionPublicKey::Groth20_Bls12_381(
groth20_bls12_381::FsEncryptionPublicKey(bls12_381::G1Bytes(pk_array)),
))
}
}
/// A forward secure encryption public key is malformed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MalformedFsEncryptionPublicKeyError {
pub key_bytes: Vec<u8>,
pub internal_error: String,
}
impl fmt::Display for MalformedFsEncryptionPublicKeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"MalformedFsEncryptionPublicKeyError {{ key_bytes: 0x{}, internal_error: {} }}",
hex::encode(&self.key_bytes[..]),
self.internal_error
)
}
}
impl TryFrom<&PublicKeyProto> for CspFsEncryptionPop {
type Error = CspFsEncryptionPopFromPublicKeyProtoError;
fn try_from(pk_proto: &PublicKeyProto) -> Result<Self, Self::Error> {
if pk_proto.algorithm != AlgorithmIdProto::Groth20Bls12381 as i32 {
return Err(
CspFsEncryptionPopFromPublicKeyProtoError::UnknownAlgorithm {
algorithm: pk_proto.algorithm,
},
);
}
let proof_bytes = pk_proto
.proof_data
.as_ref()
.ok_or(CspFsEncryptionPopFromPublicKeyProtoError::MissingProofData)?;
serde_cbor::from_slice::<CspFsEncryptionPop>(proof_bytes).map_err(|e| {
CspFsEncryptionPopFromPublicKeyProtoError::MalformedPop {
pop_bytes: proof_bytes.clone(),
internal_error: format!("{}", e),
}
})
}
}
/// The forward secure encryption proof of possession (PoP) cannot be obtained
/// from its protobuf.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CspFsEncryptionPopFromPublicKeyProtoError {
UnknownAlgorithm {
algorithm: i32,
},
MissingProofData,
MalformedPop {
pop_bytes: Vec<u8>,
internal_error: String,
},
}
impl fmt::Display for CspFsEncryptionPopFromPublicKeyProtoError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CspFsEncryptionPopFromPublicKeyProtoError::UnknownAlgorithm { algorithm } => write!(
f,
"Unknown algorithm: {:?}",
AlgorithmIdProto::from_i32(*algorithm)
),
CspFsEncryptionPopFromPublicKeyProtoError::MissingProofData => {
write!(f, "Missing proof data",)
}
CspFsEncryptionPopFromPublicKeyProtoError::MalformedPop {
pop_bytes,
internal_error,
} => write!(
f,
"Malformed proof of possession (PoP): {} (0x{})",
internal_error,
hex::encode(pop_bytes),
),
}
}
}
pub mod groth20_bls12_381 {
//! The forward secure encryption keys used in Groth20.
use crate::curves::bls12_381::{FrBytes, G1Bytes, G2Bytes};
use crate::NodeIndex;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
/// Forward secure encryption public key used in Groth20.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct FsEncryptionPublicKey(pub G1Bytes);
impl FsEncryptionPublicKey {
pub const SIZE: usize = G1Bytes::SIZE;
#[inline]
pub fn as_bytes(&self) -> &[u8; Self::SIZE] {
self.0.as_bytes()
}
}
//CRP-900: remove the following once the new POP is used
/// Old proof of knowledge
#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct FsEncryptionPok {
pub blinder: G1Bytes,
pub response: FrBytes,
}
/// Forward secure encryption proof of possession.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct FsEncryptionPop {
pub pop_key: G1Bytes,
pub challenge: FrBytes,
pub response: FrBytes,
}
pub const CHUNK_BYTES: usize = 2;
pub const NUM_CHUNKS: usize = (FrBytes::SIZE + CHUNK_BYTES - 1) / CHUNK_BYTES;
// Note: the spec currently has: Vec<(r,s,z)>; this could be represented more
// strongly as [(G1,G1,G2);NUM_CHUNKS], which is equivalent to the below.
#[derive(Debug, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct FsEncryptionCiphertextBytes {
pub rand_r: [G1Bytes; NUM_CHUNKS],
pub rand_s: [G1Bytes; NUM_CHUNKS],
pub rand_z: [G2Bytes; NUM_CHUNKS],
pub ciphertext_chunks: Vec<[G1Bytes; NUM_CHUNKS]>,
}
impl FsEncryptionCiphertextBytes {
//! Accessors by NodeIndex:
pub fn len(&self) -> usize {
self.ciphertext_chunks.len()
}
pub fn is_empty(&self) -> bool {
self.ciphertext_chunks.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (NodeIndex, &[G1Bytes; NUM_CHUNKS])> + '_ {
(0_u32..).zip(&self.ciphertext_chunks)
}
pub fn get(&self, node_index: NodeIndex) -> Option<&[G1Bytes; NUM_CHUNKS]> {
usize::try_from(node_index)
.ok()
.and_then(|node_index| self.ciphertext_chunks.get(node_index))
}
}
}