use aes::Aes256;
use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
use des::TdesEde3;
use hmac::{Hmac, Mac};
use md4::{Digest as Md4Digest, Md4};
use sha1::Sha1;
use sha2::{Sha256, Sha512};
pub type HmacSha1 = Hmac<Sha1>;
pub type HmacSha512 = Hmac<Sha512>;
pub fn hmac_sha1(key: &[u8], msg: &[u8]) -> [u8; 20] {
let mut m = <HmacSha1 as Mac>::new_from_slice(key).expect("hmac key");
m.update(msg);
m.finalize().into_bytes().into()
}
pub fn hmac_sha512(key: &[u8], msg: &[u8]) -> [u8; 64] {
let mut m = <HmacSha512 as Mac>::new_from_slice(key).expect("hmac key");
m.update(msg);
m.finalize().into_bytes().into()
}
pub fn md4(data: &[u8]) -> [u8; 16] {
let mut h = Md4::new();
h.update(data);
h.finalize().into()
}
pub fn pbkdf2_sha256(password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
let mut out = vec![0u8; dklen];
let rounds = rounds.max(1);
pbkdf2::pbkdf2_hmac::<Sha256>(password, salt, rounds, &mut out);
out
}
pub fn ms_derive_key(hash: HashAlgo, passphrase: &[u8], salt: &[u8], count: u32, dklen: usize) -> Vec<u8> {
let count = count.max(1);
let mut out = Vec::with_capacity(dklen);
let mut counter: u32 = 1;
while out.len() < dklen {
let mut buf = Vec::with_capacity(salt.len() + 4);
buf.extend_from_slice(salt);
buf.extend_from_slice(&counter.to_be_bytes());
counter += 1;
let mut derived = hash.hmac(passphrase, &buf);
for _ in 0..(count - 1) {
let actual = hash.hmac(passphrase, &derived);
for (d, a) in derived.iter_mut().zip(actual.iter()) {
*d ^= *a;
}
}
out.extend_from_slice(&derived);
}
out.truncate(dklen);
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HashAlgo {
Sha1,
Sha512,
}
impl HashAlgo {
pub fn from_alg_id(id: u32) -> Option<Self> {
match id {
0x8004 => Some(HashAlgo::Sha1),
0x800e => Some(HashAlgo::Sha512),
_ => None,
}
}
pub fn digest_len(self) -> usize {
match self {
HashAlgo::Sha1 => 20,
HashAlgo::Sha512 => 64,
}
}
pub fn block_size(self) -> usize {
match self {
HashAlgo::Sha1 => 64,
HashAlgo::Sha512 => 128,
}
}
pub fn hmac(self, key: &[u8], msg: &[u8]) -> Vec<u8> {
match self {
HashAlgo::Sha1 => hmac_sha1(key, msg).to_vec(),
HashAlgo::Sha512 => hmac_sha512(key, msg).to_vec(),
}
}
pub fn pbkdf2(self, password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
let mut out = vec![0u8; dklen];
let rounds = rounds.max(1);
match self {
HashAlgo::Sha1 => pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, rounds, &mut out),
HashAlgo::Sha512 => pbkdf2::pbkdf2_hmac::<Sha512>(password, salt, rounds, &mut out),
}
out
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CipherAlgo {
Aes256,
TripleDes,
}
impl CipherAlgo {
pub fn from_alg_id(id: u32) -> Option<Self> {
match id {
0x6610 => Some(CipherAlgo::Aes256),
0x6603 => Some(CipherAlgo::TripleDes),
_ => None,
}
}
pub fn key_len(self) -> usize {
match self {
CipherAlgo::Aes256 => 32,
CipherAlgo::TripleDes => 24,
}
}
pub fn iv_len(self) -> usize {
match self {
CipherAlgo::Aes256 => 16,
CipherAlgo::TripleDes => 8,
}
}
pub fn cbc_decrypt_nopad(self, key: &[u8], iv: &[u8], ct: &[u8]) -> Option<Vec<u8>> {
if ct.is_empty() || ct.len() % 8 != 0 {
return None;
}
let mut buf = ct.to_vec();
match self {
CipherAlgo::Aes256 => {
let d = cbc::Decryptor::<Aes256>::new_from_slices(key, iv).ok()?;
d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
}
CipherAlgo::TripleDes => {
let d = cbc::Decryptor::<TdesEde3>::new_from_slices(key, iv).ok()?;
d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
}
}
Some(buf)
}
}
pub fn unpad_pkcs7(data: &[u8]) -> Option<Vec<u8>> {
let &pad = data.last()?;
let pad = pad as usize;
if pad == 0 || pad > data.len() || pad > 16 {
return None;
}
if data[data.len() - pad..].iter().all(|&b| b as usize == pad) {
Some(data[..data.len() - pad].to_vec())
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pbkdf2_hmac_sha1_rfc6070() {
let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 1, 20);
assert_eq!(hex(&dk), "0c60c80f961f0e71f3a9b524af6012062fe037a6");
let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 2, 20);
assert_eq!(hex(&dk), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 4096, 20);
assert_eq!(hex(&dk), "4b007901b765489abead49d926f721d065a429c1");
}
#[test]
fn hmac_sha1_rfc2202() {
let mac = hmac_sha1(b"Jefe", b"what do ya want for nothing?");
assert_eq!(hex(&mac), "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
}
#[test]
fn hmac_sha512_rfc4231() {
let mac = hmac_sha512(b"Jefe", b"what do ya want for nothing?");
assert_eq!(
hex(&mac),
"164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
);
}
#[test]
fn pkcs7_unpad_roundtrip() {
assert_eq!(unpad_pkcs7(&[b'a', b'b', 2, 2]).unwrap(), b"ab");
assert_eq!(unpad_pkcs7(&[1]).unwrap(), b"");
assert!(unpad_pkcs7(&[b'a', 2, 3]).is_none()); assert!(unpad_pkcs7(&[]).is_none());
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
}