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
#![feature(libc, core)]
#![deny(warnings)]
extern crate ocb_sys;
extern crate libc;
use std::{result, mem, fmt, ptr, simd};
use std::intrinsics::volatile_set_memory;
use ocb_sys::{AE_SUCCESS, AE_INVALID, AE_NOT_SUPPORTED};
use ocb_sys::{AE_FINALIZE, AE_CTX_SIZEOF};
use ocb_sys::{OCB_KEY_LEN, OCB_TAG_LEN};
use ocb_sys::{ae_ctx, ae_ctx_sizeof, ae_clear, ae_init, ae_encrypt, ae_decrypt};
use libc::c_int;
pub const KEY_LEN: usize = OCB_KEY_LEN as usize;
pub const TAG_LEN: usize = OCB_TAG_LEN as usize;
pub const NONCE_LEN: usize = 12;
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Error {
InvalidTag,
NotSupported,
NonceNotAvailable,
Other(c_int),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
<Self as fmt::Debug>::fmt(self, f)
}
}
pub type Result<T> = result::Result<T, Error>;
fn check(x: c_int) -> Result<c_int> {
match x {
AE_INVALID => Err(Error::InvalidTag),
AE_NOT_SUPPORTED => Err(Error::NotSupported),
x if x < 0 => Err(Error::Other(x)),
x => Ok(x),
}
}
pub struct Context {
_align: [simd::u32x4; 0],
ctx: [u8; AE_CTX_SIZEOF],
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
check(ae_clear(self.ctx())).unwrap();
}
}
}
macro_rules! clear_on_drop {
($t:ty) => {
impl Drop for $t {
fn drop(&mut self) {
let buf = &mut self.0;
unsafe {
volatile_set_memory(buf.as_mut_ptr(), 0, buf.len());
}
}
}
}
}
#[derive(Clone)]
pub struct Key(pub [u8; KEY_LEN]);
clear_on_drop!(Key);
#[allow(missing_copy_implementations)]
#[derive(Clone, Debug)]
pub struct Nonce(pub [u8; NONCE_LEN]);
#[allow(missing_copy_implementations)]
pub struct Counter([u8; NONCE_LEN]);
impl Counter {
pub fn new(n: Nonce) -> Counter {
Counter(n.0)
}
}
impl Iterator for Counter {
type Item = Nonce;
fn next(&mut self) -> Option<Nonce> {
let v = self.0;
for i in 0..NONCE_LEN {
self.0[i] = self.0[i].wrapping_add(1);
if self.0[i] != 0 {
break;
}
}
Some(Nonce(v))
}
}
impl Context {
fn ctx(&mut self) -> *mut ae_ctx {
self.ctx.as_mut_ptr() as *mut ae_ctx
}
pub fn new(key: Key) -> Result<Context> {
unsafe {
assert_eq!(AE_CTX_SIZEOF, ae_ctx_sizeof() as usize);
let mut ctx = Context {
_align: [mem::uninitialized(); 0],
ctx: mem::uninitialized(),
};
let n = try!(check(ae_init(ctx.ctx(), key.0.as_ptr(),
OCB_KEY_LEN, NONCE_LEN as c_int, OCB_TAG_LEN)));
assert_eq!(n, AE_SUCCESS);
Ok(ctx)
}
}
pub fn encrypt<N>(&mut self,
nonce_stream: &mut N,
plaintext: &[u8],
assoc_data: &[u8]) -> Result<(Nonce, Vec<u8>)>
where N: Iterator<Item=Nonce>
{
let nonce = match nonce_stream.next() {
Some(n) => n,
None => return Err(Error::NonceNotAvailable),
};
let ct_len = plaintext.len() + TAG_LEN;
let mut ct: Vec<u8> = Vec::with_capacity(ct_len);
unsafe {
let n = try!(check(ae_encrypt(self.ctx(), nonce.0.as_ptr(),
plaintext.as_ptr(), plaintext.len() as c_int,
assoc_data.as_ptr(), assoc_data.len() as c_int,
ct.as_mut_ptr(), ptr::null_mut(), AE_FINALIZE)));
assert_eq!(ct_len, n as usize);
ct.set_len(ct_len);
Ok((nonce, ct))
}
}
pub fn decrypt(&mut self,
nonce: Nonce,
ciphertext: &[u8],
assoc_data: &[u8]) -> Result<Vec<u8>> {
assert!(ciphertext.len() >= TAG_LEN);
let pt_len = ciphertext.len() - TAG_LEN;
let mut pt: Vec<u8> = Vec::with_capacity(pt_len);
unsafe {
let n = try!(check(ae_decrypt(self.ctx(), nonce.0.as_ptr(),
ciphertext.as_ptr(), ciphertext.len() as c_int,
assoc_data.as_ptr(), assoc_data.len() as c_int,
pt.as_mut_ptr(), ptr::null_mut(), AE_FINALIZE)));
assert_eq!(pt_len, n as usize);
pt.set_len(pt_len);
Ok(pt)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn counter() {
let mut n = Counter::new(Nonce([0; NONCE_LEN]));
assert_eq!(n.next().unwrap().0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(n.next().unwrap().0, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(n.next().unwrap().0, [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
n.0[0] = 0xFE;
assert_eq!(n.next().unwrap().0, [0xFE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(n.next().unwrap().0, [0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(n.next().unwrap().0, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
let mut n = Counter::new(Nonce([0xFF; NONCE_LEN]));
n.0[0] = 0xFE;
assert_eq!(n.next().unwrap().0, [0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
assert_eq!(n.next().unwrap().0, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
assert_eq!(n.next().unwrap().0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(n.next().unwrap().0, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn smoke_test() {
let mut ctx = Context::new(Key([0; KEY_LEN])).unwrap();
let mut counter = Counter::new(Nonce([0; NONCE_LEN]));
let msg = "Hello, world!".as_bytes();
let assoc = "rust rulez".as_bytes();
let (nonce, mut ct) = ctx.encrypt(&mut counter, msg, assoc).unwrap();
assert_eq!(nonce.0, [0; NONCE_LEN]);
let pt = ctx.decrypt(nonce.clone(), &ct, assoc).unwrap();
assert_eq!(&*pt, msg);
assert_eq!(ctx.decrypt(nonce.clone(), &ct, "bogus".as_bytes()),
Err(Error::InvalidTag));
ct[0] ^= 0x01;
assert_eq!(ctx.decrypt(nonce.clone(), &ct, assoc),
Err(Error::InvalidTag));
ct[0] ^= 0x01;
assert!(ctx.decrypt(nonce.clone(), &ct, assoc).is_ok());
let mut ctx2 = Context::new(Key([5; KEY_LEN])).unwrap();
assert_eq!(ctx2.decrypt(nonce, &ct, assoc),
Err(Error::InvalidTag));
}
}