salsa20-0.10.2/.cargo_vcs_info.json0000644000000001450000000000100123610ustar { "git": { "sha1": "d5a03c09eb1a0326809d766686f51fbbd86ddb8b" }, "path_in_vcs": "salsa20" }salsa20-0.10.2/CHANGELOG.md000064400000000000000000000076200072674642500130170ustar 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.10.2 (2022-02-17) ### Added - `SalsaCore::from_raw_state` inherent method ([#291]) [#291]: https://github.com/RustCrypto/stream-ciphers/pull/291 ## 0.10.1 (2022-02-17) ### Fixed - Minimal versions build ([#290]) [#290]: https://github.com/RustCrypto/stream-ciphers/pull/290 ## 0.10.0 (2022-02-10) ### Changed - Bump `cipher` dependency to v0.4 ([#276]) [#276]: https://github.com/RustCrypto/stream-ciphers/pull/276 ## 0.9.0 (2021-08-29) ### Removed - `xsalsa` feature: `XSalsa20` is now available by-default ([#271]) [#271]: https://github.com/RustCrypto/stream-ciphers/pull/271 ## 0.8.1 (2021-07-20) ### Changed - Pin `zeroize` dependency to v1.3 ([#256]) [#256]: https://github.com/RustCrypto/stream-ciphers/pull/256 ## 0.8.0 (2021-04-29) ### Changed - Rename `Block` to `Core` ([#204]) - Bump `cipher` crate dependency to v0.3 release ([#226]) [#204]: https://github.com/RustCrypto/stream-ciphers/pull/204 [#226]: https://github.com/RustCrypto/stream-ciphers/pull/226 ## 0.7.2 (2020-11-11) ### Fixed - `no_std` builds with `zeroize` feature enabled ([#189]) [#189]: https://github.com/RustCrypto/stream-ciphers/pull/189 ## 0.7.1 (2020-10-18) ### Added - `expose-core` feature ([#180]) [#180]: https://github.com/RustCrypto/stream-ciphers/pull/180 ## 0.7.0 (2020-10-16) ### Changed - Replace `block-cipher`/`stream-cipher` with `cipher` crate ([#177]) - Renamed `Cipher` to `Salsa` ([#177]) [#177]: https://github.com/RustCrypto/stream-ciphers/pull/177 ## 0.6.0 (2020-08-25) ### Changed - Bump `stream-cipher` dependency to v0.7 ([#161], [#164]) [#161]: https://github.com/RustCrypto/stream-ciphers/pull/161 [#164]: https://github.com/RustCrypto/stream-ciphers/pull/164 ## 0.5.2 (2020-06-11) ### Changed - Use `Key` and `Nonce` in usage docs ([#155]) ### Fixed - `stream-cipher` version requirement ([#152]) [#155]: https://github.com/RustCrypto/stream-ciphers/pull/155 [#152]: https://github.com/RustCrypto/stream-ciphers/pull/152 ## 0.5.1 (2020-06-11) ### Added - Documentation improvements ([#149]) - `Key`, `Nonce`, and `XNonce` type aliases ([#146]) ### Changed - Bump `stream-cipher` to v0.4.1 ([#148]) [#149]: https://github.com/RustCrypto/stream-ciphers/pull/149 [#148]: https://github.com/RustCrypto/stream-ciphers/pull/148 [#146]: https://github.com/RustCrypto/stream-ciphers/pull/146 ## 0.5.0 (2020-06-06) ### Added - `Salsa8` and `Salsa12` variants ([#133]) ### Changed - Upgrade to the `stream-cipher` v0.4 crate ([#125], [#138]) [#138]: https://github.com/RustCrypto/stream-ciphers/pull/138 [#133]: https://github.com/RustCrypto/stream-ciphers/pull/133 [#125]: https://github.com/RustCrypto/stream-ciphers/pull/125 ## 0.4.1 (2020-02-25) ### Added - `hsalsa20` feature ([#103]) [#103]: https://github.com/RustCrypto/stream-ciphers/pull/103 ## 0.4.0 (2020-01-17) ### Changed - Replace `salsa20-core` with `ctr`-derived buffering; MSRV 1.34+ ([#94]) [#94]: https://github.com/RustCrypto/stream-ciphers/pull/94 ## 0.3.0 (2019-10-01) ### Added - XSalsa20 ([#54]) [#54]: https://github.com/RustCrypto/stream-ciphers/pull/44 ## 0.2.0 (2019-08-18) ### Added - Improve documentation ([#17]) - Impl `SyncStreamCipher` ([#39]) ### Changed - Refactoring ([#38], [#44]) ### Fixed - Fix broken Cargo feature attributes ([#21]) [#44]: https://github.com/RustCrypto/stream-ciphers/pull/44 [#39]: https://github.com/RustCrypto/stream-ciphers/pull/39 [#38]: https://github.com/RustCrypto/stream-ciphers/pull/38 [#21]: https://github.com/RustCrypto/stream-ciphers/pull/21 [#17]: https://github.com/RustCrypto/stream-ciphers/pull/17 ## 0.1.1 (2019-06-30) ### Added - `#![no_std]` support [#19]: https://github.com/RustCrypto/stream-ciphers/pull/19 ## 0.1.0 (2019-06-24) - Initial release salsa20-0.10.2/Cargo.toml0000644000000022300000000000100103540ustar # 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.56" name = "salsa20" version = "0.10.2" authors = ["RustCrypto Developers"] description = "Salsa20 Stream Cipher" documentation = "https://docs.rs/salsa20" readme = "README.md" keywords = ["crypto", "stream-cipher", "trait", "xsalsa20"] categories = ["cryptography", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/RustCrypto/stream-ciphers" [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies.cipher] version = "0.4.2" [dev-dependencies.cipher] version = "0.4.2" features = ["dev"] [dev-dependencies.hex-literal] version = "0.3.3" [features] std = ["cipher/std"] zeroize = ["cipher/zeroize"] salsa20-0.10.2/Cargo.toml.orig000064400000000000000000000013430072674642500140710ustar 00000000000000[package] name = "salsa20" version = "0.10.2" # Also update html_root_url in lib.rs when bumping this description = "Salsa20 Stream Cipher" authors = ["RustCrypto Developers"] license = "MIT OR Apache-2.0" edition = "2021" rust-version = "1.56" readme = "README.md" documentation = "https://docs.rs/salsa20" repository = "https://github.com/RustCrypto/stream-ciphers" keywords = ["crypto", "stream-cipher", "trait", "xsalsa20"] categories = ["cryptography", "no-std"] [dependencies] cipher = "0.4.2" [dev-dependencies] cipher = { version = "0.4.2", features = ["dev"] } hex-literal = "0.3.3" [features] std = ["cipher/std"] zeroize = ["cipher/zeroize"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] salsa20-0.10.2/LICENSE-APACHE000064400000000000000000000251410072674642500131300ustar 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. salsa20-0.10.2/LICENSE-MIT000064400000000000000000000020410072674642500126320ustar 00000000000000Copyright (c) 2019 Eric McCorkle 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. salsa20-0.10.2/README.md000064400000000000000000000057610072674642500124710ustar 00000000000000# RustCrypto: Salsa20 Stream Cipher [![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] [![HAZMAT][hazmat-image]][hazmat-link] Pure Rust implementation of the [Salsa20 Stream Cipher][1]. [Documentation][docs-link] ## About [Salsa20][1] is a [stream cipher][2] which is designed to support high-performance software implementations. This crate also contains an implementation of [XSalsa20][3]: a variant of Salsa20 with an extended 192-bit (24-byte) nonce, gated under the `xsalsa20` Cargo feature (on-by-default). ## ⚠️ Security Warning: [Hazmat!][hazmat-link] This crate does not ensure ciphertexts are authentic (i.e. by using a MAC to verify ciphertext integrity), which can lead to serious vulnerabilities if used incorrectly! 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! ## Minimum Supported Rust Version Rust **1.56** or higher. Minimum supported Rust version can be changed in the future, but it will be done with a minor version bump. ## SemVer Policy - All on-by-default features of this library are covered by SemVer - MSRV is considered exempt from SemVer as noted above ## 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://img.shields.io/crates/v/salsa20.svg [crate-link]: https://crates.io/crates/salsa20 [docs-image]: https://docs.rs/salsa20/badge.svg [docs-link]: https://docs.rs/salsa20/ [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg [chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg [chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260049-stream-ciphers [hazmat-image]: https://img.shields.io/badge/crypto-hazmat%E2%9A%A0-red.svg [hazmat-link]: https://github.com/RustCrypto/meta/blob/master/HAZMAT.md [build-image]: https://github.com/RustCrypto/stream-ciphers/workflows/salsa20/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/stream-ciphers/actions?query=workflow%3Asalsa20 [//]: # (footnotes) [1]: https://en.wikipedia.org/wiki/Salsa20 [2]: https://en.wikipedia.org/wiki/Stream_cipher [3]: https://cr.yp.to/snuffle/xsalsa-20081128.pdf [4]: https://github.com/RustCrypto/AEADs/tree/master/xsalsa20poly1305 salsa20-0.10.2/benches/mod.rs000075500000000000000000000010520072674642500137360ustar 00000000000000#![feature(test)] extern crate test; cipher::stream_cipher_bench!( salsa20::Salsa8; salsa8_bench1_16b 16; salsa8_bench2_256b 256; salsa8_bench3_1kib 1024; salsa8_bench4_16kib 16384; ); cipher::stream_cipher_bench!( salsa20::Salsa12; salsa12_bench1_16b 16; salsa12_bench2_256b 256; salsa12_bench3_1kib 1024; salsa12_bench4_16kib 16384; ); cipher::stream_cipher_bench!( salsa20::Salsa20; salsa20_bench1_16b 16; salsa20_bench2_256b 256; salsa20_bench3_1kib 1024; salsa20_bench4_16kib 16384; ); salsa20-0.10.2/src/lib.rs000064400000000000000000000200240072674642500131020ustar 00000000000000//! 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: //! //! //! //! 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 `GenericArray` 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); //! ``` //! //! [Salsa]: https://en.wikipedia.org/wiki/Salsa20 #![no_std] #![cfg_attr(docsrs, feature(doc_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", html_root_url = "https://docs.rs/salsa20/0.10.2" )] #![forbid(unsafe_code)] #![warn(missing_docs, rust_2018_idioms, trivial_casts, unused_qualifications)] pub use cipher; use cipher::{ consts::{U1, U10, U24, U32, U4, U6, U64, U8}, generic_array::{typenum::Unsigned, GenericArray}, Block, BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, ParBlocksSizeUser, StreamBackend, StreamCipherCore, StreamCipherCoreWrapper, StreamCipherSeekCore, StreamClosure, }; use core::marker::PhantomData; #[cfg(feature = "zeroize")] use cipher::zeroize::{Zeroize, ZeroizeOnDrop}; mod xsalsa; pub use xsalsa::{hsalsa, XSalsa12, XSalsa20, XSalsa8, XSalsaCore}; /// Salsa20/8 stream cipher /// (reduced-round variant of Salsa20 with 8 rounds, *not recommended*) pub type Salsa8 = StreamCipherCoreWrapper>; /// Salsa20/12 stream cipher /// (reduced-round variant of Salsa20 with 12 rounds, *not recommended*) pub type Salsa12 = StreamCipherCoreWrapper>; /// Salsa20/20 stream cipher /// (20 rounds; **recommended**) pub type Salsa20 = StreamCipherCoreWrapper>; /// Key type used by all Salsa variants and [`XSalsa20`]. pub type Key = GenericArray; /// Nonce type used by all Salsa variants. pub type Nonce = GenericArray; /// Nonce type used by [`XSalsa20`]. pub type XNonce = GenericArray; /// Number of 32-bit words in the Salsa20 state const STATE_WORDS: usize = 16; /// State initialization constant ("expand 32-byte k") const CONSTANTS: [u32; 4] = [0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574]; /// The Salsa20 core function. pub struct SalsaCore { /// Internal state of the core function state: [u32; STATE_WORDS], /// Number of rounds to perform rounds: PhantomData, } impl SalsaCore { /// 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, } } } impl KeySizeUser for SalsaCore { type KeySize = U32; } impl IvSizeUser for SalsaCore { type IvSize = U8; } impl BlockSizeUser for SalsaCore { type BlockSize = U64; } impl KeyIvInit for SalsaCore { fn new(key: &Key, iv: &Nonce) -> Self { let mut state = [0u32; STATE_WORDS]; state[0] = CONSTANTS[0]; for (i, chunk) in key[..16].chunks(4).enumerate() { state[1 + i] = u32::from_le_bytes(chunk.try_into().unwrap()); } state[5] = CONSTANTS[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[2]; for (i, chunk) in key[16..].chunks(4).enumerate() { state[11 + i] = u32::from_le_bytes(chunk.try_into().unwrap()); } state[15] = CONSTANTS[3]; Self { state, rounds: PhantomData, } } } impl StreamCipherCore for SalsaCore { #[inline(always)] fn remaining_blocks(&self) -> Option { let rem = u64::MAX - self.get_block_pos(); rem.try_into().ok() } fn process_with_backend(&mut self, f: impl StreamClosure) { f.call(&mut Backend(self)); } } impl StreamCipherSeekCore for SalsaCore { 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")] #[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))] impl Drop for SalsaCore { fn drop(&mut self) { self.state.zeroize(); } } #[cfg(feature = "zeroize")] #[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))] impl ZeroizeOnDrop for SalsaCore {} struct Backend<'a, R: Unsigned>(&'a mut SalsaCore); impl<'a, R: Unsigned> BlockSizeUser for Backend<'a, R> { type BlockSize = U64; } impl<'a, R: Unsigned> ParBlocksSizeUser for Backend<'a, R> { type ParBlocksSize = U1; } impl<'a, R: Unsigned> StreamBackend for Backend<'a, R> { #[inline(always)] fn gen_ks_block(&mut self, block: &mut Block) { let res = run_rounds::(&self.0.state); self.0.set_block_pos(self.0.get_block_pos() + 1); for (chunk, val) in block.chunks_exact_mut(4).zip(res.iter()) { chunk.copy_from_slice(&val.to_le_bytes()); } } } #[inline] #[allow(clippy::many_single_char_names)] pub(crate) fn quarter_round( a: usize, b: usize, c: usize, d: usize, state: &mut [u32; STATE_WORDS], ) { state[b] ^= state[a].wrapping_add(state[d]).rotate_left(7); state[c] ^= state[b].wrapping_add(state[a]).rotate_left(9); state[d] ^= state[c].wrapping_add(state[b]).rotate_left(13); state[a] ^= state[d].wrapping_add(state[c]).rotate_left(18); } #[inline(always)] fn run_rounds(state: &[u32; STATE_WORDS]) -> [u32; STATE_WORDS] { let mut res = *state; for _ in 0..R::USIZE { // column rounds quarter_round(0, 4, 8, 12, &mut res); quarter_round(5, 9, 13, 1, &mut res); quarter_round(10, 14, 2, 6, &mut res); quarter_round(15, 3, 7, 11, &mut res); // diagonal rounds quarter_round(0, 1, 2, 3, &mut res); quarter_round(5, 6, 7, 4, &mut res); quarter_round(10, 11, 8, 9, &mut res); quarter_round(15, 12, 13, 14, &mut res); } for (s1, s0) in res.iter_mut().zip(state.iter()) { *s1 = s1.wrapping_add(*s0); } res } salsa20-0.10.2/src/xsalsa.rs000064400000000000000000000102250072674642500136310ustar 00000000000000//! XSalsa20 is an extended nonce variant of Salsa20 use super::{quarter_round, Key, Nonce, SalsaCore, Unsigned, XNonce, CONSTANTS}; use cipher::{ consts::{U10, U16, U24, U32, U4, U6, U64}, generic_array::GenericArray, BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCore, StreamCipherCoreWrapper, StreamCipherSeekCore, StreamClosure, }; #[cfg(feature = "zeroize")] use cipher::zeroize::ZeroizeOnDrop; /// XSalsa20 is a Salsa20 variant with an extended 192-bit (24-byte) nonce. /// /// Based on the paper "Extending the Salsa20 Nonce": /// /// pub type XSalsa20 = StreamCipherCoreWrapper>; /// XSalsa12 stream cipher (reduced-round variant of [`XSalsa20`] with 12 rounds) pub type XSalsa12 = StreamCipherCoreWrapper>; /// XSalsa8 stream cipher (reduced-round variant of [`XSalsa20`] with 8 rounds) pub type XSalsa8 = StreamCipherCoreWrapper>; /// The XSalsa core function. pub struct XSalsaCore(SalsaCore); impl KeySizeUser for XSalsaCore { type KeySize = U32; } impl IvSizeUser for XSalsaCore { type IvSize = U24; } impl BlockSizeUser for XSalsaCore { type BlockSize = U64; } impl KeyIvInit for XSalsaCore { #[inline] fn new(key: &Key, iv: &XNonce) -> Self { let subkey = hsalsa::(key, iv[..16].as_ref().into()); let mut padded_iv = Nonce::default(); padded_iv.copy_from_slice(&iv[16..]); XSalsaCore(SalsaCore::new(&subkey, &padded_iv)) } } impl StreamCipherCore for XSalsaCore { #[inline(always)] fn remaining_blocks(&self) -> Option { self.0.remaining_blocks() } #[inline(always)] fn process_with_backend(&mut self, f: impl StreamClosure) { self.0.process_with_backend(f); } } impl StreamCipherSeekCore for XSalsaCore { type Counter = u64; #[inline(always)] fn get_block_pos(&self) -> u64 { self.0.get_block_pos() } #[inline(always)] fn set_block_pos(&mut self, pos: u64) { self.0.set_block_pos(pos); } } #[cfg(feature = "zeroize")] #[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))] impl ZeroizeOnDrop for XSalsaCore {} /// The HSalsa20 function defined in the paper "Extending the Salsa20 nonce" /// /// /// /// HSalsa20 takes 512-bits of input: /// /// - Constants (`u32` x 4) /// - Key (`u32` x 8) /// - Nonce (`u32` x 4) /// /// It produces 256-bits of output suitable for use as a Salsa20 key pub fn hsalsa(key: &Key, input: &GenericArray) -> GenericArray { #[inline(always)] fn to_u32(chunk: &[u8]) -> u32 { u32::from_le_bytes(chunk.try_into().unwrap()) } let mut state = [0u32; 16]; state[0] = CONSTANTS[0]; state[1..5] .iter_mut() .zip(key[0..16].chunks_exact(4)) .for_each(|(v, chunk)| *v = to_u32(chunk)); state[5] = CONSTANTS[1]; state[6..10] .iter_mut() .zip(input.chunks_exact(4)) .for_each(|(v, chunk)| *v = to_u32(chunk)); state[10] = CONSTANTS[2]; state[11..15] .iter_mut() .zip(key[16..].chunks_exact(4)) .for_each(|(v, chunk)| *v = to_u32(chunk)); state[15] = CONSTANTS[3]; // 20 rounds consisting of 10 column rounds and 10 diagonal rounds for _ in 0..R::USIZE { // column rounds quarter_round(0, 4, 8, 12, &mut state); quarter_round(5, 9, 13, 1, &mut state); quarter_round(10, 14, 2, 6, &mut state); quarter_round(15, 3, 7, 11, &mut state); // diagonal rounds quarter_round(0, 1, 2, 3, &mut state); quarter_round(5, 6, 7, 4, &mut state); quarter_round(10, 11, 8, 9, &mut state); quarter_round(15, 12, 13, 14, &mut state); } let mut output = GenericArray::default(); let key_idx: [usize; 8] = [0, 5, 10, 15, 6, 7, 8, 9]; for (i, chunk) in output.chunks_exact_mut(4).enumerate() { chunk.copy_from_slice(&state[key_idx[i]].to_le_bytes()); } output } salsa20-0.10.2/tests/mod.rs000064400000000000000000000110330072674642500134660ustar 00000000000000//! Salsa20 tests use cipher::{KeyIvInit, StreamCipher, StreamCipherSeek}; use hex_literal::hex; use salsa20::Salsa20; use salsa20::XSalsa20; cipher::stream_cipher_seek_test!(salsa20_seek, Salsa20); cipher::stream_cipher_seek_test!(xsalsa20_seek, XSalsa20); const KEY_BYTES: usize = 32; const IV_BYTES: usize = 8; const IV_BYTES_XSALSA20: usize = 24; const KEY0: [u8; KEY_BYTES] = [0; KEY_BYTES]; const KEY1: [u8; KEY_BYTES] = hex!( "80000000000000000000000000000000" "00000000000000000000000000000000" ); const KEY_LONG: [u8; KEY_BYTES] = hex!( "0102030405060708090A0B0C0D0E0F10" "1112131415161718191A1B1C1D1E1F20" ); const KEY_XSALSA20: [u8; KEY_BYTES] = *b"this is 32-byte key for xsalsa20"; const IV0: [u8; IV_BYTES] = [0; IV_BYTES]; const IV1: [u8; IV_BYTES] = hex!("8000000000000000"); const IVHI: [u8; IV_BYTES] = hex!("0000000000000001"); const IV_LONG: [u8; IV_BYTES] = hex!("0301040105090206"); const IV_XSALSA20: [u8; IV_BYTES_XSALSA20] = *b"24-byte nonce for xsalsa"; const EXPECTED_KEY1_IV0: [u8; 64] = hex!( "e3be8fdd8beca2e3ea8ef9475b29a6e7" "003951e1097a5c38d23b7a5fad9f6844" "b22c97559e2723c7cbbd3fe4fc8d9a07" "44652a83e72a9c461876af4d7ef1a117" ); const EXPECTED_KEY0_IV1: [u8; 64] = hex!( "2aba3dc45b4947007b14c851cd694456" "b303ad59a465662803006705673d6c3e" "29f1d3510dfc0405463c03414e0e07e3" "59f1f1816c68b2434a19d3eee0464873" ); const EXPECTED_KEY0_IVHI: [u8; 64] = hex!( "b47f96aa96786135297a3c4ec56a613d" "0b80095324ff43239d684c57ffe42e1c" "44f3cc011613db6cdc880999a1e65aed" "1287fcb11c839c37120765afa73e5075" ); const EXPECTED_LONG: [u8; 256] = hex!( "6ebcbdbf76fccc64ab05542bee8a67cb" "c28fa2e141fbefbb3a2f9b221909c8d7" "d4295258cb539770dd24d7ac3443769f" "fa27a50e60644264dc8b6b612683372e" "085d0a12bf240b189ce2b78289862b56" "fdc9fcffc33bef9325a2e81b98fb3fb9" "aa04cf434615ceffeb985c1cb08d8440" "e90b1d56ddeaea16d9e15affff1f698c" "483c7a466af1fe062574adfd2b06a62b" "4d98440719ea776385c470349a7ed696" "9583463ed5d26b8fefccb205da0f5bfa" "98c77812fe756b09eacc282aa42f4baf" "a79633189046e2b20f35b3e0e54aa3b9" "29e23c0f47dc7bcd4f928b2a9764be7d" "4b8a50f980a50b35ad8087375e0c556e" "cbe6a7161e8653ce9391e1e6710ed4f1" ); const EXPECTED_XSALSA20_ZEROS: [u8; 64] = hex!( "4848297feb1fb52fb66d81609bd547fa" "bcbe7026edc8b5e5e449d088bfa69c08" "8f5d8da1d791267c2c195a7f8cae9c4b" "4050d08ce6d3a151ec265f3a58e47648" ); const EXPECTED_XSALSA20_HELLO_WORLD: [u8; 12] = hex!("002d4513843fc240c401e541"); #[test] fn salsa20_key1_iv0() { let mut cipher = Salsa20::new(&KEY1.into(), &IV0.into()); let mut buf = [0; 64]; cipher.apply_keystream(&mut buf); for i in 0..64 { assert_eq!(buf[i], EXPECTED_KEY1_IV0[i]) } } #[test] fn salsa20_key0_iv1() { let mut cipher = Salsa20::new(&KEY0.into(), &IV1.into()); let mut buf = [0; 64]; cipher.apply_keystream(&mut buf); for i in 0..64 { assert_eq!(buf[i], EXPECTED_KEY0_IV1[i]) } } #[test] fn salsa20_key0_ivhi() { let mut cipher = Salsa20::new(&KEY0.into(), &IVHI.into()); let mut buf = [0; 64]; cipher.apply_keystream(&mut buf); for i in 0..64 { assert_eq!(buf[i], EXPECTED_KEY0_IVHI[i]) } } #[test] fn salsa20_long() { let mut cipher = Salsa20::new(&KEY_LONG.into(), &IV_LONG.into()); let mut buf = [0; 256]; cipher.apply_keystream(&mut buf); for i in 0..256 { assert_eq!(buf[i], EXPECTED_LONG[i]) } } #[test] #[ignore] fn salsa20_offsets() { for idx in 0..256 { for middle in idx..256 { for last in middle..256 { let mut cipher = Salsa20::new(&KEY_LONG.into(), &IV_LONG.into()); let mut buf = [0; 256]; cipher.seek(idx as u64); cipher.apply_keystream(&mut buf[idx..middle]); cipher.apply_keystream(&mut buf[middle..last]); for k in idx..last { assert_eq!(buf[k], EXPECTED_LONG[k]) } } } } } #[test] fn xsalsa20_encrypt_zeros() { let mut cipher = XSalsa20::new(&KEY_XSALSA20.into(), &IV_XSALSA20.into()); let mut buf = [0; 64]; cipher.apply_keystream(&mut buf); for i in 0..64 { assert_eq!(buf[i], EXPECTED_XSALSA20_ZEROS[i]); } } #[test] fn xsalsa20_encrypt_hello_world() { let mut cipher = XSalsa20::new(&KEY_XSALSA20.into(), &IV_XSALSA20.into()); let mut buf = *b"Hello world!"; cipher.apply_keystream(&mut buf); assert_eq!(buf, EXPECTED_XSALSA20_HELLO_WORLD); }