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
use dusk_plonk::bls12_381::Scalar as BlsScalar;
use std::io;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct EncryptedData {
a: BlsScalar,
b: BlsScalar,
}
impl EncryptedData {
pub fn encrypt(
message: &BlsScalar,
secret: &BlsScalar,
nonce: &BlsScalar,
) -> Self {
let a = *message;
let b = secret + nonce;
Self { a, b }
}
pub fn decrypt(
&self,
secret: &BlsScalar,
nonce: &BlsScalar,
) -> Option<BlsScalar> {
if self.b == secret + nonce {
Some(self.a)
} else {
None
}
}
}
impl io::Write for EncryptedData {
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
if buf.len() < 64 {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
}
let mut a = [0u8; 32];
let mut b = [0u8; 32];
let mut n = a.as_mut().write(&buf[..32])?;
n += b.as_mut().write(&buf[32..])?;
let a = BlsScalar::from_bytes(&a);
if a.is_none().into() {
return Err(io::Error::from(io::ErrorKind::InvalidData));
}
self.a = a.unwrap();
let b = BlsScalar::from_bytes(&b);
if b.is_none().into() {
return Err(io::Error::from(io::ErrorKind::InvalidData));
}
self.b = b.unwrap();
Ok(n)
}
fn flush(&mut self) -> Result<(), io::Error> {
Ok(())
}
}
impl io::Read for EncryptedData {
fn read(&mut self, mut buf: &mut [u8]) -> Result<usize, io::Error> {
let a = (&mut self.a.to_bytes().as_ref()).read(&mut buf)?;
let b = (&mut self.b.to_bytes().as_ref()).read(&mut buf)?;
Ok(a + b)
}
}