Skip to content

add MD5 crypt #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions .github/workflows/md5-crypt.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: md5-crypt

on:
pull_request:
paths:
- "md5-crypt/**"
- "Cargo.*"
push:
branches: master

defaults:
run:
working-directory: md5-crypt

env:
CARGO_INCREMENTAL: 0
RUSTFLAGS: "-Dwarnings"

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
rust:
- 1.56.0 # MSRV
- stable
target:
- thumbv7em-none-eabi
- wasm32-unknown-unknown
steps:
- uses: actions/checkout@v3
- uses: RustCrypto/actions/cargo-cache@master
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
target: ${{ matrix.target }}
override: true
- run: cargo build --target ${{ matrix.target }} --no-default-features

minimal-versions:
uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master
with:
working-directory: ${{ github.workflow }}

test:
runs-on: ubuntu-latest
strategy:
matrix:
rust:
- 1.56.0 # MSRV
- stable
steps:
- uses: actions/checkout@v3
- uses: RustCrypto/actions/cargo-cache@master
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true
- run: cargo test --no-default-features
- run: cargo test
- run: cargo test --all-features
23 changes: 21 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ members = [
"argon2",
"balloon-hash",
"bcrypt-pbkdf",
"md5-crypt",
"pbkdf2",
"scrypt",
"sha-crypt"
9 changes: 9 additions & 0 deletions md5-crypt/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 0.1.0 (2022-10-17)
- Initial release
33 changes: 33 additions & 0 deletions md5-crypt/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[package]
name = "md5-crypt"
version = "0.1.0"
description = """
Pure Rust implementation of the MD5-crypt password hash as implemented by the
POSIX crypt C library
"""
authors = ["RustCrypto Developers"]
license = "MIT OR Apache-2.0"
documentation = "https://docs.rs/md5-crypt"
repository = "https://github.com/RustCrypto/password-hashes/tree/master/md5-crypt"
categories = ["cryptography", "no-std"]
keywords = ["crypto", "password", "hashing"]
readme = "README.md"
edition = "2021"
rust-version = "1.56"

[dependencies]

# optional dependencies
rand = { version = "0.8", optional = true }
subtle = { version = ">=2, <2.5", optional = true, default-features = false }
base64ct = "1.5.3"
md-5 = { version = "0.10.5", default-features = false }

[features]
default = ["simple"]
alloc = []
simple = ["alloc", "rand", "subtle"]

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
201 changes: 201 additions & 0 deletions md5-crypt/LICENSE-APACHE
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
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.
25 changes: 25 additions & 0 deletions md5-crypt/LICENSE-MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) 2021 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.
61 changes: 61 additions & 0 deletions md5-crypt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# RustCrypto: md5-crypt password hash

[![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]

Pure Rust implementation of the MD5-crypt password hash based on MD5,
a legacy password hashing scheme supported by the [POSIX crypt C library][1].

Password hashes using this algorithm start with `$1$` when encoded using the
[PHC string format][2].

[Documentation][docs-link]

## 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/md5-crypt.svg
[crate-link]: https://crates.io/crates/md5-crypt
[docs-image]: https://docs.rs/md5-crypt/badge.svg
[docs-link]: https://docs.rs/md5-crypt/
[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/260046-password-hashes
[build-image]: https://github.com/RustCrypto/password-hashes/workflows/md5-crypt/badge.svg?branch=master&event=push
[build-link]: https://github.com/RustCrypto/password-hashes/actions?query=workflow%3Amd5-crypt

[//]: # (general links)

[1]: https://en.wikipedia.org/wiki/Crypt_(C)
[2]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
44 changes: 44 additions & 0 deletions md5-crypt/src/b64.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//! Base64 encoding support
use crate::defs::{BLOCK_SIZE, MAP_MD5, PW_SIZE_MD5};
#[cfg(any(feature = "subtle", test))]
use crate::errors::DecodeError;
use base64ct::{Base64ShaCrypt, Encoding};

pub fn encode_md5(source: &[u8]) -> [u8; PW_SIZE_MD5] {
let mut transposed = [0u8; BLOCK_SIZE];
for (i, &ti) in MAP_MD5.iter().enumerate() {
transposed[i] = source[ti as usize];
}
let mut buf = [0u8; PW_SIZE_MD5];
Base64ShaCrypt::encode(&transposed, &mut buf).unwrap();
buf
}

#[cfg(any(feature = "subtle", test))]
pub fn decode_md5(source: &[u8]) -> Result<[u8; BLOCK_SIZE], DecodeError> {
let mut buf = [0u8; PW_SIZE_MD5];
Base64ShaCrypt::decode(source, &mut buf).map_err(|_| DecodeError)?;
let mut transposed = [0u8; BLOCK_SIZE];
for (i, &ti) in MAP_MD5.iter().enumerate() {
transposed[ti as usize] = buf[i];
}
Ok(transposed)
}

mod tests {
#[test]
fn test_encode_decode_md5() {
let original: [u8; 16] = [
0x0b, 0x5b, 0xdf, 0x7d, 0x92, 0xe2, 0xfc, 0xbd, 0xab, 0x57, 0xcb, 0xf3, 0xe0, 0x03,
0x16, 0x62,
];

let e = super::encode_md5(&original);
let d = super::decode_md5(&e).unwrap();

for i in 0..d.len() {
assert_eq!(&original[i], &d[i]);
}
}
}
15 changes: 15 additions & 0 deletions md5-crypt/src/defs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/// Block size for MD5
pub const BLOCK_SIZE: usize = 16;

/// PWD part length of the password string
pub const PW_SIZE_MD5: usize = 22;

/// Maximum length of a salt
pub const SALT_MAX_LEN: usize = 8;

/// Encoding table.
#[cfg(feature = "simple")]
pub static TAB: &[u8] = b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

/// Inverse encoding map for MD5.
pub const MAP_MD5: [u8; BLOCK_SIZE] = [12, 6, 0, 13, 7, 1, 14, 8, 2, 15, 9, 3, 5, 10, 4, 11];
42 changes: 42 additions & 0 deletions md5-crypt/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//! Error types.
#[cfg(feature = "alloc")]
use alloc::string;

/// Error type.
#[derive(Debug)]
pub enum CryptError {
/// RNG failed.
RandomError,

/// UTF-8 error.
#[cfg(feature = "alloc")]
StringError(string::FromUtf8Error),
}

#[cfg(feature = "alloc")]
impl From<string::FromUtf8Error> for CryptError {
fn from(e: string::FromUtf8Error) -> Self {
CryptError::StringError(e)
}
}

#[derive(Debug)]
pub enum CheckError {
InvalidFormat(&'static str),
#[cfg(feature = "subtle")]
Crypt(CryptError),
#[cfg(feature = "subtle")]
HashMismatch,
}

/// Decoding errors.
#[cfg_attr(docsrs, doc(cfg(feature = "simple")))]
#[derive(Debug)]
pub struct DecodeError;

impl From<DecodeError> for CheckError {
fn from(_: DecodeError) -> CheckError {
CheckError::InvalidFormat("invalid B64")
}
}
263 changes: 263 additions & 0 deletions md5-crypt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
//! Pure Rust implementation of the `MD5-crypt` password hash based on md5,
//! a legacy password hashing scheme supported by the [POSIX crypt C library][1].
//!
//! Password hashes using this algorithm start with `$1$` when encoded using the
//! [PHC string format][2].
//!
//! # Usage
//!
//! ```
//! # #[cfg(feature = "simple")]
//! # {
//! use md5_crypt::{md5_simple, md5_check};
//!
//! // Hash the password for storage
//! let hashed_password = md5_simple("Not so secure password")
//! .expect("Should not fail");
//!
//! // Verifying a stored password
//! assert!(md5_check("Not so secure password", &hashed_password).is_ok());
//! # }
//! ```
//!
//! [1]: https://en.wikipedia.org/wiki/Crypt_(C)
//! [2]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
#![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"
)]
#![deny(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms)]

// TODO(tarcieri): heapless support
#[cfg(feature = "alloc")]
extern crate alloc;

mod b64;
mod defs;
mod errors;

pub use crate::{
defs::{BLOCK_SIZE, PW_SIZE_MD5, SALT_MAX_LEN},
errors::CryptError,
};

use md5::{Digest, Md5};

#[cfg(feature = "subtle")]
use crate::errors::CheckError;

#[cfg(feature = "simple")]
use {
crate::defs::TAB,
alloc::string::String,
rand::{distributions::Distribution, thread_rng, Rng},
};

static MD5_SALT_PREFIX: &str = "$1$";

/// The MD5 crypt function returned as byte vector
///
/// If the provided hash is longer than defs::SALT_MAX_LEN character, it will
/// be stripped down to defs::SALT_MAX_LEN characters.
///
/// # Arguments
/// - `password` - The password to process as a byte vector
/// - `salt` - The salt value to use as a byte vector
/// **WARNING: Make sure to compare this value in constant time!**
///
/// # Returns
/// - `Ok(())` if calculation was successful
/// - `Err(errors::CryptError)` otherwise
pub fn md5_crypt(password: &[u8], salt: &[u8]) -> Result<[u8; BLOCK_SIZE], CryptError> {
let salt_len = salt.len();
let salt = match salt_len {
0..=SALT_MAX_LEN => &salt[0..salt_len],
_ => &salt[0..SALT_MAX_LEN],
};

let mut digest_b = Md5::default();
digest_b.update(password);
digest_b.update(salt);
digest_b.update(password);
let hash_b = digest_b.finalize();

let mut digest_a = Md5::default();
digest_a.update(password);
digest_a.update(MD5_SALT_PREFIX);
digest_a.update(salt);

let mut pw_len = password.len();
let rounds = pw_len / BLOCK_SIZE;
for _ in 0..rounds {
digest_a.update(hash_b);
}

// leftover password
digest_a.update(&hash_b[..(pw_len - rounds * BLOCK_SIZE)]);

while pw_len > 0 {
match pw_len & 1 {
0 => digest_a.update(&password[..1]),
1 => digest_a.update([0u8]),
_ => unreachable!(),
}
pw_len >>= 1;
}

let mut hash_a = digest_a.finalize();

// Repeatedly run the collected hash value through MD5 to burn
// CPU cycles
for i in 0..1000_usize {
// new hasher
let mut hasher = Md5::default();

// Add key or last result
if (i & 1) != 0 {
hasher.update(password);
} else {
hasher.update(hash_a);
}

// Add salt for numbers not divisible by 3
if i % 3 != 0 {
hasher.update(salt);
}

// Add key for numbers not divisible by 7
if i % 7 != 0 {
hasher.update(password);
}

// Add key or last result
if (i & 1) != 0 {
hasher.update(hash_a);
} else {
hasher.update(password);
}

// digest_c.clone_from_slice(&hasher.finalize());
hash_a = hasher.finalize();
}

Ok(hash_a.into())
}

/// Same as md5_crypt except base64 representation will be returned.
///
/// # Arguments
/// - `password` - The password to process as a byte vector
/// - `salt` - The salt value to use as a byte vector
/// **WARNING: Make sure to compare this value in constant time!**
///
/// # Returns
/// - `Ok(())` if calculation was successful
/// - `Err(errors::CryptError)` otherwise
pub fn md5_crypt_b64(password: &[u8], salt: &[u8]) -> Result<[u8; PW_SIZE_MD5], CryptError> {
let output = md5_crypt(password, salt)?;
Ok(b64::encode_md5(&output))
}

/// Simple interface for generating a MD5 password hash.
///
/// The salt will be chosen randomly.
///
/// `$<ID>$<SALT>$<HASH>`
///
/// # Returns
/// - `Ok(String)` containing the full MD5 password hash format on success
/// - `Err(CryptError)` if something went wrong.
#[cfg(feature = "simple")]
#[cfg_attr(docsrs, doc(cfg(feature = "simple")))]
pub fn md5_simple(password: &str) -> Result<String, CryptError> {
let rng = thread_rng();

let salt: String = rng
.sample_iter(&Md5CryptDistribution)
.take(SALT_MAX_LEN)
.collect();

let out = md5_crypt(password.as_bytes(), salt.as_bytes())?;

let mut result = String::new();
result.push_str(MD5_SALT_PREFIX);
result.push_str(&salt);
result.push('$');
let s = String::from_utf8(b64::encode_md5(&out).to_vec())?;
result.push_str(&s);
Ok(result)
}

/// Checks that given password matches provided hash.
///
/// # Arguments
/// - `password` - expected password
/// - `hashed_value` - the hashed value which should be used for checking,
/// should be of format mentioned `$1$<SALT>$<PWD>`.
///
/// # Return
/// `OK(())` if password matches otherwise Err(CheckError) in case of invalid
/// format or password mismatch.
#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "simple")))]
pub fn md5_check(password: &str, hashed_value: &str) -> Result<(), CheckError> {
let mut iter = hashed_value.split('$');

// Check that there are no characters before the first "$"
if iter.next() != Some("") {
return Err(CheckError::InvalidFormat("Should start with '$"));
}

if iter.next() != Some("1") {
return Err(CheckError::InvalidFormat(
"does not contain MD5 identifier: '$1$'",
));
}

let next = iter.next().ok_or(CheckError::InvalidFormat(
"Does not contain a salt or hash string",
))?;

let salt = next;

let hash = iter
.next()
.ok_or(CheckError::InvalidFormat("Does not contain a hash string"))?;

// Make sure there is no trailing data after the final "$"
if iter.next().is_some() {
return Err(CheckError::InvalidFormat("Trailing characters present"));
}

let output = md5_crypt(password.as_bytes(), salt.as_bytes()).map_err(CheckError::Crypt)?;

let hash = b64::decode_md5(hash.as_bytes())?;

use subtle::ConstantTimeEq;
if output.ct_eq(&hash).into() {
Ok(())
} else {
Err(CheckError::HashMismatch)
}
}

#[cfg(feature = "simple")]
#[derive(Debug)]
struct Md5CryptDistribution;

#[cfg(feature = "simple")]
impl Distribution<char> for Md5CryptDistribution {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
const RANGE: u32 = 26 + 26 + 10 + 2; // 2 == "./"
loop {
let var = rng.next_u32() >> (32 - 6);
if var < RANGE {
return TAB[var as usize] as char;
}
}
}
}
132 changes: 132 additions & 0 deletions md5-crypt/tests/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
use md5_crypt::md5_crypt_b64;

#[cfg(feature = "simple")]
use md5_crypt::{md5_check, md5_simple};

use std::str;

struct TestVector {
input: &'static str,
salt: &'static str,
result: &'static str,
}

const TEST_VECTORS: &[TestVector] = &[
TestVector {
input: "",
salt: "salt",
result: "UsdFqFVB.FsuinRDK5eE..",
},
TestVector {
input: "abc",
salt: "salt",
result: "Ix0K7gMcCieLMZGthf6yT1",
},
TestVector {
input: "Hello world!",
salt: "salt",
result: "wa8aFuC3rkp5bjoBIGTc41",
},
TestVector {
input: "Hello world!",
salt: "saltsalt",
result: "le8lFSqqnPaRFOlmAZpvH1",
},
TestVector {
input: "This is just a test",
salt: "saltsalt",
result: "GG3.Tf92SRQMW0mClBXo..",
},
// 63 length password
TestVector {
input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
salt: "kf8.jB3Z",
result: "UZFByQYndkZGAc9kqF4A21",
},
// 64 length password
TestVector {
input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // 64 length
salt: "kf8.jB3Z",
result: ".XRGr/PlZPFr11frOZsYQ0",
},
// 65 length password
TestVector {
input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // 65 length
salt: "kf8.jB3Z",
result: "xErCjUcXBWx7JNSY/bdJM1",
},
// 127 length password
TestVector {
input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
salt: "kf8.jB3Z",
result: "ay9BDuVT.pV2B.EX6V4HC1",
},
// 128 length password
TestVector {
input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
salt: "kf8.jB3Z",
result: "kZ6Ws32gDHOGf1DEqpBUq.",
},
// 129 length password
TestVector {
input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
salt: "kf8.jB3Z",
result: "5hc1Ea4UM8OzOhdb2/WvW0",
},
];

#[test]
fn test_md5_crypt() {
for t in TEST_VECTORS {
let result_array = md5_crypt_b64(t.input.as_bytes(), t.salt.as_bytes()).unwrap();
let result = str::from_utf8(&result_array).unwrap();
assert!(result == t.result);
}
}

#[cfg(feature = "simple")]
#[test]
fn test_md5_check() {
let pw = "foobar";
let s = "$1$NoaSCTUg$j91ZS4vEeaHDdpecPbzkY0";
assert!(md5_check(pw, s).is_ok());
}

#[cfg(feature = "simple")]
#[test]
fn test_md5_simple_check_roundtrip() {
let pw = "this is my password";

let r = md5_simple(&pw);
assert!(r.is_ok());
let hash = r.unwrap();

let c_r = md5_check(&pw, &hash);
assert!(c_r.is_ok());
}

#[cfg(feature = "simple")]
#[test]
fn test_md5_unexpected_prefix() {
let pw = "foobar";
let s = "SHOULDNOTBEHERE$1$WtWGiGnH$Ryci5v8qFuzlfj25Yye97";
assert!(!md5_check(pw, s).is_ok());
}

#[cfg(feature = "simple")]
#[test]
fn test_md5_wrong_id() {
// wrong id '2'
let pw = "foobar";
let s = "$2$WtWGiGnH$Ryci5v8qFuzlfj25Yye97";
assert!(!md5_check(pw, s).is_ok());
}

#[cfg(feature = "simple")]
#[test]
fn test_md5_missing_trailing_slash() {
// Missing trailing slash
let pw = "abc";
let s = "$1$/dUAwECj$E7lsyZl3NQqTePIPi4/42";
assert!(!md5_check(pw, s).is_ok());
}