Skip to content

Commit c1db5ad

Browse files
committed
encoding/serialization: set top three bits of last byte to zero
1 parent 08bb29e commit c1db5ad

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/encoding.rs

+7
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ impl Encoding {
2828
}
2929

3030
pub fn vartime_decompress(&self) -> Result<Element, EncodingError> {
31+
// Top three bits of last byte should be zero
32+
if self.0[31] >> 5 != 0u8 {
33+
return Err(EncodingError::InvalidEncoding);
34+
}
35+
3136
// This isn't a constant, only because traits don't have const methods
3237
// yet and multiplication is only implemented as part of the Mul trait.
3338
let D4: Fq = EdwardsParameters::COEFF_D * Fq::from(4u32);
@@ -120,6 +125,8 @@ impl Element {
120125
debug_assert_eq!(s.serialized_size(), 32);
121126
s.serialize(&mut bytes[..])
122127
.expect("serialization into array should be infallible");
128+
// Set top three bits of last byte to zero
129+
bytes[31] &= 0b00011111;
123130

124131
Encoding(bytes)
125132
}

src/field_ext.rs

+8
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,18 @@ impl FieldExt for Fq {
3030
debug_assert_eq!(self.serialized_size(), 32);
3131
self.serialize(&mut bytes[..])
3232
.expect("serialization into array should be infallible");
33+
// Set top three bits of last byte to zero
34+
bytes[31] &= 0b00011111;
35+
3336
bytes
3437
}
3538

3639
fn from_bytes(bytes: [u8; 32]) -> Result<Self, EncodingError> {
40+
// Top three bits of last byte should be zero
41+
if bytes[31] >> 5 != 0u8 {
42+
return Err(EncodingError::InvalidEncoding);
43+
}
44+
3745
Self::deserialize(&bytes[..]).map_err(|_| EncodingError::InvalidEncoding)
3846
}
3947
}

0 commit comments

Comments
 (0)