crypto_secretbox-0.1.1/.cargo_vcs_info.json0000644000000001560000000000100144330ustar { "git": { "sha1": "0324a1ed7ef3fdf5d53f35b6cae6f7ff2429e27a" }, "path_in_vcs": "crypto_secretbox" }crypto_secretbox-0.1.1/CHANGELOG.md000064400000000000000000000006371046102023000150400ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 0.1.1 (2023-05-15) ### Added - Re-export `cipher` ([#113]) [#113]: https://github.com/RustCrypto/nacl-compat/pull/113 ## 0.1.0 (2023-05-15) - Initial release crypto_secretbox-0.1.1/Cargo.toml0000644000000040310000000000100124250ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.60" name = "crypto_secretbox" version = "0.1.1" authors = ["RustCrypto Developers"] description = """ Pure Rust implementation of the XSalsa20Poly1305 (a.k.a. NaCl crypto_secretbox) authenticated encryption cipher as well as the libsodium variant of XChaCha20Poly1305 """ documentation = "https://docs.rs/crypto_secretbox" readme = "README.md" keywords = [ "aead", "nacl", "poly1305", "salsa20", "xsalsa20", ] categories = [ "cryptography", "no-std", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/nacl-compat/tree/master/crypto_secretbox" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.aead] version = "0.5" default-features = false [dependencies.chacha20] version = "0.9" features = ["zeroize"] optional = true [dependencies.cipher] version = "0.4" default-features = false [dependencies.generic-array] version = "0.14.7" features = ["zeroize"] default-features = false [dependencies.poly1305] version = "0.8" [dependencies.salsa20] version = "0.10" features = ["zeroize"] optional = true [dependencies.subtle] version = "2" default-features = false [dependencies.zeroize] version = "1" default-features = false [dev-dependencies.hex-literal] version = "0.4" [features] alloc = ["aead/alloc"] default = [ "alloc", "getrandom", "salsa20", ] getrandom = [ "aead/getrandom", "rand_core", ] heapless = ["aead/heapless"] rand_core = ["aead/rand_core"] std = [ "aead/std", "alloc", ] stream = ["aead/stream"] crypto_secretbox-0.1.1/Cargo.toml.orig000064400000000000000000000027031046102023000161120ustar 00000000000000[package] name = "crypto_secretbox" version = "0.1.1" description = """ Pure Rust implementation of the XSalsa20Poly1305 (a.k.a. NaCl crypto_secretbox) authenticated encryption cipher as well as the libsodium variant of XChaCha20Poly1305 """ authors = ["RustCrypto Developers"] edition = "2021" license = "Apache-2.0 OR MIT" readme = "README.md" documentation = "https://docs.rs/crypto_secretbox" repository = "https://github.com/RustCrypto/nacl-compat/tree/master/crypto_secretbox" keywords = ["aead", "nacl", "poly1305", "salsa20", "xsalsa20"] categories = ["cryptography", "no-std"] rust-version = "1.60" [dependencies] aead = { version = "0.5", default-features = false } cipher = { version = "0.4", default-features = false } generic-array = { version = "0.14.7", default-features = false, features = ["zeroize"] } poly1305 = "0.8" subtle = { version = "2", default-features = false } zeroize = { version = "1", default-features = false } # optional dependencies chacha20 = { version = "0.9", optional = true, features = ["zeroize"] } salsa20 = { version = "0.10", optional = true, features = ["zeroize"] } [dev-dependencies] hex-literal = "0.4" [features] default = ["alloc", "getrandom", "salsa20"] alloc = ["aead/alloc"] std = ["aead/std", "alloc"] getrandom = ["aead/getrandom", "rand_core"] heapless = ["aead/heapless"] rand_core = ["aead/rand_core"] stream = ["aead/stream"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] crypto_secretbox-0.1.1/LICENSE-APACHE000064400000000000000000000251411046102023000151500ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. crypto_secretbox-0.1.1/LICENSE-MIT000064400000000000000000000020721046102023000146560ustar 00000000000000Copyright (c) 2019-2023 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. crypto_secretbox-0.1.1/README.md000064400000000000000000000053701046102023000145050ustar 00000000000000# RustCrypto: `crypto_secretbox` [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [![Project Chat][chat-image]][chat-link] [![Build Status][build-image]][build-link] [`crypto_secretbox`][1] is an [authenticated symmetric encryption][2] cipher amenable to fast, constant-time implementations in software, combining either the [Salsa20][3] stream cipher (with [XSalsa20][4] 192-bit nonce extension) or [ChaCha20][5] stream cipher with the [Poly1305][6] universal hash function, which acts as a message authentication code. This algorithm has largely been replaced by the newer IETF variant of [ChaCha20Poly1305][7] (and the associated [XChaCha20Poly1305][8]) AEAD ciphers ([RFC 8439][9]), but is useful for interoperability with legacy NaCl-based protocols. [Documentation][docs-link] ## Security Warning No security audits of this crate have ever been performed, and it has not been thoroughly assessed to ensure its operation is constant-time on common CPU architectures. USE AT YOUR OWN RISK! ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [//]: # (badges) [crate-image]: https://buildstats.info/crate/crypto_secretbox [crate-link]: https://crates.io/crates/crypto_secretbox [docs-image]: https://docs.rs/crypto_secretbox/badge.svg [docs-link]: https://docs.rs/crypto_secretbox/ [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.60+-blue.svg [chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg [chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs [build-image]: https://github.com/RustCrypto/nacl-compat/actions/workflows/crypto_secretbox.yml/badge.svg [build-link]: https://github.com/RustCrypto/nacl-compat/actions/workflows/crypto_secretbox.yml [//]: # (general links) [1]: https://nacl.cr.yp.to/secretbox.html [2]: https://en.wikipedia.org/wiki/Authenticated_encryption [3]: https://github.com/RustCrypto/stream-ciphers/tree/master/salsa20 [4]: https://cr.yp.to/snuffle/xsalsa-20081128.pdf [5]: https://cr.yp.to/chacha.html [6]: https://github.com/RustCrypto/universal-hashes/tree/master/poly1305 [7]: https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305 [8]: https://docs.rs/chacha20poly1305/latest/chacha20poly1305/struct.XChaCha20Poly1305.html [9]: https://tools.ietf.org/html/rfc8439 crypto_secretbox-0.1.1/src/lib.rs000064400000000000000000000265711046102023000151370ustar 00000000000000#![no_std] #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![doc = include_str!("../README.md")] #![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" )] #![forbid(unsafe_code)] #![warn(missing_docs, rust_2018_idioms)] //! # Usage //! #![cfg_attr(all(feature = "getrandom", feature = "std"), doc = "```")] #![cfg_attr(not(all(feature = "getrandom", feature = "std")), doc = "```ignore")] //! # fn main() -> Result<(), Box> { //! use crypto_secretbox::{ //! aead::{Aead, AeadCore, KeyInit, OsRng}, //! XSalsa20Poly1305, Nonce //! }; //! //! let key = XSalsa20Poly1305::generate_key(&mut OsRng); //! let cipher = XSalsa20Poly1305::new(&key); //! let nonce = XSalsa20Poly1305::generate_nonce(&mut OsRng); // unique per message //! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?; //! let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?; //! assert_eq!(&plaintext, b"plaintext message"); //! # Ok(()) //! # } //! ``` //! //! ## In-place Usage (eliminates `alloc` requirement) //! //! This crate has an optional `alloc` feature which can be disabled in e.g. //! microcontroller environments that don't have a heap. //! //! The [`AeadInPlace::encrypt_in_place`] and [`AeadInPlace::decrypt_in_place`] //! methods accept any type that impls the [`aead::Buffer`] trait which //! contains the plaintext for encryption or ciphertext for decryption. //! //! Note that if you enable the `heapless` feature of this crate, //! you will receive an impl of [`aead::Buffer`] for `heapless::Vec` //! (re-exported from the `aead` crate as [`aead::heapless::Vec`]), //! which can then be passed as the `buffer` parameter to the in-place encrypt //! and decrypt methods: //! #![cfg_attr( all(feature = "getrandom", feature = "heapless", feature = "std"), doc = "```" )] #![cfg_attr( not(all(feature = "getrandom", feature = "heapless", feature = "std")), doc = "```ignore" )] //! # fn main() -> Result<(), Box> { //! use crypto_secretbox::{ //! aead::{AeadCore, AeadInPlace, KeyInit, OsRng, heapless::Vec}, //! XSalsa20Poly1305, Nonce, //! }; //! //! let key = XSalsa20Poly1305::generate_key(&mut OsRng); //! let cipher = XSalsa20Poly1305::new(&key); //! let nonce = XSalsa20Poly1305::generate_nonce(&mut OsRng); // unique per message //! //! let mut buffer: Vec = Vec::new(); // Note: buffer needs 16-bytes overhead for auth tag //! buffer.extend_from_slice(b"plaintext message"); //! //! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext //! cipher.encrypt_in_place(&nonce, b"", &mut buffer)?; //! //! // `buffer` now contains the message ciphertext //! assert_ne!(&buffer, b"plaintext message"); //! //! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext //! cipher.decrypt_in_place(&nonce, b"", &mut buffer)?; //! assert_eq!(&buffer, b"plaintext message"); //! # Ok(()) //! # } //! ``` //! //! ``` //! # #[cfg(feature = "heapless")] //! # { //! use crypto_secretbox::XSalsa20Poly1305; //! use crypto_secretbox::aead::{AeadCore, AeadInPlace, KeyInit, generic_array::GenericArray}; //! use crypto_secretbox::aead::heapless::Vec; //! //! let key = GenericArray::from_slice(b"an example very very secret key."); //! let cipher = XSalsa20Poly1305::new(key); //! //! let nonce = GenericArray::from_slice(b"extra long unique nonce!"); // 24-bytes; unique //! //! let mut buffer: Vec = Vec::new(); //! buffer.extend_from_slice(b"plaintext message"); //! //! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext //! cipher.encrypt_in_place(nonce, b"", &mut buffer).expect("encryption failure!"); //! //! // `buffer` now contains the message ciphertext //! assert_ne!(&buffer, b"plaintext message"); //! //! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext //! cipher.decrypt_in_place(nonce, b"", &mut buffer).expect("decryption failure!"); //! assert_eq!(&buffer, b"plaintext message"); //! # } //! ``` //! //! [1]: https://nacl.cr.yp.to/secretbox.html //! [2]: https://en.wikipedia.org/wiki/Authenticated_encryption //! [3]: https://docs.rs/salsa20 //! [4]: http://docs.rs/chacha20poly1305 //! [5]: https://docs.rs/chacha20poly1305/latest/chacha20poly1305/struct.XChaCha20Poly1305.html //! [6]: https://tools.ietf.org/html/rfc8439 pub use aead::{self, consts, AeadCore, AeadInPlace, Error, KeyInit, KeySizeUser}; pub use cipher; use aead::{ consts::{U0, U16, U24, U32, U8}, generic_array::GenericArray, Buffer, }; use cipher::{IvSizeUser, KeyIvInit, StreamCipher}; use core::marker::PhantomData; use poly1305::Poly1305; use zeroize::{Zeroize, Zeroizing}; #[cfg(feature = "chacha20")] use chacha20::{hchacha, ChaCha20Legacy as ChaCha20}; #[cfg(feature = "salsa20")] use salsa20::{hsalsa, Salsa20}; #[cfg(any(feature = "chacha20", feature = "salsa20"))] use cipher::consts::U10; /// Key type. pub type Key = GenericArray; /// Nonce type. pub type Nonce = GenericArray; /// Poly1305 tag. pub type Tag = GenericArray; /// `crypto_secretbox` instantiated with the XChaCha20 stream cipher. /// /// NOTE: this is a legacy construction which is missing modern features like /// additional associated data. /// /// We do not recommend using it in greenfield applications, and instead only /// using it for interop with legacy applications which require use of the /// `crypto_secretbox` construction instantiated with XChaCha20. /// /// For new applications, we recommend using the `AEAD_XChaCha20_Poly1305` /// construction as described in [`draft-irtf-cfrg-xchacha`]. An implementation /// of this IETF flavor of XChaCha20Poly1305 can be found in /// [`chacha20poly1305::XChaCha20Poly1305`]. /// /// [`draft-irtf-cfrg-xchacha`]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha /// [`chacha20poly1305::XChaCha20Poly1305`]: https://docs.rs/chacha20poly1305/latest/chacha20poly1305/type.XChaCha20Poly1305.html #[cfg(feature = "chacha20")] pub type XChaCha20Poly1305 = SecretBox; /// `crypto_secretbox` instantiated with the XSalsa20 stream cipher. #[cfg(feature = "salsa20")] pub type XSalsa20Poly1305 = SecretBox; /// The NaCl `crypto_secretbox` authenticated symmetric encryption primitive, /// generic pub struct SecretBox { /// Secret key. key: Key, /// Cipher. cipher: PhantomData, } impl SecretBox { /// Size of an XSalsa20Poly1305 key in bytes pub const KEY_SIZE: usize = 32; /// Size of an XSalsa20Poly1305 nonce in bytes pub const NONCE_SIZE: usize = 24; /// Size of a Poly1305 tag in bytes pub const TAG_SIZE: usize = 16; } impl SecretBox where C: Kdf + KeyIvInit + KeySizeUser + IvSizeUser + StreamCipher, { /// Initialize cipher instance and Poly1305 MAC. fn init_cipher_and_mac(&self, nonce: &Nonce) -> (C, Poly1305) { let (nonce_prefix, nonce_suffix) = nonce.split_at(16); let subkey = Zeroizing::new(C::kdf(&self.key, nonce_prefix.as_ref().into())); let mut cipher = C::new(&subkey, nonce_suffix.as_ref().into()); // Derive Poly1305 key from the first 32-bytes of the keystream. let mut mac_key = Zeroizing::new(poly1305::Key::default()); cipher.apply_keystream(&mut mac_key); let mac = Poly1305::new(&mac_key); (cipher, mac) } } // Handwritten instead of derived to avoid `C: Clone` bound impl Clone for SecretBox { fn clone(&self) -> Self { Self { key: self.key, cipher: PhantomData, } } } impl KeySizeUser for SecretBox { type KeySize = U32; } impl KeyInit for SecretBox { fn new(key: &Key) -> Self { SecretBox { key: *key, cipher: PhantomData, } } } impl AeadCore for SecretBox { type NonceSize = U24; type TagSize = U16; type CiphertextOverhead = U0; } impl AeadInPlace for SecretBox where C: Kdf + KeyIvInit + KeySizeUser + IvSizeUser + StreamCipher, { fn encrypt_in_place( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<(), Error> { let pt_len = buffer.len(); // Make room in the buffer for the tag. It needs to be prepended. buffer.extend_from_slice(Tag::default().as_slice())?; // TODO(tarcieri): add offset param to `encrypt_in_place_detached` buffer.as_mut().copy_within(..pt_len, Self::TAG_SIZE); let tag = self.encrypt_in_place_detached( nonce, associated_data, &mut buffer.as_mut()[Self::TAG_SIZE..], )?; buffer.as_mut()[..Self::TAG_SIZE].copy_from_slice(tag.as_slice()); Ok(()) } fn encrypt_in_place_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], ) -> Result { // AAD unsupported if !associated_data.is_empty() { return Err(Error); } let (mut cipher, mac) = self.init_cipher_and_mac(nonce); cipher.apply_keystream(buffer); Ok(mac.compute_unpadded(buffer)) } fn decrypt_in_place( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<(), Error> { if buffer.len() < Self::TAG_SIZE { return Err(Error); } let tag = Tag::clone_from_slice(&buffer.as_ref()[..Self::TAG_SIZE]); self.decrypt_in_place_detached( nonce, associated_data, &mut buffer.as_mut()[Self::TAG_SIZE..], &tag, )?; let pt_len = buffer.len() - Self::TAG_SIZE; // TODO(tarcieri): add offset param to `encrypt_in_place_detached` buffer.as_mut().copy_within(Self::TAG_SIZE.., 0); buffer.truncate(pt_len); Ok(()) } fn decrypt_in_place_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], tag: &Tag, ) -> Result<(), Error> { // AAD unsupported if !associated_data.is_empty() { return Err(Error); } let (mut cipher, mac) = self.init_cipher_and_mac(nonce); let expected_tag = mac.compute_unpadded(buffer); // This performs a constant-time comparison using the `subtle` crate use subtle::ConstantTimeEq; if expected_tag.ct_eq(tag).into() { cipher.apply_keystream(buffer); Ok(()) } else { Err(Error) } } } impl Drop for SecretBox { fn drop(&mut self) { self.key.as_mut_slice().zeroize(); } } /// Key derivation function: trait for abstracting over HSalsa20 and HChaCha20. pub trait Kdf { /// Derive a new key from the provided input key and nonce. fn kdf(key: &Key, nonce: &GenericArray) -> Key; } impl Kdf for SecretBox where C: Kdf, { fn kdf(key: &Key, nonce: &GenericArray) -> Key { C::kdf(key, nonce) } } #[cfg(feature = "chacha20")] impl Kdf for ChaCha20 { fn kdf(key: &Key, nonce: &GenericArray) -> Key { hchacha::(key, nonce) } } #[cfg(feature = "salsa20")] impl Kdf for Salsa20 { fn kdf(key: &Key, nonce: &GenericArray) -> Key { hsalsa::(key, nonce) } } crypto_secretbox-0.1.1/tests/lib.rs000064400000000000000000000064311046102023000155030ustar 00000000000000//! Integration tests. //! //! XChaCha20Poly1305 test vectors generated using `test-vector-gen` which uses //! a libsodium reference. //! //! XSalsa20Poly1305 test vectors adapted from NaCl's `tests/secretbox.c` and //! `tests/secretbox.out`. #![cfg(any(feature = "chacha20", feature = "salsa20"))] use hex_literal::hex; const KEY: &[u8; 32] = &hex!("1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389"); const NONCE: &[u8; 24] = &hex!("69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37"); const PLAINTEXT: &[u8] = &hex!( "be075fc53c81f2d5cf141316ebeb0c7b5228c52a4c62cbd44b66849b64244ffce5ecbaaf33bd751a" "1ac728d45e6c61296cdc3c01233561f41db66cce314adb310e3be8250c46f06dceea3a7fa1348057" "e2f6556ad6b1318a024a838f21af1fde048977eb48f59ffd4924ca1c60902e52f0a089bc76897040" "e082f937763848645e0705" ); macro_rules! impl_tests { ($cipher:path, $ciphertext:expr) => { #[test] fn encrypt() { let key = GenericArray::from_slice(KEY); let nonce = GenericArray::from_slice(NONCE); let cipher = <$cipher>::new(key); let ciphertext = cipher.encrypt(nonce, PLAINTEXT).unwrap(); assert_eq!($ciphertext, ciphertext.as_slice()); } #[test] fn decrypt() { let key = GenericArray::from_slice(KEY); let nonce = GenericArray::from_slice(NONCE); let cipher = <$cipher>::new(key); let plaintext = cipher.decrypt(nonce, $ciphertext).unwrap(); assert_eq!(PLAINTEXT, plaintext.as_slice()); } #[test] fn decrypt_modified() { let key = GenericArray::from_slice(KEY); let nonce = GenericArray::from_slice(NONCE); let mut ciphertext = Vec::from($ciphertext); // Tweak the first byte ciphertext[0] ^= 0xaa; let cipher = <$cipher>::new(key); assert!(cipher.decrypt(nonce, ciphertext.as_slice()).is_err()); } }; } #[cfg(feature = "chacha20")] mod xchacha20poly1305 { use super::{KEY, NONCE, PLAINTEXT}; use crypto_secretbox::{ aead::{generic_array::GenericArray, Aead, KeyInit}, XChaCha20Poly1305, }; use hex_literal::hex; const CIPHERTEXT: &[u8] = &hex!( "0c61fcffbc3fc8d3aa7464b91ab35374bf8af3198585e55d9cb07edcd1e5a69526547fbd0f2c642e" "9ee96e19462031f1032f1cd862bb952900103c06ac16344d7f9c9df0feaaf5a733dea7ea2df70a61" "9936fcc5501de75c5d112e8abd7573c461ada29ec016d131aa557804320011ff6d94092581ceea1b" "ad3cf0d651938802ca867cd52bbe50c2da1161cb09514407609920" ); impl_tests!(XChaCha20Poly1305, CIPHERTEXT); } #[cfg(feature = "salsa20")] mod xsalsa20poly1305 { use super::{KEY, NONCE, PLAINTEXT}; use crypto_secretbox::{ aead::{generic_array::GenericArray, Aead, KeyInit}, XSalsa20Poly1305, }; use hex_literal::hex; const CIPHERTEXT: &[u8] = &hex!( "f3ffc7703f9400e52a7dfb4b3d3305d98e993b9f48681273c29650ba32fc76ce48332ea7164d96a4" "476fb8c531a1186ac0dfc17c98dce87b4da7f011ec48c97271d2c20f9b928fe2270d6fb863d51738" "b48eeee314a7cc8ab932164548e526ae90224368517acfeabd6bb3732bc0e9da99832b61ca01b6de" "56244a9e88d5f9b37973f622a43d14a6599b1f654cb45a74e355a5" ); impl_tests!(XSalsa20Poly1305, CIPHERTEXT); }