Skip to content

Commit d261b71

Browse files
committed
refactor(sha): use sha2 crate for hashes instead of sodiumoxide
1 parent c5ca3ab commit d261b71

File tree

12 files changed

+46
-46
lines changed

12 files changed

+46
-46
lines changed

tox_binary_io/src/sodium.rs

+2-13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
use nom::named;
2-
3-
use nom::{map_opt, take};
1+
use nom::{map_opt, named, take};
42

53
use sodiumoxide::crypto::box_::{
64
PublicKey,
@@ -11,7 +9,6 @@ use sodiumoxide::crypto::box_::{
119
NONCEBYTES
1210
};
1311

14-
use sodiumoxide::crypto::hash::{sha256, sha512};
1512
use sodiumoxide::crypto::secretbox;
1613

1714
use super::FromBytes;
@@ -46,18 +43,10 @@ impl FromBytes for secretbox::Nonce {
4643
named!(from_bytes<secretbox::Nonce>, map_opt!(take!(secretbox::NONCEBYTES), secretbox::Nonce::from_slice));
4744
}
4845

49-
impl FromBytes for sha256::Digest {
50-
named!(from_bytes<sha256::Digest>, map_opt!(take!(sha256::DIGESTBYTES), sha256::Digest::from_slice));
51-
}
52-
53-
impl FromBytes for sha512::Digest {
54-
named!(from_bytes<sha512::Digest>, map_opt!(take!(sha512::DIGESTBYTES), sha512::Digest::from_slice));
55-
}
56-
5746
#[cfg(test)]
5847
mod tests {
5948
use super::*;
60-
49+
6150
#[test]
6251
fn public_key_parse_bytes_test() {
6352
let bytes = [42; PUBLICKEYBYTES];

tox_core/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ lru = "0.6"
3232
bitflags = "1.0"
3333
itertools = "0.10"
3434
rand = "0.8"
35+
sha2 = "0.9"
3536

3637
[dependencies.tokio]
3738
version = "1.0"

tox_core/src/dht/server/mod.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -2414,12 +2414,11 @@ mod tests {
24142414
let response = unpack!(packet, Packet::OnionResponse3);
24152415
let response = unpack!(response.payload, InnerOnionResponse::OnionAnnounceResponse);
24162416
let payload = response.get_payload(&precomp).unwrap();
2417-
let ping_id = sha256::Digest(payload.ping_id_or_pk);
24182417

24192418
// announce node
24202419

24212420
let payload = OnionAnnounceRequestPayload {
2422-
ping_id,
2421+
ping_id: payload.ping_id_or_pk,
24232422
search_pk: gen_keypair().0,
24242423
data_pk: gen_keypair().0,
24252424
sendback_data: 42

tox_core/src/onion/client/mod.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ struct OnionNode {
169169
/// Path used to send packets to this node.
170170
path_id: OnionPathId,
171171
/// Ping id that should be used to announce to this node.
172-
ping_id: Option<sha256::Digest>,
172+
ping_id: Option<[u8; 32]>,
173173
/// Data `PublicKey` that should be used to send data packets to our friend
174174
/// through this node.
175175
data_pk: Option<PublicKey>,
@@ -268,7 +268,7 @@ struct AnnouncePacketData<'a> {
268268
impl<'a> AnnouncePacketData<'a> {
269269
/// Create `InnerOnionAnnounceRequest`. The request is a search request if
270270
/// pind_id is 0 and an announce request otherwise.
271-
fn request(&self, node_pk: &PublicKey, ping_id: Option<sha256::Digest>, request_id: u64) -> InnerOnionAnnounceRequest {
271+
fn request(&self, node_pk: &PublicKey, ping_id: Option<[u8; 32]>, request_id: u64) -> InnerOnionAnnounceRequest {
272272
let payload = OnionAnnounceRequestPayload {
273273
ping_id: ping_id.unwrap_or(INITIAL_PING_ID),
274274
search_pk: self.search_pk,
@@ -286,7 +286,7 @@ impl<'a> AnnouncePacketData<'a> {
286286
self.request(node_pk, None, request_id)
287287
}
288288
/// Create `InnerOnionAnnounceRequest` for an announce request.
289-
pub fn announce_request(&self, node_pk: &PublicKey, ping_id: sha256::Digest, request_id: u64) -> InnerOnionAnnounceRequest {
289+
pub fn announce_request(&self, node_pk: &PublicKey, ping_id: [u8; 32], request_id: u64) -> InnerOnionAnnounceRequest {
290290
self.request(node_pk, Some(ping_id), request_id)
291291
}
292292
}
@@ -469,7 +469,7 @@ impl OnionClient {
469469
let (ping_id, data_pk) = if payload.announce_status == AnnounceStatus::Found {
470470
(None, Some(PublicKey(payload.ping_id_or_pk)))
471471
} else {
472-
(Some(sha256::Digest(payload.ping_id_or_pk)), None)
472+
(Some(payload.ping_id_or_pk), None)
473473
};
474474

475475
let now = clock_now();
@@ -1021,7 +1021,7 @@ mod tests {
10211021
keys: [gen_keypair().0, gen_keypair().0, gen_keypair().0],
10221022
path_type: OnionPathType::Udp,
10231023
};
1024-
let ping_id = sha256::hash(&[1, 2, 3]);
1024+
let ping_id = [42; 32];
10251025
let data_pk = gen_keypair().0;
10261026
let new_now = now + Duration::from_secs(1);
10271027
let other_onion_node = OnionNode {
@@ -1228,7 +1228,7 @@ mod tests {
12281228
// The sender should be added to close nodes
12291229
let onion_node = state.announce_list.get_node(&real_pk, &sender_pk).unwrap();
12301230
assert_eq!(onion_node.path_id, path.id());
1231-
assert_eq!(onion_node.ping_id, Some(sha256::Digest(ping_id)));
1231+
assert_eq!(onion_node.ping_id, Some(ping_id));
12321232
assert_eq!(onion_node.data_pk, None);
12331233
assert_eq!(onion_node.announce_status, AnnounceStatus::Announced);
12341234

@@ -1920,7 +1920,7 @@ mod tests {
19201920
state.paths_pool.path_nodes.put(node);
19211921
}
19221922

1923-
let ping_id = sha256::hash(&[1, 2, 3]);
1923+
let ping_id = [42; 32];
19241924
let now = Instant::now();
19251925

19261926
let mut nodes_key_by_addr = HashMap::new();
@@ -2064,7 +2064,7 @@ mod tests {
20642064
saddr,
20652065
path_id: path.id(),
20662066
// regardless of this ping_id search requests should contain 0
2067-
ping_id: Some(sha256::hash(&[1, 2, 3])),
2067+
ping_id: Some([42; 32]),
20682068
data_pk: None,
20692069
unsuccessful_pings: 0,
20702070
added_time: now,

tox_core/src/onion/onion_announce.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
use std::io::{ErrorKind, Error};
55
use std::net::{IpAddr, SocketAddr};
66
use std::time::{Duration, Instant, SystemTime};
7+
use sha2::{Digest, Sha256};
8+
use sha2::digest::generic_array::typenum::marker_traits::Unsigned;
79

810
use tox_binary_io::*;
911
use tox_crypto::*;
@@ -28,7 +30,7 @@ pub const PING_ID_TIMEOUT: Duration = Duration::from_secs(300);
2830
pub const ONION_ANNOUNCE_TIMEOUT: Duration = Duration::from_secs(300);
2931

3032
/// Create onion ping id filled with zeros.
31-
pub const INITIAL_PING_ID: sha256::Digest = sha256::Digest([0; sha256::DIGESTBYTES]);
33+
pub const INITIAL_PING_ID: [u8; 32] = [0; 32];
3234

3335
/** Entry that corresponds to announced onion node.
3436
@@ -137,11 +139,11 @@ impl OnionPingData {
137139
so this hash remains unchanged for `PING_ID_TIMEOUT`.
138140
139141
*/
140-
pub fn ping_id(&self) -> sha256::Digest {
142+
pub fn ping_id(&self) -> [u8; <Sha256 as Digest>::OutputSize::USIZE] {
141143
let mut buf = [0; ONION_PING_DATA_SIZE];
142144
// can not fail since buf has enough length
143145
self.to_bytes((&mut buf, 0)).unwrap();
144-
sha256::hash(&buf)
146+
Sha256::digest(&buf).into()
145147
}
146148
}
147149

@@ -176,7 +178,7 @@ impl OnionAnnounce {
176178
so this hash remains unchanged for `PING_ID_TIMEOUT`.
177179
178180
*/
179-
fn ping_id(&self, time: SystemTime, pk: PublicKey, ip_addr: IpAddr, port: u16) -> sha256::Digest {
181+
fn ping_id(&self, time: SystemTime, pk: PublicKey, ip_addr: IpAddr, port: u16) -> [u8; <Sha256 as Digest>::OutputSize::USIZE] {
180182
let data = OnionPingData {
181183
secret_bytes: self.secret_bytes,
182184
time,
@@ -286,18 +288,18 @@ impl OnionAnnounce {
286288
if entry.data_pk != payload.data_pk {
287289
// failed to find ourselves with same long term pk but different data pk
288290
// weird case, should we remove it?
289-
(AnnounceStatus::Failed, ping_id_2.0)
291+
(AnnounceStatus::Failed, ping_id_2)
290292
} else {
291293
// successfully announced ourselves
292-
(AnnounceStatus::Announced, ping_id_2.0)
294+
(AnnounceStatus::Announced, ping_id_2)
293295
}
294296
} else {
295297
// requested node is found by its long term pk
296298
(AnnounceStatus::Found, entry.data_pk.0)
297299
}
298300
} else {
299301
// requested node not found or failed to announce
300-
(AnnounceStatus::Failed, ping_id_2.0)
302+
(AnnounceStatus::Failed, ping_id_2)
301303
}
302304
}
303305

tox_crypto/src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
pub use sodiumoxide::randombytes::randombytes_into;
66
pub use sodiumoxide::crypto::box_::*;
7-
pub use sodiumoxide::crypto::hash::{sha256, sha512};
87
pub use sodiumoxide::crypto::secretbox;
98

109
pub use sodiumoxide::crypto::pwhash;

tox_encryptsave/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@ edition = "2018"
2121
[dependencies]
2222
tox_crypto = { version = "0.1.0", path = "../tox_crypto" }
2323
failure = "0.1"
24+
sha2 = "0.9"

tox_encryptsave/src/lib.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ assert_eq!(plaintext,
2222
*/
2323

2424
use failure::Fail;
25+
use sha2::{Digest, Sha256};
2526

2627
use tox_crypto::pwhash::{
2728
MEMLIMIT_INTERACTIVE, OPSLIMIT_INTERACTIVE,
@@ -33,7 +34,7 @@ use tox_crypto::{
3334
NONCEBYTES, MACBYTES,
3435
Nonce, PrecomputedKey,
3536
gen_nonce,
36-
secretbox, sha256
37+
secretbox
3738
};
3839

3940
/// Length in bytes of the salt used to encrypt/decrypt data.
@@ -117,7 +118,7 @@ impl PassKey {
117118
pub fn with_salt(passphrase: &[u8], salt: Salt) -> Result<PassKey, KeyDerivationError> {
118119
if passphrase.is_empty() { return Err(KeyDerivationError::Null) };
119120

120-
let sha256::Digest(passhash) = sha256::hash(passphrase);
121+
let passhash = Sha256::digest(passphrase);
121122
let OpsLimit(ops) = OPSLIMIT_INTERACTIVE;
122123
let mut key = secretbox::Key([0; secretbox::KEYBYTES]);
123124

tox_packet/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,4 @@ nom = "5.1"
2626
cookie-factory = "0.3"
2727
bitflags = "1.0"
2828
failure = "0.1"
29+
sha2 = "0.9"

tox_packet/src/dht/cookie.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33

44
use super::*;
55
use nom::number::complete::be_u64;
6+
use sha2::{Digest, Sha512};
7+
use sha2::digest::generic_array::typenum::marker_traits::Unsigned;
68

7-
use std::time::SystemTime;
9+
use std::{convert::TryInto, time::SystemTime};
810

911
use tox_binary_io::*;
1012
use tox_crypto::*;
@@ -160,10 +162,11 @@ impl EncryptedCookie {
160162
}
161163
}
162164
/// Calculate SHA512 hash of encrypted cookie together with nonce
163-
pub fn hash(&self) -> sha512::Digest {
165+
pub fn hash(&self) -> [u8; <Sha512 as Digest>::OutputSize::USIZE] {
164166
let mut buf = [0; 112];
165167
let (_, size) = self.to_bytes((&mut buf, 0)).unwrap();
166-
sha512::hash(&buf[..size])
168+
// TODO: use `Into` directly when GenericArray supports it
169+
Sha512::digest(&buf[..size]).as_slice().try_into().unwrap()
167170
}
168171
}
169172

tox_packet/src/dht/crypto_handshake.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
use super::*;
55

6+
use std::convert::TryInto;
7+
use nom::map_opt;
68
use tox_binary_io::*;
79
use tox_crypto::*;
810
use crate::dht::cookie::EncryptedCookie;
@@ -126,7 +128,7 @@ pub struct CryptoHandshakePayload {
126128
/// used to make sure that possible attacker can't combine payload from old
127129
/// `CryptoHandshake` with new `Cookie` and try to do mess sending such
128130
/// packets.
129-
pub cookie_hash: sha512::Digest,
131+
pub cookie_hash: [u8; 64],
130132
/// Encrypted cookie of sender of `CryptoHandshake` packet. When node
131133
/// receives `CryptoHandshake` it can take this cookie instead of sending
132134
/// `CookieRequest` to obtain one.
@@ -137,7 +139,7 @@ impl FromBytes for CryptoHandshakePayload {
137139
named!(from_bytes<CryptoHandshakePayload>, do_parse!(
138140
base_nonce: call!(Nonce::from_bytes) >>
139141
session_pk: call!(PublicKey::from_bytes) >>
140-
cookie_hash: call!(sha512::Digest::from_bytes) >>
142+
cookie_hash: map_opt!(take!(64), |bytes: &[u8]| bytes.try_into().ok()) >>
141143
cookie: call!(EncryptedCookie::from_bytes) >>
142144
eof!() >>
143145
(CryptoHandshakePayload {
@@ -184,7 +186,7 @@ mod tests {
184186
CryptoHandshakePayload {
185187
base_nonce: gen_nonce(),
186188
session_pk: gen_keypair().0,
187-
cookie_hash: sha512::hash(&[1, 2, 3]),
189+
cookie_hash: [42; 64],
188190
cookie: EncryptedCookie {
189191
nonce: secretbox::gen_nonce(),
190192
payload: vec![42; 88],
@@ -205,7 +207,7 @@ mod tests {
205207
let payload = CryptoHandshakePayload {
206208
base_nonce: gen_nonce(),
207209
session_pk: gen_keypair().0,
208-
cookie_hash: sha512::hash(&[1, 2, 3]),
210+
cookie_hash: [42; 64],
209211
cookie: EncryptedCookie {
210212
nonce: secretbox::gen_nonce(),
211213
payload: vec![42; 88],
@@ -234,7 +236,7 @@ mod tests {
234236
let payload = CryptoHandshakePayload {
235237
base_nonce: gen_nonce(),
236238
session_pk: gen_keypair().0,
237-
cookie_hash: sha512::hash(&[1, 2, 3]),
239+
cookie_hash: [42; 64],
238240
cookie: EncryptedCookie {
239241
nonce: secretbox::gen_nonce(),
240242
payload: vec![42; 88],

tox_packet/src/onion/onion_announce_request.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@
33

44
use super::*;
55

6+
use std::convert::TryInto;
67
use tox_binary_io::*;
78
use tox_crypto::*;
89
use crate::dht::*;
910

1011
use nom::{
1112
flat_map,
13+
map_opt,
1214
number::complete::le_u64,
1315
combinator::{rest, rest_len},
1416
bytes::complete::take
@@ -170,7 +172,7 @@ Length | Content
170172
#[derive(Clone, Debug, Eq, PartialEq)]
171173
pub struct OnionAnnounceRequestPayload {
172174
/// Onion ping id
173-
pub ping_id: sha256::Digest,
175+
pub ping_id: [u8; 32],
174176
/// `PublicKey` we are searching for
175177
pub search_pk: PublicKey,
176178
/// `PublicKey` that should be used for sending data packets
@@ -181,7 +183,7 @@ pub struct OnionAnnounceRequestPayload {
181183

182184
impl FromBytes for OnionAnnounceRequestPayload {
183185
named!(from_bytes<OnionAnnounceRequestPayload>, do_parse!(
184-
ping_id: call!(sha256::Digest::from_bytes) >>
186+
ping_id: map_opt!(take!(32), |bytes: &[u8]| bytes.try_into().ok()) >>
185187
search_pk: call!(PublicKey::from_bytes) >>
186188
data_pk: call!(PublicKey::from_bytes) >>
187189
sendback_data: le_u64 >>
@@ -237,7 +239,7 @@ mod tests {
237239
tox_crypto::crypto_init().unwrap(),
238240
onion_announce_request_payload_encode_decode,
239241
OnionAnnounceRequestPayload {
240-
ping_id: sha256::hash(&[1, 2, 3]),
242+
ping_id: [42; 32],
241243
search_pk: gen_keypair().0,
242244
data_pk: gen_keypair().0,
243245
sendback_data: 12345
@@ -251,7 +253,7 @@ mod tests {
251253
let (bob_pk, _bob_sk) = gen_keypair();
252254
let shared_secret = encrypt_precompute(&bob_pk, &alice_sk);
253255
let payload = OnionAnnounceRequestPayload {
254-
ping_id: sha256::hash(&[1, 2, 3]),
256+
ping_id: [42; 32],
255257
search_pk: gen_keypair().0,
256258
data_pk: gen_keypair().0,
257259
sendback_data: 12345
@@ -272,7 +274,7 @@ mod tests {
272274
let (_eve_pk, eve_sk) = gen_keypair();
273275
let shared_secret = encrypt_precompute(&bob_pk, &alice_sk);
274276
let payload = OnionAnnounceRequestPayload {
275-
ping_id: sha256::hash(&[1, 2, 3]),
277+
ping_id: [42; 32],
276278
search_pk: gen_keypair().0,
277279
data_pk: gen_keypair().0,
278280
sendback_data: 12345

0 commit comments

Comments
 (0)