1
1
use std:: fmt;
2
2
3
- use aes_gcm :: {
4
- AeadCore , Aes256Gcm , Nonce ,
5
- aead :: { generic_array :: GenericArray , Aead , KeyInit , OsRng } ,
3
+ use chacha20poly1305 :: {
4
+ aead :: { Aead , AeadCore , KeyInit , OsRng , generic_array :: GenericArray } ,
5
+ XChaCha20Poly1305 , XNonce ,
6
6
} ;
7
7
use cookie:: Key ;
8
8
use serde:: { de, ser, Deserialize , Serialize } ;
9
9
10
10
use crate :: request:: { Outcome , Request , FromRequest } ;
11
11
12
- const NONCE_LEN : usize = 12 ;
12
+ const NONCE_LEN : usize = 24 ; // 192-bit
13
13
const KEY_LEN : usize = 32 ;
14
14
15
15
#[ derive( Debug ) ]
@@ -218,14 +218,12 @@ impl SecretKey {
218
218
. try_into ( )
219
219
. map_err ( |_| Error :: KeyLengthError ) ?;
220
220
221
- // Create a new AES-256-GCM instance with the provided key
222
- let aead = Aes256Gcm :: new ( GenericArray :: from_slice ( & key ) ) ;
221
+ let cipher = XChaCha20Poly1305 :: new ( GenericArray :: from_slice ( & key) ) ;
222
+ let nonce = XChaCha20Poly1305 :: generate_nonce ( & mut OsRng ) ;
223
223
224
- // Generate a random nonce
225
- let nonce = Aes256Gcm :: generate_nonce ( & mut OsRng ) ;
226
-
227
- // Encrypt the plaintext using the nonce
228
- let ciphertext = aead. encrypt ( & nonce, value. as_ref ( ) ) . map_err ( |_| Error :: EncryptionError ) ?;
224
+ let ciphertext = cipher
225
+ . encrypt ( & nonce, value. as_ref ( ) )
226
+ . map_err ( |_| Error :: EncryptionError ) ?;
229
227
230
228
// Prepare a vector to hold the nonce and ciphertext
231
229
let mut encrypted_data = Vec :: with_capacity ( NONCE_LEN + ciphertext. len ( ) ) ;
@@ -248,19 +246,18 @@ impl SecretKey {
248
246
249
247
// Split the decoded data into nonce and ciphertext
250
248
let ( nonce, ciphertext) = encrypted. split_at ( NONCE_LEN ) ;
251
- let nonce = Nonce :: from_slice ( nonce) ;
249
+ let nonce = XNonce :: from_slice ( nonce) ;
252
250
253
251
// Convert the encryption key to a fixed-length array
254
252
let key: [ u8 ; KEY_LEN ] = self . key
255
253
. encryption ( )
256
254
. try_into ( )
257
255
. map_err ( |_| Error :: KeyLengthError ) ?;
258
256
259
- // Create a new AES-256-GCM instance with the provided key
260
- let aead = Aes256Gcm :: new ( GenericArray :: from_slice ( & key) ) ;
257
+ let cipher = XChaCha20Poly1305 :: new ( GenericArray :: from_slice ( & key) ) ;
261
258
262
259
// Decrypt the ciphertext using the nonce
263
- let decrypted = aead . decrypt ( nonce, ciphertext)
260
+ let decrypted = cipher . decrypt ( nonce, ciphertext)
264
261
. map_err ( |_| Error :: DecryptionError ) ?;
265
262
266
263
Ok ( decrypted)
0 commit comments