forked from tari-project/tari
/
encryption.rs
180 lines (154 loc) · 7.16 KB
/
encryption.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
// Copyright 2020. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::mem::size_of;
use chacha20poly1305::{
aead::{Aead, Error as AeadError, Payload},
Tag,
XChaCha20Poly1305,
XNonce,
};
use rand::{rngs::OsRng, RngCore};
use tari_utilities::{ByteArray, Hidden};
pub trait Encryptable<C> {
const KEY_MANAGER: &'static [u8] = b"KEY_MANAGER";
const OUTPUT: &'static [u8] = b"OUTPUT";
const WALLET_SETTING_MASTER_SEED: &'static [u8] = b"MASTER_SEED";
const WALLET_SETTING_TOR_ID: &'static [u8] = b"TOR_ID";
const INBOUND_TRANSACTION: &'static [u8] = b"INBOUND_TRANSACTION";
const OUTBOUND_TRANSACTION: &'static [u8] = b"OUTBOUND_TRANSACTION";
const COMPLETED_TRANSACTION: &'static [u8] = b"COMPLETED_TRANSACTION";
const KNOWN_ONESIDED_PAYMENT_SCRIPT: &'static [u8] = b"KNOWN_ONESIDED_PAYMENT_SCRIPT";
const CLIENT_KEY_VALUE: &'static [u8] = b"CLIENT_KEY_VALUE";
fn domain(&self, field_name: &'static str) -> Vec<u8>;
fn encrypt(&mut self, cipher: &C) -> Result<(), String>;
fn decrypt(&mut self, cipher: &C) -> Result<(), String>;
}
// Decrypt data (with domain binding and authentication) using XChaCha20-Poly1305
pub fn decrypt_bytes_integral_nonce(
cipher: &XChaCha20Poly1305,
domain: Vec<u8>,
ciphertext: Vec<u8>,
) -> Result<Vec<u8>, String> {
// We need at least a nonce and tag, or there's no point in attempting decryption
if ciphertext.len() < size_of::<XNonce>() + size_of::<Tag>() {
return Err(AeadError.to_string());
}
// Extract the nonce
let (nonce, ciphertext) = ciphertext.split_at(size_of::<XNonce>());
let nonce_ga = XNonce::from_slice(nonce);
let payload = Payload {
msg: ciphertext,
aad: domain.as_bytes(),
};
// Attempt authentication and decryption
let plaintext = cipher.decrypt(nonce_ga, payload).map_err(|e| e.to_string())?;
Ok(plaintext)
}
// Encrypt data (with domain binding and authentication) using XChaCha20-Poly1305
pub fn encrypt_bytes_integral_nonce(
cipher: &XChaCha20Poly1305,
domain: Vec<u8>,
plaintext: Hidden<Vec<u8>>,
) -> Result<Vec<u8>, String> {
// Produce a secure random nonce
let mut nonce = [0u8; size_of::<XNonce>()];
OsRng.fill_bytes(&mut nonce);
let nonce_ga = XNonce::from_slice(&nonce);
// Bind the domain as additional data
let payload = Payload {
msg: plaintext.reveal(),
aad: domain.as_slice(),
};
// Attempt authenticated encryption
let mut ciphertext = cipher.encrypt(nonce_ga, payload).map_err(|e| e.to_string())?;
// Concatenate the nonce and ciphertext (which already include the tag)
let mut ciphertext_integral_nonce = nonce.to_vec();
ciphertext_integral_nonce.append(&mut ciphertext);
Ok(ciphertext_integral_nonce)
}
#[cfg(test)]
mod test {
use std::mem::size_of;
use chacha20poly1305::{Key, KeyInit, Tag, XChaCha20Poly1305, XNonce};
use rand::{rngs::OsRng, RngCore};
use tari_utilities::{ByteArray, Hidden};
use crate::util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce};
#[test]
fn test_encrypt_decrypt() {
// Encrypt a message
let plaintext = b"The quick brown fox was annoying".to_vec();
let mut key = [0u8; size_of::<Key>()];
OsRng.fill_bytes(&mut key);
let key_ga = Key::from_slice(&key);
let cipher = XChaCha20Poly1305::new(key_ga);
let ciphertext =
encrypt_bytes_integral_nonce(&cipher, b"correct_domain".to_vec(), Hidden::hide(plaintext.clone())).unwrap();
// Check the ciphertext size, which we rely on for later tests
// It should extend the plaintext size by the nonce and tag sizes
assert_eq!(
ciphertext.len(),
size_of::<XNonce>() + plaintext.len() + size_of::<Tag>()
);
// Valid decryption must succeed and yield correct plaintext
let decrypted_text =
decrypt_bytes_integral_nonce(&cipher, b"correct_domain".to_vec(), ciphertext.clone()).unwrap();
assert_eq!(decrypted_text, plaintext);
// Must fail on an incorrect domain
assert!(decrypt_bytes_integral_nonce(&cipher, b"wrong_domain".to_vec(), ciphertext.clone()).is_err());
// Must fail with an evil nonce
let ciphertext_with_evil_nonce = ciphertext
.clone()
.splice(0..size_of::<XNonce>(), [0u8; size_of::<XNonce>()])
.collect();
assert!(decrypt_bytes_integral_nonce(&cipher, b"correct_domain".to_vec(), ciphertext_with_evil_nonce).is_err());
// Must fail with malleated ciphertext
let ciphertext_with_evil_ciphertext = ciphertext
.clone()
.splice(
size_of::<XNonce>()..(ciphertext.len() - size_of::<Tag>()),
vec![0u8; plaintext.len()],
)
.collect();
assert!(
decrypt_bytes_integral_nonce(&cipher, b"correct_domain".to_vec(), ciphertext_with_evil_ciphertext).is_err()
);
// Must fail with malleated authentication tag
let ciphertext_with_evil_tag = ciphertext
.clone()
.splice((ciphertext.len() - size_of::<Tag>())..ciphertext.len(), vec![
0u8;
size_of::<
Tag,
>(
)
])
.collect();
assert!(decrypt_bytes_integral_nonce(&cipher, b"correct_domain".to_vec(), ciphertext_with_evil_tag).is_err());
// Must fail if truncated too short (if shorter than a nonce and tag, decryption is not even attempted)
assert!(decrypt_bytes_integral_nonce(
&cipher,
b"correct_domain".to_vec(),
ciphertext[0..(size_of::<XNonce>() + size_of::<Tag>() - 1)].to_vec()
)
.is_err());
}
}