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
#![no_std]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms, trivial_casts, unused_qualifications)]
pub use stream_cipher;
mod block;
mod cipher;
mod rounds;
#[cfg(feature = "xsalsa20")]
mod xsalsa20;
#[cfg(feature = "xsalsa20")]
pub use self::xsalsa20::{XNonce, XSalsa20};
#[cfg(feature = "hsalsa20")]
pub use self::xsalsa20::hsalsa20;
use crate::{
block::Block,
cipher::Cipher,
rounds::{Rounds, R12, R20, R8},
};
use core::convert::TryInto;
use stream_cipher::{
consts::{U32, U8},
LoopError, NewStreamCipher, OverflowError, SeekNum, SyncStreamCipher, SyncStreamCipherSeek,
};
pub const BLOCK_SIZE: usize = 64;
pub const KEY_SIZE: usize = 32;
const IV_SIZE: usize = 8;
const STATE_WORDS: usize = 16;
const CONSTANTS: [u32; 4] = [0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574];
pub type Salsa8 = Salsa<R8>;
pub type Salsa12 = Salsa<R12>;
pub type Salsa20 = Salsa<R20>;
pub type Key = stream_cipher::Key<Salsa20>;
pub type Nonce = stream_cipher::Nonce<Salsa20>;
#[derive(Debug)]
pub struct Salsa<R: Rounds>(Cipher<R>);
impl<R: Rounds> NewStreamCipher for Salsa<R> {
type KeySize = U32;
type NonceSize = U8;
fn new(key: &Key, nonce: &Nonce) -> Self {
let block = Block::new(key.as_slice().try_into().unwrap(), (*nonce).into());
Salsa(Cipher::new(block))
}
}
impl<R: Rounds> SyncStreamCipherSeek for Salsa<R> {
fn try_current_pos<T: SeekNum>(&self) -> Result<T, OverflowError> {
self.0.try_current_pos()
}
fn try_seek<T: SeekNum>(&mut self, pos: T) -> Result<(), LoopError> {
self.0.try_seek(pos)
}
}
impl<R: Rounds> SyncStreamCipher for Salsa<R> {
fn try_apply_keystream(&mut self, data: &mut [u8]) -> Result<(), LoopError> {
self.0.try_apply_keystream(data)
}
}