-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathlib.rs
More file actions
284 lines (242 loc) · 8.46 KB
/
lib.rs
File metadata and controls
284 lines (242 loc) · 8.46 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
//! Implementation of the [Salsa] family of stream ciphers.
//!
//! Cipher functionality is accessed using traits from re-exported [`cipher`] crate.
//!
//! # ⚠️ Security Warning: Hazmat!
//!
//! This crate does not ensure ciphertexts are authentic! Thus ciphertext integrity
//! is not verified, which can lead to serious vulnerabilities!
//!
//! USE AT YOUR OWN RISK!
//!
//! # Diagram
//!
//! This diagram illustrates the Salsa quarter round function.
//! Each round consists of four quarter-rounds:
//!
//! <img src="https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/img/stream-ciphers/salsa20.png" width="300px">
//!
//! Legend:
//!
//! - ⊞ add
//! - ‹‹‹ rotate
//! - ⊕ xor
//!
//! # Example
//! ```
//! use salsa20::Salsa20;
//! // Import relevant traits
//! use salsa20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
//! use hex_literal::hex;
//!
//! let key = [0x42; 32];
//! let nonce = [0x24; 8];
//! let plaintext = hex!("00010203 04050607 08090A0B 0C0D0E0F");
//! let ciphertext = hex!("85843cc5 d58cce7b 5dd3dd04 fa005ded");
//!
//! // Key and IV must be references to the `Array` type.
//! // Here we use the `Into` trait to convert arrays into it.
//! let mut cipher = Salsa20::new(&key.into(), &nonce.into());
//!
//! let mut buffer = plaintext.clone();
//!
//! // apply keystream (encrypt)
//! cipher.apply_keystream(&mut buffer);
//! assert_eq!(buffer, ciphertext);
//!
//! let ciphertext = buffer.clone();
//!
//! // Salsa ciphers support seeking
//! cipher.seek(0u32);
//!
//! // decrypt ciphertext by applying keystream again
//! cipher.apply_keystream(&mut buffer);
//! assert_eq!(buffer, plaintext);
//!
//! // stream ciphers can be used with streaming messages
//! cipher.seek(0u32);
//! for chunk in buffer.chunks_mut(3) {
//! cipher.apply_keystream(chunk);
//! }
//! assert_eq!(buffer, ciphertext);
//! ```
//!
//! Salsa20 will run the SSE2 backend in x86(-64) targets for Salsa20/20 variant.
//! Other variants will fallback to the software backend.
//!
//! [Salsa]: https://en.wikipedia.org/wiki/Salsa20
#![no_std]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
)]
#![warn(missing_docs, rust_2018_idioms, trivial_casts, unused_qualifications)]
pub use cipher;
use cipher::{
Block, BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherClosure,
StreamCipherCore, StreamCipherCoreWrapper, StreamCipherSeekCore,
array::{Array, ArraySize, typenum::Unsigned},
consts::{U4, U6, U8, U10, U16, U24, U32, U64},
};
use core::marker::PhantomData;
#[cfg(feature = "zeroize")]
use cipher::zeroize::{Zeroize, ZeroizeOnDrop};
mod backends;
mod xsalsa;
pub use xsalsa::{XSalsa8, XSalsa12, XSalsa20, XSalsaCore, hsalsa};
/// Salsa20/8 stream cipher
/// (reduced-round variant of Salsa20 with 8 rounds, *not recommended*)
pub type Salsa8 = StreamCipherCoreWrapper<SalsaCore<U4, U32>>;
/// Salsa20/12 stream cipher
/// (reduced-round variant of Salsa20 with 12 rounds, *not recommended*)
pub type Salsa12 = StreamCipherCoreWrapper<SalsaCore<U6, U32>>;
/// Salsa20/20 stream cipher
/// (20 rounds; **recommended**)
pub type Salsa20 = StreamCipherCoreWrapper<SalsaCore<U10, U32>>;
/// Salsa20/20 stream cipher, using 16-byte keys (*not recommended*)
///
/// # ⚠️ Security warning
///
/// Using Salsa20 with keys shorter than 32 bytes is
/// [**explicitly discouraged** by its creator][0]. It is included for
/// compatibility with systems that use these weaker keys.
///
/// [0]: https://cr.yp.to/snuffle/keysizes.pdf
pub type Salsa20_16 = StreamCipherCoreWrapper<SalsaCore<U10, U16>>;
/// Key type used by all Salsa variants and [`XSalsa20`].
pub type Key<KeySize = U32> = Array<u8, KeySize>;
/// Nonce type used by all Salsa variants.
pub type Nonce = Array<u8, U8>;
/// Nonce type used by [`XSalsa20`].
pub type XNonce = Array<u8, U24>;
/// Number of 32-bit words in the Salsa20 state
const STATE_WORDS: usize = 16;
/// State initialization constant for 16-byte keys ("expand 16-byte k")
const CONSTANTS_16: [u32; 4] = [0x6170_7865, 0x3120_646e, 0x7962_2d36, 0x6b20_6574];
/// State initialization constant for 32-byte keys ("expand 32-byte k")
const CONSTANTS_32: [u32; 4] = [0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574];
/// The Salsa20 core function.
pub struct SalsaCore<R: Unsigned, KeySize = U32> {
/// Internal state of the core function
state: [u32; STATE_WORDS],
/// Number of rounds to perform
rounds: PhantomData<R>,
/// Key size
key_size: PhantomData<KeySize>,
}
impl<R: Unsigned, KeySize> SalsaCore<R, KeySize> {
/// Create new Salsa core from raw state.
///
/// This method is mainly intended for the `scrypt` crate.
/// Other users generally should not use this method.
pub fn from_raw_state(state: [u32; STATE_WORDS]) -> Self {
Self {
state,
rounds: PhantomData,
key_size: PhantomData,
}
}
}
impl<R: Unsigned, KeySize> KeySizeUser for SalsaCore<R, KeySize>
where
KeySize: ArraySize,
{
type KeySize = KeySize;
}
impl<R: Unsigned, KeySize> IvSizeUser for SalsaCore<R, KeySize> {
type IvSize = U8;
}
impl<R: Unsigned, KeySize> BlockSizeUser for SalsaCore<R, KeySize> {
type BlockSize = U64;
}
impl<R: Unsigned> KeyIvInit for SalsaCore<R, U16> {
/// Create a new Salsa core using a _weaker_ 16-byte key.
///
/// # ⚠️ Security warning
///
/// Using Salsa20 with keys shorter than 32 bytes is
/// [**explicitly discouraged** by its creator][0]. It is included for
/// compatibility with systems that use these weaker keys.
///
/// [0]: https://cr.yp.to/snuffle/keysizes.pdf
fn new(key: &Key<U16>, iv: &Nonce) -> Self {
let mut state = [0u32; STATE_WORDS];
state[0] = CONSTANTS_16[0];
for (i, chunk) in key.chunks(4).enumerate() {
state[1 + i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
state[5] = CONSTANTS_16[1];
for (i, chunk) in iv.chunks(4).enumerate() {
state[6 + i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
state[8] = 0;
state[9] = 0;
state[10] = CONSTANTS_16[2];
for (i, chunk) in key.chunks(4).enumerate() {
state[11 + i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
state[15] = CONSTANTS_16[3];
Self {
state,
rounds: PhantomData,
key_size: PhantomData,
}
}
}
impl<R: Unsigned> KeyIvInit for SalsaCore<R, U32> {
/// Create a new Salsa core using a 32-byte key.
fn new(key: &Key<U32>, iv: &Nonce) -> Self {
let mut state = [0u32; STATE_WORDS];
state[0] = CONSTANTS_32[0];
for (i, chunk) in key[..16].chunks(4).enumerate() {
state[1 + i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
state[5] = CONSTANTS_32[1];
for (i, chunk) in iv.chunks(4).enumerate() {
state[6 + i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
state[8] = 0;
state[9] = 0;
state[10] = CONSTANTS_32[2];
for (i, chunk) in key[16..].chunks(4).enumerate() {
state[11 + i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
state[15] = CONSTANTS_32[3];
Self {
state,
rounds: PhantomData,
key_size: PhantomData,
}
}
}
impl<R: Unsigned, KeySize> StreamCipherCore for SalsaCore<R, KeySize> {
#[inline(always)]
fn remaining_blocks(&self) -> Option<usize> {
let rem = u64::MAX - self.get_block_pos();
rem.try_into().ok()
}
fn process_with_backend(&mut self, f: impl StreamCipherClosure<BlockSize = Self::BlockSize>) {
f.call(&mut backends::soft::Backend(self));
}
}
impl<R: Unsigned, KeySize> StreamCipherSeekCore for SalsaCore<R, KeySize> {
type Counter = u64;
#[inline(always)]
fn get_block_pos(&self) -> u64 {
(self.state[8] as u64) + ((self.state[9] as u64) << 32)
}
#[inline(always)]
fn set_block_pos(&mut self, pos: u64) {
self.state[8] = (pos & 0xffff_ffff) as u32;
self.state[9] = ((pos >> 32) & 0xffff_ffff) as u32;
}
}
#[cfg(feature = "zeroize")]
impl<R: Unsigned, KeySize> Drop for SalsaCore<R, KeySize> {
fn drop(&mut self) {
self.state.zeroize();
}
}
#[cfg(feature = "zeroize")]
impl<R: Unsigned, KeySize> ZeroizeOnDrop for SalsaCore<R, KeySize> {}