@@ -6,6 +6,7 @@ use chacha20poly1305::{
6
6
} ;
7
7
use lazy_static:: lazy_static;
8
8
use pin_project:: pin_project;
9
+ use rayon:: prelude:: * ;
9
10
use secrecy:: { ExposeSecret , SecretVec } ;
10
11
use std:: cmp;
11
12
use std:: convert:: TryInto ;
@@ -53,9 +54,9 @@ impl Nonce {
53
54
self . 0 = u128:: from ( val) << 8 ;
54
55
}
55
56
56
- fn increment_counter ( & mut self ) {
57
+ fn increment_counter ( & mut self , by : usize ) {
57
58
// Increment the 11-byte counter
58
- self . 0 += 1 << 8 ;
59
+ self . 0 += ( by as u128 ) << 8 ;
59
60
if self . 0 >> ( 8 * 12 ) != 0 {
60
61
panic ! ( "We overflowed the nonce!" ) ;
61
62
}
@@ -194,26 +195,29 @@ impl Stream {
194
195
let num_chunks = chunks. len ( ) ;
195
196
let mut encrypted = vec ! [ 0 ; chunks_len + TAG_SIZE * num_chunks] ;
196
197
197
- for ( i , ( encrypted , chunk ) ) in encrypted
198
+ encrypted
198
199
. chunks_mut ( ENCRYPTED_CHUNK_SIZE )
199
200
. zip ( chunks)
200
201
. enumerate ( )
201
- {
202
- if i + 1 == num_chunks {
203
- self . nonce . set_last ( last) . unwrap ( ) ;
204
- }
202
+ . par_bridge ( )
203
+ . for_each_with ( self . nonce , |nonce, ( i, ( encrypted, chunk) ) | {
204
+ nonce. increment_counter ( i) ;
205
+ if i + 1 == num_chunks {
206
+ nonce. set_last ( last) . unwrap ( ) ;
207
+ }
205
208
206
- let ( buffer, tag) = encrypted. split_at_mut ( chunk. len ( ) ) ;
207
- buffer. copy_from_slice ( chunk) ;
208
- tag. copy_from_slice (
209
- self . aead
210
- . encrypt_in_place_detached ( & self . nonce . to_bytes ( ) . into ( ) , & [ ] , buffer)
211
- . expect ( "we will never hit chacha20::MAX_BLOCKS because of the chunk size" )
212
- . as_slice ( ) ,
213
- ) ;
209
+ let ( buffer, tag) = encrypted. split_at_mut ( chunk. len ( ) ) ;
210
+ buffer. copy_from_slice ( chunk) ;
211
+ tag. copy_from_slice (
212
+ self . aead
213
+ . encrypt_in_place_detached ( & nonce. to_bytes ( ) . into ( ) , & [ ] , buffer)
214
+ . expect ( "we will never hit chacha20::MAX_BLOCKS because of the chunk size" )
215
+ . as_slice ( ) ,
216
+ ) ;
217
+ } ) ;
214
218
215
- self . nonce . increment_counter ( ) ;
216
- }
219
+ self . nonce . increment_counter ( num_chunks ) ;
220
+ self . nonce . set_last ( last ) . unwrap ( ) ;
217
221
218
222
Ok ( encrypted)
219
223
}
@@ -248,7 +252,7 @@ impl Stream {
248
252
)
249
253
. map_err ( |_| io:: Error :: new ( io:: ErrorKind :: InvalidData , "decryption error" ) ) ?;
250
254
251
- self . nonce . increment_counter ( ) ;
255
+ self . nonce . increment_counter ( 1 ) ;
252
256
}
253
257
254
258
Ok ( SecretVec :: new ( decrypted) )
0 commit comments