DaGenix / rust-crypto

A (mostly) pure-Rust implementation of various cryptographic algorithms.
Apache License 2.0
1.4k stars 297 forks source link

Custom encryption similar to Python cannot be implemented #484

Open ImmortalD opened 3 days ago

ImmortalD commented 3 days ago
  1. KDF.KDF._bcrypt_hash function The parameter 'invest=True' cannot be implemented, but 'invest=True' is ok
  2. KDF.PBKDF2 cannot be implemented
import os
from Crypto.Hash import SHA512
from Crypto.Cipher import AES
from Crypto.Protocol import KDF

def bcrypt_hash(password: bytes, salt: bytes) -> bytes:
    return KDF._bcrypt_hash(password, 6, salt, b'OxychromaticBlowfishSwatDynamite', False)

# pip3 install pycryptodome -y
if __name__ == '__main__':
    password = SHA512.new(b"").digest()
    salt = SHA512.new(bytes.fromhex("4fa26e03")).digest()
    p = SHA512.new()
    enc = KDF.PBKDF2(password, salt, 64, 16, prf=bcrypt_hash)
    print("KDF.PBKDF2:  " + enc.hex())

    digest = KDF._bcrypt_hash(password, 6, salt, b'OxychromaticBlowfishSwatDynamite', False)
    print("KDF._bcrypt_hash(invert=False):  " + digest.hex())

    digest = KDF._bcrypt_hash(password, 6, salt, b'OxychromaticBlowfishSwatDynamite', True)
    print("KDF._bcrypt_hash(invert=True):  " + digest.hex())

output

KDF.PBKDF2:  1076fc401301ef1ecfce3a291ddc2a8b9c7d863b459befe455f82e518b36eecdf473864fefc0f5e68d3ab004b5ee0fc781b02befb283b48bfbd770cf9a3c6923
KDF._bcrypt_hash(invert=False):  34ffd5c0e5eacaa24af4b3b6d585c306ba8af7b377ce5f9495e0cb7da714b125
KDF._bcrypt_hash(invert=True):  7458c590585877392b9ca79ce8b93336e053b090501a0141c7b2c609fc4e6550
fn main() {
    let salt = vec![0x4f, 0xa2, 0x6e, 0x03];
    let password: &[u8] = b"";

    let mut out = [0; 32];
    bcrypt_pbkdf(password, salt.as_slice(), 16, out.as_mut_slice());
    println!("bcrypt_pbkdf: {:0x?}", out);

    let mut h_hash = [0; 64];
    let mut h_password = [0; 64];

    let mut sha512 = Sha512::new();
    sha512.input(salt.as_slice());
    sha512.result(&mut h_hash);

    sha512.reset();
    sha512.input(password);
    sha512.result(&mut h_password);

    bcrypt_hash(h_password.as_slice(), h_hash.as_slice(), &mut out);
    println!("KDF._bcrypt_hash(invert=False): {:0x?}", out);
}

output

bcrypt_pbkdf: [1a, b2, 47, e, be, 3, 69, d, 51, 98, 2e, f4, 69, 84, 53, 2b, 6b, 42, 3a, f6, 4a, 7c, 2e, 7e, a7, 2b, a, eb, ff, be, e, c6]
KDF._bcrypt_hash(invert=False): [c0, d5, ff, 34, a2, ca, ea, e5, b6, b3, f4, 4a, 6, c3, 85, d5, b3, f7, 8a, ba, 94, 5f, ce, 77, 7d, cb, e0, 95, 25, b1, 14, a7]

KDF._bcrypt_hash(invert=False): is ok,but rust is little-endian,python is big-endian.

newpavlov commented 3 days ago

This crate is unmaintained. See: https://rustsec.org/advisories/RUSTSEC-2016-0005.html