themis 0.14.0

High-level cryptographic services for storage and messaging
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// Copyright 2018 (c) rust-themis developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Secure Message system.
//!
//! **Secure Message** provides a sequence-independent, stateless, contextless messaging system.
//! This may be preferred in cases that do not require frequent sequential message exchange and/or
//! in low-bandwidth contexts. It is secure enough to exchange messages from time to time, but if
//! you would like to have Perfect Forward Secrecy and higher security guarantees, please consider
//! using [Secure Session] instead.
//!
//! Secure Message offers two modes of operation:
//!
//!   - In **[Sign]/[Verify]** mode the message is signed using the private key
//!     of the sender and is verified by the receiver using the public key of
//!     the sender. The message is packed in a suitable container and ECDSA is
//!     used by default to sign the message (when RSA key is used, RSA+PSS+PKCS#7
//!     digital signature is used).
//!
//!   - In **[Encrypt/Decrypt]** mode the message will be encrypted with a randomly
//!     generated key (in RSA) or a key derived by ECDH (in ECDSA), via symmetric
//!     algorithm with Secure Cell in seal mode (keys are 256 bits long).
//!
//! [Here you can read more][docs] about cryptographic internals of Secure Messages.
//!
//! [Secure Session]: ../secure_session/index.html
//! [Sign]: struct.SecureSign.html
//! [Verify]: struct.SecureVerify.html
//! [Encrypt/Decrypt]: struct.SecureMessage.html
//! [docs]: https://docs.cossacklabs.com/themis/crypto-theory/cryptosystems/secure-message/
//!
//! # Examples
//!
//! Basic operation of Secure Message looks like this:
//!
//! ```
//! # fn main() -> Result<(), themis::Error> {
//! use themis::secure_message::SecureMessage;
//! use themis::keygen::gen_ec_key_pair;
//!
//! let key_pair = gen_ec_key_pair();
//!
//! let secure = SecureMessage::new(key_pair);
//!
//! let encrypted = secure.encrypt(b"message")?;
//! let decrypted = secure.decrypt(&encrypted)?;
//! assert_eq!(decrypted, b"message");
//! # Ok(())
//! # }
//! ```
//!
//! You can find more examples for each operation mode in their respective documentation.

use std::ptr;

use bindings::{
    themis_secure_message_decrypt, themis_secure_message_encrypt, themis_secure_message_sign,
    themis_secure_message_verify,
};

use crate::error::{Error, ErrorKind, Result};
use crate::keys::{KeyPair, PrivateKey, PublicKey};
use crate::utils::into_raw_parts;

/// Secure Message encryption and decryption.
///
/// **Encrypted message** is useful when you need the full stack of protection for your data —
/// in most cases you will be using this flavor. Encrypted messages currently use Secure Cell
/// in sealing mode for data protection.
///
/// # Examples
///
/// In order to use Secure Message in encrypting mode you will need to have both public and
/// private keys available on both peers. Typical usage of Secure Message looks like this:
///
/// ```
/// # fn main() -> Result<(), themis::Error> {
/// use themis::secure_message::SecureMessage;
/// use themis::keygen::gen_ec_key_pair;
///
/// // Generate and share this key pair between peers.
/// let key_pair = gen_ec_key_pair();
///
/// // Alice uses her own Secure Message instance to encrypt messages.
/// let secure_a = SecureMessage::new(key_pair.clone());
/// let encrypted = secure_a.encrypt(b"message")?;
///
/// // Bob uses his Secure Message instance to decrypt received messages.
/// let secure_b = SecureMessage::new(key_pair.clone());
/// let decrypted = secure_b.decrypt(&encrypted)?;
///
/// assert_eq!(decrypted, b"message");
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct SecureMessage {
    key_pair: KeyPair,
}

impl SecureMessage {
    /// Makes a new Secure Message using given key pair.
    ///
    /// Both ECDSA and RSA key pairs are supported.
    pub fn new(key_pair: impl Into<KeyPair>) -> Self {
        Self {
            key_pair: key_pair.into(),
        }
    }

    /// Encrypts the provided message into a secure container.
    ///
    /// # Examples
    ///
    /// You can use anything convertible into a byte slice as a message: a byte slice or an array,
    /// a `Vec<u8>`, or a `String`.
    ///
    /// ```
    /// # fn main() -> Result<(), themis::Error> {
    /// use themis::secure_message::SecureMessage;
    /// use themis::keygen::gen_ec_key_pair;
    ///
    /// let secure = SecureMessage::new(gen_ec_key_pair());
    ///
    /// secure.encrypt(b"byte string")?;
    /// secure.encrypt(&[1, 2, 3, 4, 5])?;
    /// secure.encrypt(vec![6, 7, 8, 9])?;
    /// secure.encrypt(format!("owned string"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn encrypt(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (private_key_ptr, private_key_len) = into_raw_parts(self.key_pair.private_key_bytes());
        let (public_key_ptr, public_key_len) = into_raw_parts(self.key_pair.public_key_bytes());
        let (message_ptr, message_len) = into_raw_parts(message.as_ref());

        let mut encrypted = Vec::new();
        let mut encrypted_len = 0;

        unsafe {
            let status = themis_secure_message_encrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                message_ptr,
                message_len,
                ptr::null_mut(),
                &mut encrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        encrypted.reserve(encrypted_len);

        unsafe {
            let status = themis_secure_message_encrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                message_ptr,
                message_len,
                encrypted.as_mut_ptr(),
                &mut encrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(encrypted_len <= encrypted.capacity());
            encrypted.set_len(encrypted_len as usize);
        }

        Ok(encrypted)
    }

    /// Decrypts an encrypted message back into its original form.
    pub fn decrypt(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (private_key_ptr, private_key_len) = into_raw_parts(self.key_pair.private_key_bytes());
        let (public_key_ptr, public_key_len) = into_raw_parts(self.key_pair.public_key_bytes());
        let (wrapped_ptr, wrapped_len) = into_raw_parts(message.as_ref());

        let mut decrypted = Vec::new();
        let mut decrypted_len = 0;

        unsafe {
            let status = themis_secure_message_decrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                wrapped_ptr,
                wrapped_len,
                ptr::null_mut(),
                &mut decrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        decrypted.reserve(decrypted_len);

        unsafe {
            let status = themis_secure_message_decrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                wrapped_ptr,
                wrapped_len,
                decrypted.as_mut_ptr(),
                &mut decrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(decrypted_len <= decrypted.capacity());
            decrypted.set_len(decrypted_len as usize);
        }

        Ok(decrypted)
    }
}

/// Secure Message signing.
///
/// **Signed message** is useful for cases where you don’t need data confidentiality. It allows
/// the receiver to verify the origin and integrity of the data while still allowing intermediate
/// nodes to process it accordingly (for example, route data based on its type).
///
/// Signatures can be checked with [`SecureVerify`].
///
/// [`SecureVerify`]: struct.SecureVerify.html
///
/// # Examples
///
/// In order to sign messages you need only the private half of a key pair. It does not need to be
/// shared with your peer for verification.
///
/// ```
/// # fn main() -> Result<(), themis::Error> {
/// use themis::secure_message::SecureSign;
/// use themis::secure_message::SecureVerify;
/// use themis::keygen::gen_rsa_key_pair;
///
/// // Alice generates a key pair and shares `public` half with Bob
/// let (private, public) = gen_rsa_key_pair().split();
///
/// // Alice is able to sign her messages with her private key.
/// let secure_a = SecureSign::new(private);
/// let signed_message = secure_a.sign(b"important message")?;
///
/// // Bob is able to verify that signature on the message matches.
/// let secure_b = SecureVerify::new(public);
/// let received_message = secure_b.verify(&signed_message)?;
/// assert_eq!(received_message, b"important message");
/// # Ok(())
/// # }
/// ```
///
/// Note that the signed message is _not encrypted_ and contains the original data as plain text:
///
/// ```
/// # use themis::secure_message::SecureSign;
/// # use themis::secure_message::SecureVerify;
/// # use themis::keygen::gen_rsa_key_pair;
/// #
/// # let (private, _) = gen_rsa_key_pair().split();
/// # let secure = SecureSign::new(private);
/// # let signed_message = secure.sign(b"important message").unwrap();
/// #
/// let message = b"important message";
///
/// assert!(signed_message.windows(message.len()).any(|subslice| subslice == message));
/// ```
#[derive(Debug)]
pub struct SecureSign {
    private_key: PrivateKey,
}

impl SecureSign {
    /// Makes a new Secure Message using given private key.
    ///
    /// Both ECDSA and RSA keys are supported.
    pub fn new(private_key: impl Into<PrivateKey>) -> Self {
        Self {
            private_key: private_key.into(),
        }
    }

    /// Securely signs a message and returns it with signature attached.
    ///
    /// # Examples
    ///
    /// You can use anything convertible into a byte slice as a message: a byte slice or an array,
    /// a `Vec<u8>`, or a `String`.
    ///
    /// ```
    /// # fn main() -> Result<(), themis::Error> {
    /// use themis::secure_message::SecureSign;
    /// use themis::keygen::gen_ec_key_pair;
    ///
    /// let secure = SecureSign::new(gen_ec_key_pair().split().0);
    ///
    /// secure.sign(b"byte string")?;
    /// secure.sign(&[1, 2, 3, 4, 5])?;
    /// secure.sign(vec![6, 7, 8, 9])?;
    /// secure.sign(format!("owned string"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn sign(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (private_key_ptr, private_key_len) = into_raw_parts(self.private_key.as_ref());
        let (message_ptr, message_len) = into_raw_parts(message.as_ref());

        let mut signed = Vec::new();
        let mut signed_len = 0;

        unsafe {
            let status = themis_secure_message_sign(
                private_key_ptr,
                private_key_len,
                message_ptr,
                message_len,
                ptr::null_mut(),
                &mut signed_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        signed.reserve(signed_len);

        unsafe {
            let status = themis_secure_message_sign(
                private_key_ptr,
                private_key_len,
                message_ptr,
                message_len,
                signed.as_mut_ptr(),
                &mut signed_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(signed_len <= signed.capacity());
            signed.set_len(signed_len as usize);
        }

        Ok(signed)
    }
}

// TODO: provide a way to inspect signed messages
//
// It would be nice to be able to get access to plaintext data in messages returned by SecureSign.
// Consider returning something like SignedMessage which is a newtype over Vec<u8> with additional
// utility methods and impls like AsRef<[u8]> and Into<Vec<u8>>.

/// Secure Message verification.
///
/// **Signed message** is useful for cases where you don’t need data confidentiality. It allows
/// the receiver to verify the origin and integrity of the data while still allowing intermediate
/// nodes to process it accordingly (for example, route data based on its type).
///
/// Verifies signatures produced by [`SecureSign`].
///
/// [`SecureSign`]: struct.SecureSign.html
///
/// # Examples
///
/// In order to verify signed messages you need the public half of a key pair corresponding to the
/// private key used by your peer to sign messages.
///
/// ```
/// # fn main() -> Result<(), themis::Error> {
/// use themis::secure_message::SecureSign;
/// use themis::secure_message::SecureVerify;
/// use themis::keygen::gen_ec_key_pair;
///
/// // Alice generates a key pair and shares `public` half with Bob
/// let (private, public) = gen_ec_key_pair().split();
///
/// // Alice is able to sign her messages with her private key.
/// let secure_a = SecureSign::new(private);
/// let signed_message = secure_a.sign(b"important message")?;
///
/// // Bob is able to verify that signature on the message matches.
/// let secure_b = SecureVerify::new(public);
/// let received_message = secure_b.verify(&signed_message)?;
/// assert_eq!(received_message, b"important message");
/// # Ok(())
/// # }
/// ```
///
/// Secure Message guarantees integrity of the message and identity of its author.
///
/// ```
/// # use themis::secure_message::SecureSign;
/// # use themis::secure_message::SecureVerify;
/// # use themis::keygen::gen_ec_key_pair;
/// #
/// # let (private, public) = gen_ec_key_pair().split();
/// # let secure_a = SecureSign::new(private);
/// # let secure_b = SecureVerify::new(public);
/// # let signed_message = secure_a.sign(b"important message").unwrap();
/// #
/// // Let's flip some bits somewhere.
/// let mut corrupted_message = signed_message.clone();
/// corrupted_message[20] = !corrupted_message[20];
///
/// // Bob is able to see that the message has been tampered.
/// assert!(secure_b.verify(&corrupted_message).is_err());
///
/// // Only Alice's public key verifies the message, any other key won't do.
/// let (_, carol_public_key) = gen_ec_key_pair().split();
/// let secure_c = SecureVerify::new(carol_public_key);
///
/// assert!(secure_c.verify(&signed_message).is_err());
/// ```
#[derive(Debug)]
pub struct SecureVerify {
    public_key: PublicKey,
}

impl SecureVerify {
    /// Makes a new Secure Message using given public key.
    ///
    /// Both ECDSA and RSA keys are supported.
    pub fn new(public_key: impl Into<PublicKey>) -> Self {
        Self {
            public_key: public_key.into(),
        }
    }

    /// Verifies the signature and returns the original message.
    pub fn verify(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (public_key_ptr, public_key_len) = into_raw_parts(self.public_key.as_ref());
        let (signed_ptr, signed_len) = into_raw_parts(message.as_ref());

        let mut original = Vec::new();
        let mut original_len = 0;

        unsafe {
            let status = themis_secure_message_verify(
                public_key_ptr,
                public_key_len,
                signed_ptr,
                signed_len,
                ptr::null_mut(),
                &mut original_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        original.reserve(original_len);

        unsafe {
            let status = themis_secure_message_verify(
                public_key_ptr,
                public_key_len,
                signed_ptr,
                signed_len,
                original.as_mut_ptr(),
                &mut original_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(original_len <= original.capacity());
            original.set_len(original_len as usize);
        }

        Ok(original)
    }
}