bcrypt-pbkdf-0.10.0/.cargo_vcs_info.json0000644000000001520000000000100134770ustar { "git": { "sha1": "0afb60ffcf1014faca3175cb9e38f862b2e2e0e9" }, "path_in_vcs": "bcrypt-pbkdf" }bcrypt-pbkdf-0.10.0/CHANGELOG.md000064400000000000000000000060501046102023000141030ustar 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.0 (2023-03-04) ### Added - Support for `alloc`-free usage ([#372]) ### Changed - Bump `pbkdf2` dependency to v0.12; MSRV 1.60 ([#393]) [#372]: https://github.com/RustCrypto/password-hashes/pull/372 [#393]: https://github.com/RustCrypto/password-hashes/pull/393 ## 0.9.0 (2022-03-18) ### Changed - 2021 edition upgrade ([#284]) - Bump `pbkdf2` dependency to v0.11; MSRV 1.57 ([#291]) [#284]: https://github.com/RustCrypto/password-hashes/pull/284 [#291]: https://github.com/RustCrypto/password-hashes/pull/291 ## 0.8.1 (2022-02-20) ### Changed - Change `passphrase` to be `impl AsRef<[u8]>` allowing non-UTF8 passphrases ([#277]) [#277]: https://github.com/RustCrypto/password-hashes/pull/277 ## 0.8.0 (2022-02-17) ### Changed - Bump `blowfish` dependency to v0.9, edition to 2021, and MSRV to 1.56 ([#273]) [#273]: https://github.com/RustCrypto/password-hashes/pull/273 ## 0.7.2 (2021-11-25) ### Changed - Bump `sha2` and `pbkdf2` dependencies to v0.10 ([#254]) [#254]: https://github.com/RustCrypto/password-hashes/pull/254 ## 0.7.1 (2021-08-27) ### Changed - Bump `pbkdf2` dependency to v0.9 ([#223]) [#223]: https://github.com/RustCrypto/password-hashes/pull/223 ## 0.7.0 (2021-08-27) [YANKED] ### Changed - Relax `zeroize` requirements ([#195]) - Use `resolver = "2"`; MSRV 1.51+ ([#220]) [#195]: https://github.com/RustCrypto/password-hashes/pull/195 [#220]: https://github.com/RustCrypto/password-hashes/pull/220 ## 0.6.2 (2021-07-20) ### Changed - Pin `zeroize` dependency to v1.3 ([#190]) [#190]: https://github.com/RustCrypto/password-hashes/pull/190 ## 0.6.1 (2021-05-04) ### Changed - Bump `blowfish` dependency to v0.8 ([#171]) [#171]: https://github.com/RustCrypto/password-hashing/pull/171 ## 0.6.0 (2021-04-29) [YANKED] ### Changed - Bump `crypto-mac` dependency to v0.11 ([#165]) - Bump `pbkdf2` to v0.8 ([#167]) [#165]: https://github.com/RustCrypto/password-hashing/pull/165 [#167]: https://github.com/RustCrypto/password-hashing/pull/167 ## 0.5.0 (2021-01-29) ### Changed - Bump `pbkdf2` dependency to v0.7 ([#102]) [#102]: https://github.com/RustCrypto/password-hashing/pull/102 ## 0.4.0 (2020-10-18) ### Changed - Bump `crypto-mac` dependency to v0.10 ([#58]) - Bump `pbkdf2` dependency to v0.10 ([#61]) [#61]: https://github.com/RustCrypto/password-hashing/pull/61 [#58]: https://github.com/RustCrypto/password-hashing/pull/58 ## 0.3.0 (2020-08-18) ### Changed - Bump `crypto-mac` dependency to v0.9, `blowfish` to v0.6, and `pbkdf2` to v0.5 ([#46]) [#46]: https://github.com/RustCrypto/password-hashing/pull/46 ## 0.2.1 (2020-06-03) ### Added - `no_std` support ([#41]) [#41]: https://github.com/RustCrypto/password-hashing/pull/41 ## 0.2.0 (2020-05-13) ### Changed - Update dependencies to `sha2 v0.9`, `pbkdf2 v0.4`, `blowfish v0.5`, and `crypto-mac v0.8` ## 0.1.0 (2020-01-03) - Initial release bcrypt-pbkdf-0.10.0/Cargo.toml0000644000000025470000000000100115070ustar # 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 = "bcrypt-pbkdf" version = "0.10.0" authors = ["RustCrypto Developers"] description = "bcrypt-pbkdf password-based key derivation function" documentation = "https://docs.rs/bcrypt-pbkdf" 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/bcrypt-pbkdf" [dependencies.blowfish] version = "0.9.1" features = ["bcrypt"] [dependencies.pbkdf2] version = "0.12" default-features = false [dependencies.sha2] version = "0.10.5" default-features = false [dependencies.zeroize] version = "1" optional = true default-features = false [dev-dependencies.hex-literal] version = "0.3.3" [features] alloc = [] default = [ "alloc", "std", ] std = [] bcrypt-pbkdf-0.10.0/Cargo.toml.orig000064400000000000000000000015401046102023000151600ustar 00000000000000[package] name = "bcrypt-pbkdf" version = "0.10.0" description = "bcrypt-pbkdf password-based key derivation function" authors = ["RustCrypto Developers"] license = "MIT OR Apache-2.0" readme = "README.md" documentation = "https://docs.rs/bcrypt-pbkdf" repository = "https://github.com/RustCrypto/password-hashes/tree/master/bcrypt-pbkdf" keywords = ["crypto", "hashing", "password", "phf"] categories = ["authentication", "cryptography", "no-std"] edition = "2021" rust-version = "1.60" [dependencies] blowfish = { version = "0.9.1", features = ["bcrypt"] } pbkdf2 = { version = "0.12", default-features = false, path = "../pbkdf2" } sha2 = { version = "0.10.5", default-features = false } zeroize = { version = "1", default-features = false, optional = true } [dev-dependencies] hex-literal = "0.3.3" [features] default = ["alloc", "std"] alloc = [] std = [] bcrypt-pbkdf-0.10.0/LICENSE-APACHE000064400000000000000000000251401046102023000142170ustar 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. bcrypt-pbkdf-0.10.0/LICENSE-MIT000064400000000000000000000021301046102023000137210ustar 00000000000000Copyright (c) 2019 Jack Grigg Copyright (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. bcrypt-pbkdf-0.10.0/README.md000064400000000000000000000040301046102023000135450ustar 00000000000000# RustCrypto: bcrypt-pbkdf [![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 [`bcrypt_pbkdf`] password-based key derivation function, a custom derivative of PBKDF2 [used in OpenSSH]. [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/bcrypt-pbkdf [crate-link]: https://crates.io/crates/bcrypt-pbkdf [docs-image]: https://docs.rs/bcrypt-pbkdf/badge.svg [docs-link]: https://docs.rs/bcrypt-pbkdf/ [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/bcrypt-pbkdf/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/password-hashes/actions?query=workflow%3Abcrypt-pbkdf [//]: # (links) [`bcrypt_pbkdf`]: https://flak.tedunangst.com/post/bcrypt-pbkdf [used in OpenSSH]: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf bcrypt-pbkdf-0.10.0/src/errors.rs000064400000000000000000000016001046102023000147370ustar 00000000000000use core::fmt; /// `bcrypt_pbkdf` error #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { /// An input parameter has an invalid length. InvalidParamLen, /// An invalid number of rounds was specified. InvalidRounds, /// The output parameter has an invalid length. InvalidOutputLen, /// The manually provided memory was not long enough. InvalidMemoryLen, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::InvalidParamLen => write!(f, "Invalid parameter length"), Error::InvalidRounds => write!(f, "Invalid number of rounds"), Error::InvalidOutputLen => write!(f, "Invalid output length"), Error::InvalidMemoryLen => write!(f, "Invalid memory length"), } } } #[cfg(feature = "std")] impl std::error::Error for Error {} bcrypt-pbkdf-0.10.0/src/lib.rs000064400000000000000000000175321046102023000142040ustar 00000000000000//! This crate implements [bcrypt_pbkdf], a custom derivative of PBKDF2 used in //! [OpenSSH]. //! //! [bcrypt_pbkdf]: https://flak.tedunangst.com/post/bcrypt-pbkdf //! [OpenSSH]: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf #![no_std] #![doc = include_str!("../README.md")] #![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" )] #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "std")] extern crate std; mod errors; pub use errors::Error; use blowfish::Blowfish; use sha2::{ digest::{ crypto_common::{Key, KeyInit, KeySizeUser}, generic_array::typenum::U32, FixedOutput, MacMarker, Output, OutputSizeUser, Update, }, Digest, Sha512, }; #[cfg(feature = "zeroize")] use zeroize::Zeroize; const BHASH_WORDS: usize = 8; const BHASH_OUTPUT_SIZE: usize = BHASH_WORDS * 4; const BHASH_SEED: &[u8; BHASH_OUTPUT_SIZE] = b"OxychromaticBlowfishSwatDynamite"; fn bhash(sha2_pass: &Output, sha2_salt: &Output) -> Output { let mut blowfish = Blowfish::bc_init_state(); blowfish.salted_expand_key(sha2_salt, sha2_pass); for _ in 0..64 { blowfish.bc_expand_key(sha2_salt); blowfish.bc_expand_key(sha2_pass); } let mut cdata = [0u32; BHASH_WORDS]; for i in 0..BHASH_WORDS { cdata[i] = u32::from_be_bytes(BHASH_SEED[i * 4..(i + 1) * 4].try_into().unwrap()); } for _ in 0..64 { for i in (0..BHASH_WORDS).step_by(2) { let [l, r] = blowfish.bc_encrypt([cdata[i], cdata[i + 1]]); cdata[i] = l; cdata[i + 1] = r; } } let mut output = Output::::default(); for i in 0..BHASH_WORDS { output[i * 4..(i + 1) * 4].copy_from_slice(&cdata[i].to_le_bytes()); } output } #[derive(Clone)] struct Bhash { sha2_pass: Output, salt: Sha512, } impl MacMarker for Bhash {} impl KeySizeUser for Bhash { type KeySize = ::OutputSize; } impl KeyInit for Bhash { fn new(key: &Key) -> Self { Bhash { sha2_pass: *key, salt: Sha512::default(), } } } impl Update for Bhash { fn update(&mut self, data: &[u8]) { Update::update(&mut self.salt, data); } } impl OutputSizeUser for Bhash { type OutputSize = U32; } impl FixedOutput for Bhash { fn finalize_into(mut self, out: &mut Output) { *out = bhash(&self.sha2_pass, &self.salt.finalize_reset()); } } #[cfg(feature = "zeroize")] impl Drop for Bhash { fn drop(&mut self) { self.sha2_pass.zeroize(); } } /// The bcrypt_pbkdf function. /// /// # Arguments /// - `passphrase` - The passphrase to process. /// - `salt` - The salt value to use as a byte vector. /// - `rounds` - The number of rounds to apply. /// - `output` - The resulting derived key is returned in this byte vector. /// /// # Returns /// - `Ok(())` if everything is fine. /// - `Err(Error::InvalidParamLen)` if `passphrase.is_empty() || salt.is_empty()`. /// - `Err(Error::InvalidRounds)` if `rounds == 0`. /// - `Err(Error::InvalidOutputLen)` if `output.is_empty() || output.len() > 1024`. #[cfg(feature = "alloc")] pub fn bcrypt_pbkdf( passphrase: impl AsRef<[u8]>, salt: &[u8], rounds: u32, output: &mut [u8], ) -> Result<(), Error> { /// number of strides which will be processed on stack const STACK_STRIDE: usize = 8; // Allocate a Vec large enough to hold the output we require. let stride = (output.len() + BHASH_OUTPUT_SIZE - 1) / BHASH_OUTPUT_SIZE; let mut vec_buf; let mut stack_buf = [0u8; STACK_STRIDE * BHASH_OUTPUT_SIZE]; let generated = if stride > STACK_STRIDE { vec_buf = alloc::vec![0u8; stride * BHASH_OUTPUT_SIZE]; &mut vec_buf[..] } else { &mut stack_buf[..stride * BHASH_OUTPUT_SIZE] }; bcrypt_pbkdf_with_memory(passphrase, salt, rounds, output, generated) } /// Like [`bcrypt_pbkdf`], but usable on "heapless" targets. /// /// # Arguments /// - `passphrase` - The passphrase to process. /// - `salt` - The salt value to use as a byte vector. /// - `rounds` - The number of rounds to apply. /// - `output` - The resulting derived key is returned in this byte vector. /// - `memory` - Buffer space used for internal computation. /// /// # Returns /// - `Ok(())` if everything is fine. /// - `Err(Error::InvalidParamLen)` if `passphrase.is_empty() || salt.is_empty()`. /// - `Err(Error::InvalidRounds)` if `rounds == 0`. /// - `Err(Error::InvalidOutputLen)` if `output.is_empty() || output.len() > 1024`. /// - `Err(Error::InvalidMemoryLen)` if `memory.len() < (output.len() + 32 - 1) / 32 * 32`, i.e. /// `output.len()` rounded up to the nearest multiple of 32. pub fn bcrypt_pbkdf_with_memory( passphrase: impl AsRef<[u8]>, salt: &[u8], rounds: u32, output: &mut [u8], memory: &mut [u8], ) -> Result<(), Error> { let stride = (output.len() + BHASH_OUTPUT_SIZE - 1) / BHASH_OUTPUT_SIZE; // Validate inputs in same way as OpenSSH implementation let passphrase = passphrase.as_ref(); if passphrase.is_empty() || salt.is_empty() { return Err(errors::Error::InvalidParamLen); } else if rounds == 0 { return Err(errors::Error::InvalidRounds); } else if output.is_empty() || output.len() > BHASH_OUTPUT_SIZE * BHASH_OUTPUT_SIZE { return Err(errors::Error::InvalidOutputLen); } else if memory.len() < stride * BHASH_OUTPUT_SIZE { return Err(errors::Error::InvalidMemoryLen); } // Run the regular PBKDF2 algorithm with bhash as the PRF. pbkdf2::pbkdf2::(&Sha512::digest(passphrase), salt, rounds, memory) .expect("Bhash can be initialized with any key length"); // Apply the bcrypt_pbkdf non-linear transformation on the output. for (i, out_byte) in output.iter_mut().enumerate() { let chunk_num = i % stride; let chunk_index = i / stride; *out_byte = memory[chunk_num * BHASH_OUTPUT_SIZE + chunk_index]; } Ok(()) } #[cfg(test)] mod test { use super::bhash; use hex_literal::hex; use sha2::digest::generic_array::GenericArray; #[test] fn test_bhash() { struct Test { hpass: [u8; 64], hsalt: [u8; 64], out: [u8; 32], } const TEST_VAL: [u8; 64] = hex!( "000102030405060708090a0b0c0d0e0f" "101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f" "303132333435363738393a3b3c3d3e3f" ); let tests = [ Test { hpass: [0; 64], hsalt: [0; 64], out: hex!( "460286e972fa833f8b1283ad8fa919fa" "29bde20e23329e774d8422bac0a7926c" ), }, Test { hpass: TEST_VAL, hsalt: [0; 64], out: hex!( "b0b229dbc6badef0e1da2527474a8b28" "888f8b061476fe80c32256e1142dd00d" ), }, Test { hpass: [0; 64], hsalt: TEST_VAL, out: hex!( "b62b4e367d3157f5c31e4d2cbafb2931" "494d9d3bdd171d55cf799fa4416042e2" ), }, Test { hpass: TEST_VAL, hsalt: TEST_VAL, out: hex!( "c6a95fe6413115fb57e99f757498e85d" "a3c6e1df0c3c93aa975c548a344326f8" ), }, ]; for t in tests.iter() { let hpass = GenericArray::from_slice(&t.hpass); let hsalt = GenericArray::from_slice(&t.hsalt); let out = bhash(hpass, hsalt); assert_eq!(out[..], t.out[..]); } } } bcrypt-pbkdf-0.10.0/tests/test_vectors.rs000064400000000000000000000074701046102023000165350ustar 00000000000000extern crate bcrypt_pbkdf; use bcrypt_pbkdf::bcrypt_pbkdf_with_memory; #[test] fn test_openbsd_vectors() { struct Test { password: &'static str, salt: Vec, rounds: u32, out: Vec, } let tests = vec!( Test{ password: "password", salt: b"salt".to_vec(), rounds: 4, out: vec![ 0x5b, 0xbf, 0x0c, 0xc2, 0x93, 0x58, 0x7f, 0x1c, 0x36, 0x35, 0x55, 0x5c, 0x27, 0x79, 0x65, 0x98, 0xd4, 0x7e, 0x57, 0x90, 0x71, 0xbf, 0x42, 0x7e, 0x9d, 0x8f, 0xbe, 0x84, 0x2a, 0xba, 0x34, 0xd9], }, Test{ password: "password", salt: vec![0], rounds: 4, out: vec![0xc1, 0x2b, 0x56, 0x62, 0x35, 0xee, 0xe0, 0x4c, 0x21, 0x25, 0x98, 0x97, 0x0a, 0x57, 0x9a, 0x67], }, Test{ password: "\x00", salt: b"salt".to_vec(), rounds: 4, out: vec![0x60, 0x51, 0xbe, 0x18, 0xc2, 0xf4, 0xf8, 0x2c, 0xbf, 0x0e, 0xfe, 0xe5, 0x47, 0x1b, 0x4b, 0xb9], }, Test{ password: "password\x00", salt: b"salt\x00".to_vec(), rounds: 4, out: vec![ 0x74, 0x10, 0xe4, 0x4c, 0xf4, 0xfa, 0x07, 0xbf, 0xaa, 0xc8, 0xa9, 0x28, 0xb1, 0x72, 0x7f, 0xac, 0x00, 0x13, 0x75, 0xe7, 0xbf, 0x73, 0x84, 0x37, 0x0f, 0x48, 0xef, 0xd1, 0x21, 0x74, 0x30, 0x50], }, Test{ password: "pass\x00wor", salt: b"sa\x00l".to_vec(), rounds: 4, out: vec![0xc2, 0xbf, 0xfd, 0x9d, 0xb3, 0x8f, 0x65, 0x69, 0xef, 0xef, 0x43, 0x72, 0xf4, 0xde, 0x83, 0xc0], }, Test{ password: "pass\x00word", salt: b"sa\x00lt".to_vec(), rounds: 4, out: vec![0x4b, 0xa4, 0xac, 0x39, 0x25, 0xc0, 0xe8, 0xd7, 0xf0, 0xcd, 0xb6, 0xbb, 0x16, 0x84, 0xa5, 0x6f], }, Test{ password: "password", salt: b"salt".to_vec(), rounds: 8, out: vec![ 0xe1, 0x36, 0x7e, 0xc5, 0x15, 0x1a, 0x33, 0xfa, 0xac, 0x4c, 0xc1, 0xc1, 0x44, 0xcd, 0x23, 0xfa, 0x15, 0xd5, 0x54, 0x84, 0x93, 0xec, 0xc9, 0x9b, 0x9b, 0x5d, 0x9c, 0x0d, 0x3b, 0x27, 0xbe, 0xc7, 0x62, 0x27, 0xea, 0x66, 0x08, 0x8b, 0x84, 0x9b, 0x20, 0xab, 0x7a, 0xa4, 0x78, 0x01, 0x02, 0x46, 0xe7, 0x4b, 0xba, 0x51, 0x72, 0x3f, 0xef, 0xa9, 0xf9, 0x47, 0x4d, 0x65, 0x08, 0x84, 0x5e, 0x8d], }, Test{ password: "password", salt: b"salt".to_vec(), rounds: 42, out: vec![0x83, 0x3c, 0xf0, 0xdc, 0xf5, 0x6d, 0xb6, 0x56, 0x08, 0xe8, 0xf0, 0xdc, 0x0c, 0xe8, 0x82, 0xbd], }, Test{ password: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", salt: b"salis\x00".to_vec(), rounds: 8, out: vec![0x10, 0x97, 0x8b, 0x07, 0x25, 0x3d, 0xf5, 0x7f, 0x71, 0xa1, 0x62, 0xeb, 0x0e, 0x8a, 0xd3, 0x0a], }, ); for t in tests.iter() { let mut out = vec![0; t.out.len()]; let mut memory = vec![0; (t.out.len() + 32 - 1) / 32 * 32]; bcrypt_pbkdf_with_memory(t.password, &t.salt[..], t.rounds, &mut out, &mut memory).unwrap(); assert_eq!(out, t.out); } }