scrypt-0.11.0/.cargo_vcs_info.json0000644000000001440000000000100124360ustar { "git": { "sha1": "7e84684d711846230b265c45da0da0bb40513fea" }, "path_in_vcs": "scrypt" }scrypt-0.11.0/CHANGELOG.md000064400000000000000000000123201046102023000130360ustar 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.11.0 (2023-03-04) ### Added - Ability to use custom output key length ([#255]) - Inherent constants for `Params` recommendations ([#387]) ### Changed - Bump `password-hash` to v0.5; MSRV 1.60 ([#383]) - Adopt OWASP recommendations ([#388]) - Bump `pbkdf2` to v0.12 ([#393]) [#255]: https://github.com/RustCrypto/password-hashes/pull/255 [#383]: https://github.com/RustCrypto/password-hashes/pull/383 [#387]: https://github.com/RustCrypto/password-hashes/pull/387 [#388]: https://github.com/RustCrypto/password-hashes/pull/388 [#393]: https://github.com/RustCrypto/password-hashes/pull/393 ## 0.10.0 (2022-03-18) ### Changed - Bump `password-hash` dependency to v0.4; MSRV 1.57 ([#283]) - Bump `pbkdf2` dependency to v0.11 ([#291]) [#283]: https://github.com/RustCrypto/password-hashes/pull/283 [#291]: https://github.com/RustCrypto/password-hashes/pull/291 ## 0.9.0 (2022-02-17) ### Changed - Bump `salsa20` dependency to v0.10, edition to 2021, and MSRV to 1.56 ([#273]) [#273]: https://github.com/RustCrypto/password-hashes/pull/273 ## 0.8.1 (2021-11-25) ### Changed - Bump `sha2` dependency to v0.10, `pbkdf2` to v0.10, `hmac` to v0.12 ([#254]) [#254]: https://github.com/RustCrypto/password-hashes/pull/254 ## 0.8.0 (2021-08-27) ### Changed - Bump `password-hash` to v0.3 ([#217]) - Use `resolver = "2"`; MSRV 1.51+ ([#220]) - Bump `pbkdf2` dependency to v0.9 ([#233]) ### Removed - `McfHasher` impls for `Scrypt` ([#219]) [#217]: https://github.com/RustCrypto/password-hashing/pull/217 [#219]: https://github.com/RustCrypto/password-hashing/pull/219 [#220]: https://github.com/RustCrypto/password-hashing/pull/220 [#233]: https://github.com/RustCrypto/password-hashing/pull/233 ## 0.7.0 (2021-04-29) ### Changed - Bump `password-hash` crate dependency to v0.2 ([#164]) - Bump `hmac` and `crypto-mac` crate deps to v0.11 ([#165]) - Bump `salsa20` crate dependency to v0.8 ([#166]) - Bump `pbkdf2` crate dependency to v0.8 ([#167]) [#164]: https://github.com/RustCrypto/password-hashing/pull/164 [#165]: https://github.com/RustCrypto/password-hashing/pull/165 [#166]: https://github.com/RustCrypto/password-hashing/pull/166 [#167]: https://github.com/RustCrypto/password-hashing/pull/167 ## 0.6.5 (2021-03-27) ### Fixed - Pin `password-hash` to v0.1.2 or newer ([#151]) [#151]: https://github.com/RustCrypto/password-hashing/pull/151 ## 0.6.4 (2021-03-17) ### Changed - Bump `base64ct` dependency to v1.0 ([#144]) [#144]: https://github.com/RustCrypto/password-hashing/pull/144 ## 0.6.3 (2021-02-20) ### Changed - Enable `rand_core` feature of `password-hash` ([#139]) [#139]: https://github.com/RustCrypto/password-hashing/pull/139 ## 0.6.2 (2021-02-06) ### Added - `Params` accessor methods ([#123]) [#123]: https://github.com/RustCrypto/password-hashing/pull/123 ## 0.6.1 (2021-02-01) ### Changed - Bump `base64ct` dependency to v0.2 ([#119]) [#119]: https://github.com/RustCrypto/password-hashing/pull/119 ## 0.6.0 (2021-01-29) ### Added - PHC hash support using `password-hash` crate ([#111]) ### Changed - Rename `include_simple` features to `simple` ([#99]) - Rename `ScryptParams` => `Params` ([#112]) [#99]: https://github.com/RustCrypto/password-hashing/pull/99 [#111]: https://github.com/RustCrypto/password-hashing/pull/111 [#112]: https://github.com/RustCrypto/password-hashing/pull/112 ## 0.5.0 (2020-10-18) ### Changed - Bump `crypto-mac` dependency to v0.10 ([#58]) - Use `salsa20`crate to implement Salsa20/8 ([#60]) [#60]: https://github.com/RustCrypto/password-hashing/pull/60 [#58]: https://github.com/RustCrypto/password-hashing/pull/58 ## 0.4.1 (2020-08-24) ### Changed - Minor documentation update ([#50]) [#50]: https://github.com/RustCrypto/password-hashing/pull/50 ## 0.4.0 (2020-08-18) ### Changed - Bump `pbkdf2` dependency to v0.5 ([#45]) [#45]: https://github.com/RustCrypto/password-hashing/pull/45 ## 0.3.1 (2020-07-03) ### Fixed - Enable `alloc` feature for `base64`. ([#38]) - Remove superfluous `main()` in documentation ([#40]) [#38]: https://github.com/RustCrypto/password-hashing/pull/38 [#40]: https://github.com/RustCrypto/password-hashing/pull/40 ## 0.3.0 (2020-06-10) ### Added - `recommended` method for easy creation of recommended ScryptParam ([#28]) - `std` feature ([#32]) - `thread_rng` feature ([#33]) ### Changed - Code improvements ([#33]) - Bump `rand` to v0.7 ([#33]) - Bump `hmac` to v0.8 ([#30]) - Bump `sha2` to v0.9 ([#30]) - Bump `pbkdf2` to v0.4 ([#36]) - Bump `subtle` to v2 ([#13]) - MSRV 1.41+ ([#30]) - Upgrade to Rust 2018 edition ([#24]) [#36]: https://github.com/RustCrypto/password-hashing/pull/36 [#33]: https://github.com/RustCrypto/password-hashing/pull/33 [#32]: https://github.com/RustCrypto/password-hashing/pull/32 [#30]: https://github.com/RustCrypto/password-hashing/pull/30 [#28]: https://github.com/RustCrypto/password-hashing/pull/28 [#24]: https://github.com/RustCrypto/password-hashing/pull/24 [#13]: https://github.com/RustCrypto/password-hashing/pull/13 ## 0.2.0 (2018-10-08) ## 0.1.2 (2018-08-30) ## 0.1.1 (2018-07-15) ## 0.1.0 (2018-06-30) scrypt-0.11.0/Cargo.toml0000644000000027630000000000100104450ustar # 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 = "scrypt" version = "0.11.0" authors = ["RustCrypto Developers"] description = "Scrypt password-based key derivation function" documentation = "https://docs.rs/scrypt" readme = "README.md" keywords = [ "crypto", "hashing", "password", "phf", ] categories = [ "authentication", "cryptography", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/RustCrypto/password-hashes/tree/master/scrypt" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.password-hash] version = "0.5" features = ["rand_core"] optional = true default-features = false [dependencies.pbkdf2] version = "0.12" [dependencies.salsa20] version = "0.10.2" default-features = false [dependencies.sha2] version = "0.10" default-features = false [dev-dependencies.password-hash] version = "0.5" features = ["rand_core"] [features] default = [ "simple", "std", ] simple = ["password-hash"] std = ["password-hash/std"] scrypt-0.11.0/Cargo.toml.orig000064400000000000000000000020111046102023000141100ustar 00000000000000[package] name = "scrypt" version = "0.11.0" description = "Scrypt password-based key derivation function" authors = ["RustCrypto Developers"] license = "MIT OR Apache-2.0" readme = "README.md" documentation = "https://docs.rs/scrypt" repository = "https://github.com/RustCrypto/password-hashes/tree/master/scrypt" keywords = ["crypto", "hashing", "password", "phf"] categories = ["authentication", "cryptography", "no-std"] edition = "2021" rust-version = "1.60" [dependencies] pbkdf2 = { version = "0.12", path = "../pbkdf2" } salsa20 = { version = "0.10.2", default-features = false } sha2 = { version = "0.10", default-features = false } # optional dependencies password-hash = { version = "0.5", default-features = false, features = ["rand_core"], optional = true } [dev-dependencies] password-hash = { version = "0.5", features = ["rand_core"] } [features] default = ["simple", "std"] simple = ["password-hash"] std = ["password-hash/std"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] scrypt-0.11.0/LICENSE-APACHE000064400000000000000000000251411046102023000131560ustar 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. scrypt-0.11.0/LICENSE-MIT000064400000000000000000000020721046102023000126640ustar 00000000000000Copyright (c) 2021-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. scrypt-0.11.0/README.md000064400000000000000000000034761046102023000125200ustar 00000000000000# RustCrypto: scrypt [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] [![Build Status][build-image]][build-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [![Project Chat][chat-image]][chat-link] Pure Rust implementation of the [scrypt key derivation function][1]. [Documentation][docs-link] ## Minimum Supported Rust Version Rust **1.60** 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://buildstats.info/crate/scrypt [crate-link]: https://crates.io/crates/scrypt [docs-image]: https://docs.rs/scrypt/badge.svg [docs-link]: https://docs.rs/scrypt/ [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/260046-password-hashes [build-image]: https://github.com/RustCrypto/password-hashes/workflows/scrypt/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/password-hashes/actions?query=workflow%3Ascrypt [//]: # (general links) [1]: https://www.tarsnap.com/scrypt.html scrypt-0.11.0/benches/lib.rs000064400000000000000000000006131046102023000137520ustar 00000000000000#![no_std] #![feature(test)] extern crate test; use test::Bencher; #[bench] pub fn scrypt_15_8_1(bh: &mut Bencher) { let password = b"my secure password"; let salt = b"salty salt"; let mut buf = [0u8; 32]; let params = scrypt::Params::recommended(); bh.iter(|| { scrypt::scrypt(password, salt, ¶ms, &mut buf).unwrap(); test::black_box(&buf); }); } scrypt-0.11.0/src/errors.rs000064400000000000000000000012411046102023000136760ustar 00000000000000use core::fmt; /// `scrypt()` error #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct InvalidOutputLen; /// `ScryptParams` error #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct InvalidParams; impl fmt::Display for InvalidOutputLen { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("invalid output buffer length") } } #[cfg(feature = "std")] impl std::error::Error for InvalidOutputLen {} impl fmt::Display for InvalidParams { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("invalid scrypt parameters") } } #[cfg(feature = "std")] impl std::error::Error for InvalidParams {} scrypt-0.11.0/src/lib.rs000064400000000000000000000066631046102023000131450ustar 00000000000000//! This crate implements the Scrypt key derivation function as specified //! in \[1\]. //! //! If you are only using the low-level [`scrypt`] function instead of the //! higher-level [`Scrypt`] struct to produce/verify hash strings, //! it's recommended to disable default features in your `Cargo.toml`: //! //! ```toml //! [dependencies] //! scrypt = { version = "0.2", default-features = false } //! ``` //! //! # Usage (simple with default params) //! //! ``` //! # fn main() -> Result<(), Box> { //! # #[cfg(all(feature = "simple", feature = "std"))] //! # { //! use scrypt::{ //! password_hash::{ //! rand_core::OsRng, //! PasswordHash, PasswordHasher, PasswordVerifier, SaltString //! }, //! Scrypt //! }; //! //! let password = b"hunter42"; // Bad password; don't actually use! //! let salt = SaltString::generate(&mut OsRng); //! //! // Hash password to PHC string ($scrypt$...) //! let password_hash = Scrypt.hash_password(password, &salt)?.to_string(); //! //! // Verify password against PHC string //! let parsed_hash = PasswordHash::new(&password_hash)?; //! assert!(Scrypt.verify_password(password, &parsed_hash).is_ok()); //! # } //! # Ok(()) //! # } //! ``` //! //! # References //! \[1\] - [C. Percival. Stronger Key Derivation Via Sequential //! Memory-Hard Functions](http://www.tarsnap.com/scrypt/scrypt.pdf) #![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" )] #[macro_use] extern crate alloc; #[cfg(feature = "std")] extern crate std; use pbkdf2::pbkdf2_hmac; use sha2::Sha256; /// Errors for `scrypt` operations. pub mod errors; mod params; mod romix; #[cfg(feature = "simple")] mod simple; pub use crate::params::Params; #[cfg(feature = "simple")] pub use password_hash; #[cfg(feature = "simple")] pub use crate::simple::{Scrypt, ALG_ID}; /// The scrypt key derivation function. /// /// # Arguments /// - `password` - The password to process as a byte vector /// - `salt` - The salt value to use as a byte vector /// - `params` - The ScryptParams to use /// - `output` - The resulting derived key is returned in this byte vector. /// **WARNING: Make sure to compare this value in constant time!** /// /// # Return /// `Ok(())` if calculation is successful and `Err(InvalidOutputLen)` if /// `output` does not satisfy the following condition: /// `output.len() > 0 && output.len() <= (2^32 - 1) * 32`. pub fn scrypt( password: &[u8], salt: &[u8], params: &Params, output: &mut [u8], ) -> Result<(), errors::InvalidOutputLen> { // This check required by Scrypt: // check output.len() > 0 && output.len() <= (2^32 - 1) * 32 if output.is_empty() || output.len() / 32 > 0xffff_ffff { return Err(errors::InvalidOutputLen); } // The checks in the ScryptParams constructor guarantee // that the following is safe: let n = 1 << params.log_n; let r128 = (params.r as usize) * 128; let pr128 = (params.p as usize) * r128; let nr128 = n * r128; let mut b = vec![0u8; pr128]; pbkdf2_hmac::(password, salt, 1, &mut b); let mut v = vec![0u8; nr128]; let mut t = vec![0u8; r128]; for chunk in &mut b.chunks_mut(r128) { romix::scrypt_ro_mix(chunk, &mut v, &mut t, n); } pbkdf2_hmac::(password, &b, 1, output); Ok(()) } scrypt-0.11.0/src/params.rs000064400000000000000000000125171046102023000136550ustar 00000000000000use core::mem::size_of; use crate::errors::InvalidParams; #[cfg(feature = "simple")] use password_hash::{errors::InvalidValue, Error, ParamsString, PasswordHash}; /// The Scrypt parameter values. #[derive(Clone, Copy, Debug)] pub struct Params { pub(crate) log_n: u8, pub(crate) r: u32, pub(crate) p: u32, #[allow(dead_code)] // this field is used only with the `PasswordHasher` impl pub(crate) len: usize, } impl Params { /// Recommended log₂ of the Scrypt parameter `N`: CPU/memory cost. pub const RECOMMENDED_LOG_N: u8 = 17; /// Recommended Scrypt parameter `r`: block size. pub const RECOMMENDED_R: u32 = 8; /// Recommended Scrypt parameter `p`: parallelism. pub const RECOMMENDED_P: u32 = 1; /// Recommended Scrypt parameter `Key length`. pub const RECOMMENDED_LEN: usize = 32; /// Create a new instance of [`Params`]. /// /// # Arguments /// - `log_n` - The log₂ of the Scrypt parameter `N` /// - `r` - The Scrypt parameter `r` /// - `p` - The Scrypt parameter `p` /// - `len` - The Scrypt parameter `Key length` /// /// # Conditions /// - `log_n` must be less than `64` /// - `r` must be greater than `0` and less than or equal to `4294967295` /// - `p` must be greater than `0` and less than `4294967295` /// - `len` must be greater than `9` and less than or equal to `64` pub fn new(log_n: u8, r: u32, p: u32, len: usize) -> Result { let cond1 = (log_n as usize) < usize::BITS as usize; let cond2 = size_of::() >= size_of::(); let cond3 = r <= usize::MAX as u32 && p < usize::MAX as u32; let cond4 = (10..=64).contains(&len); if !(r > 0 && p > 0 && cond1 && (cond2 || cond3) && cond4) { return Err(InvalidParams); } let r = r as usize; let p = p as usize; let n: usize = 1 << log_n; // check that r * 128 doesn't overflow let r128 = r.checked_mul(128).ok_or(InvalidParams)?; // check that n * r * 128 doesn't overflow r128.checked_mul(n).ok_or(InvalidParams)?; // check that p * r * 128 doesn't overflow r128.checked_mul(p).ok_or(InvalidParams)?; // This check required by Scrypt: // check: n < 2^(128 * r / 8) // r * 16 won't overflow since r128 didn't if (log_n as usize) >= r * 16 { return Err(InvalidParams); } // This check required by Scrypt: // check: p <= ((2^32-1) * 32) / (128 * r) // It takes a bit of re-arranging to get the check above into this form, // but it is indeed the same. if r * p >= 0x4000_0000 { return Err(InvalidParams); } Ok(Params { log_n, r: r as u32, p: p as u32, len, }) } /// Recommended values sufficient for most use-cases /// - `log_n = 15` (`n = 32768`) /// - `r = 8` /// - `p = 1` pub fn recommended() -> Params { Params { log_n: Self::RECOMMENDED_LOG_N, r: Self::RECOMMENDED_R, p: Self::RECOMMENDED_P, len: Self::RECOMMENDED_LEN, } } /// log₂ of the Scrypt parameter `N`, the work factor. /// /// Memory and CPU usage scale linearly with `N`. pub fn log_n(&self) -> u8 { self.log_n } /// `r` parameter: resource usage. /// /// scrypt iterates 2*r times. Memory and CPU time scale linearly /// with this parameter. pub fn r(&self) -> u32 { self.r } /// `p` parameter: parallelization. pub fn p(&self) -> u32 { self.p } } impl Default for Params { fn default() -> Params { Params::recommended() } } #[cfg(feature = "simple")] #[cfg_attr(docsrs, doc(cfg(feature = "simple")))] impl<'a> TryFrom<&'a PasswordHash<'a>> for Params { type Error = password_hash::Error; fn try_from(hash: &'a PasswordHash<'a>) -> Result { let mut log_n = Self::RECOMMENDED_LOG_N; let mut r = Self::RECOMMENDED_R; let mut p = Self::RECOMMENDED_P; if hash.version.is_some() { return Err(Error::Version); } for (ident, value) in hash.params.iter() { match ident.as_str() { "ln" => { log_n = value .decimal()? .try_into() .map_err(|_| InvalidValue::Malformed.param_error())? } "r" => r = value.decimal()?, "p" => p = value.decimal()?, _ => return Err(password_hash::Error::ParamNameInvalid), } } let len = hash .hash .map(|out| out.len()) .unwrap_or(Self::RECOMMENDED_LEN); Params::new(log_n, r, p, len).map_err(|_| InvalidValue::Malformed.param_error()) } } #[cfg(feature = "simple")] #[cfg_attr(docsrs, doc(cfg(feature = "simple")))] impl TryFrom for ParamsString { type Error = password_hash::Error; fn try_from(input: Params) -> Result { let mut output = ParamsString::new(); output.add_decimal("ln", input.log_n as u32)?; output.add_decimal("r", input.r)?; output.add_decimal("p", input.p)?; Ok(output) } } scrypt-0.11.0/src/romix.rs000064400000000000000000000045071046102023000135300ustar 00000000000000/// Execute the ROMix operation in-place. /// b - the data to operate on /// v - a temporary variable to store the vector V /// t - a temporary variable to store the result of the xor /// n - the scrypt parameter N #[allow(clippy::many_single_char_names)] pub(crate) fn scrypt_ro_mix(b: &mut [u8], v: &mut [u8], t: &mut [u8], n: usize) { fn integerify(x: &[u8], n: usize) -> usize { // n is a power of 2, so n - 1 gives us a bitmask that we can use to perform a calculation // mod n using a simple bitwise and. let mask = n - 1; // This cast is safe since we're going to get the value mod n (which is a power of 2), so we // don't have to care about truncating any of the high bits off //let result = (LittleEndian::read_u32(&x[x.len() - 64..x.len() - 60]) as usize) & mask; let t = u32::from_le_bytes(x[x.len() - 64..x.len() - 60].try_into().unwrap()); (t as usize) & mask } let len = b.len(); for chunk in v.chunks_mut(len) { chunk.copy_from_slice(b); scrypt_block_mix(chunk, b); } for _ in 0..n { let j = integerify(b, n); xor(b, &v[j * len..(j + 1) * len], t); scrypt_block_mix(t, b); } } /// Execute the BlockMix operation /// input - the input vector. The length must be a multiple of 128. /// output - the output vector. Must be the same length as input. fn scrypt_block_mix(input: &[u8], output: &mut [u8]) { use salsa20::{ cipher::{typenum::U4, StreamCipherCore}, SalsaCore, }; type Salsa20_8 = SalsaCore; let mut x = [0u8; 64]; x.copy_from_slice(&input[input.len() - 64..]); let mut t = [0u8; 64]; for (i, chunk) in input.chunks(64).enumerate() { xor(&x, chunk, &mut t); let mut t2 = [0u32; 16]; for (c, b) in t.chunks_exact(4).zip(t2.iter_mut()) { *b = u32::from_le_bytes(c.try_into().unwrap()); } Salsa20_8::from_raw_state(t2).write_keystream_block((&mut x).into()); let pos = if i % 2 == 0 { (i / 2) * 64 } else { (i / 2) * 64 + input.len() / 2 }; output[pos..pos + 64].copy_from_slice(&x); } } fn xor(x: &[u8], y: &[u8], output: &mut [u8]) { for ((out, &x_i), &y_i) in output.iter_mut().zip(x.iter()).zip(y.iter()) { *out = x_i ^ y_i; } } scrypt-0.11.0/src/simple.rs000064400000000000000000000035251046102023000136620ustar 00000000000000//! Implementation of the `password-hash` crate API. use crate::{scrypt, Params}; use core::cmp::Ordering; use password_hash::{Decimal, Error, Ident, Output, PasswordHash, PasswordHasher, Result, Salt}; /// Algorithm identifier pub const ALG_ID: Ident = Ident::new_unwrap("scrypt"); /// scrypt type for use with [`PasswordHasher`]. /// /// See the [crate docs](crate) for a usage example. #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[cfg_attr(docsrs, doc(cfg(feature = "simple")))] pub struct Scrypt; impl PasswordHasher for Scrypt { type Params = Params; fn hash_password_customized<'a>( &self, password: &[u8], alg_id: Option>, version: Option, params: Params, salt: impl Into>, ) -> Result> { if !matches!(alg_id, Some(ALG_ID) | None) { return Err(Error::Algorithm); } // Versions unsupported if version.is_some() { return Err(Error::Version); } let salt = salt.into(); let mut salt_arr = [0u8; 64]; let salt_bytes = salt.decode_b64(&mut salt_arr)?; let output = Output::init_with(params.len, |out| { scrypt(password, salt_bytes, ¶ms, out).map_err(|_| { let provided = if out.is_empty() { Ordering::Less } else { Ordering::Greater }; password_hash::Error::OutputSize { provided, expected: 0, // TODO(tarcieri): calculate for `Ordering::Greater` case } }) })?; Ok(PasswordHash { algorithm: ALG_ID, version: None, params: params.try_into()?, salt: Some(salt), hash: Some(output), }) } } scrypt-0.11.0/tests/mod.rs000064400000000000000000000066611046102023000135270ustar 00000000000000use scrypt::{scrypt, Params}; #[cfg(feature = "simple")] use { password_hash::{PasswordHash, PasswordVerifier}, scrypt::Scrypt, }; struct Test { password: &'static str, salt: &'static str, log_n: u8, r: u32, p: u32, expected: Vec, } // Test vectors from [1]. The last test vector is omitted because it takes // too long to run. fn tests() -> Vec { vec![ Test { password: "", salt: "", log_n: 4, r: 1, p: 1, expected: vec![ 0x77, 0xd6, 0x57, 0x62, 0x38, 0x65, 0x7b, 0x20, 0x3b, 0x19, 0xca, 0x42, 0xc1, 0x8a, 0x04, 0x97, 0xf1, 0x6b, 0x48, 0x44, 0xe3, 0x07, 0x4a, 0xe8, 0xdf, 0xdf, 0xfa, 0x3f, 0xed, 0xe2, 0x14, 0x42, 0xfc, 0xd0, 0x06, 0x9d, 0xed, 0x09, 0x48, 0xf8, 0x32, 0x6a, 0x75, 0x3a, 0x0f, 0xc8, 0x1f, 0x17, 0xe8, 0xd3, 0xe0, 0xfb, 0x2e, 0x0d, 0x36, 0x28, 0xcf, 0x35, 0xe2, 0x0c, 0x38, 0xd1, 0x89, 0x06, ], }, Test { password: "password", salt: "NaCl", log_n: 10, r: 8, p: 16, expected: vec![ 0xfd, 0xba, 0xbe, 0x1c, 0x9d, 0x34, 0x72, 0x00, 0x78, 0x56, 0xe7, 0x19, 0x0d, 0x01, 0xe9, 0xfe, 0x7c, 0x6a, 0xd7, 0xcb, 0xc8, 0x23, 0x78, 0x30, 0xe7, 0x73, 0x76, 0x63, 0x4b, 0x37, 0x31, 0x62, 0x2e, 0xaf, 0x30, 0xd9, 0x2e, 0x22, 0xa3, 0x88, 0x6f, 0xf1, 0x09, 0x27, 0x9d, 0x98, 0x30, 0xda, 0xc7, 0x27, 0xaf, 0xb9, 0x4a, 0x83, 0xee, 0x6d, 0x83, 0x60, 0xcb, 0xdf, 0xa2, 0xcc, 0x06, 0x40, ], }, Test { password: "pleaseletmein", salt: "SodiumChloride", log_n: 14, r: 8, p: 1, expected: vec![ 0x70, 0x23, 0xbd, 0xcb, 0x3a, 0xfd, 0x73, 0x48, 0x46, 0x1c, 0x06, 0xcd, 0x81, 0xfd, 0x38, 0xeb, 0xfd, 0xa8, 0xfb, 0xba, 0x90, 0x4f, 0x8e, 0x3e, 0xa9, 0xb5, 0x43, 0xf6, 0x54, 0x5d, 0xa1, 0xf2, 0xd5, 0x43, 0x29, 0x55, 0x61, 0x3f, 0x0f, 0xcf, 0x62, 0xd4, 0x97, 0x05, 0x24, 0x2a, 0x9a, 0xf9, 0xe6, 0x1e, 0x85, 0xdc, 0x0d, 0x65, 0x1e, 0x40, 0xdf, 0xcf, 0x01, 0x7b, 0x45, 0x57, 0x58, 0x87, ], }, ] } #[test] fn test_scrypt() { let tests = tests(); for t in tests.iter() { let mut result = vec![0u8; t.expected.len()]; let params = Params::new(t.log_n, t.r, t.p, t.expected.len()).unwrap(); scrypt( t.password.as_bytes(), t.salt.as_bytes(), ¶ms, &mut result, ) .unwrap(); assert!(result == t.expected); } } /// Test vector from passlib: /// #[cfg(feature = "simple")] const EXAMPLE_PASSWORD_HASH: &str = "$scrypt$ln=16,r=8,p=1$aM15713r3Xsvxbi31lqr1Q$nFNh2CVHVjNldFVKDHDlm4CbdRSCdEBsjjJxD+iCs5E"; #[cfg(feature = "simple")] #[test] fn simple_verify_password() { let password = "password"; let hash = PasswordHash::new(EXAMPLE_PASSWORD_HASH).unwrap(); assert_eq!(Scrypt.verify_password(password.as_bytes(), &hash), Ok(())); } #[cfg(feature = "simple")] #[test] fn simple_reject_incorrect_password() { let hash = PasswordHash::new(EXAMPLE_PASSWORD_HASH).unwrap(); assert!(Scrypt.verify_password(b"invalid", &hash).is_err()); }