How to decrypt hash stored by bcrypt

PerlBcrypt

Perl Problem Overview


I have this script that encrypts a password but I don't know how to reverse it and decrypt it. This may be a very simple answer but I don't understand how to do it.

#!/usr/bin/perl
use Crypt::Eksblowfish::Bcrypt;
use Crypt::Random;
 
$password = 'bigtest';
$encrypted = encrypt_password($password);
print "$password is encrypted as $encrypted\n";
 
print "Yes the password is $password\n" if check_password($password, $encrypted);
print "No the password is not smalltest\n" if !check_password('smalltest', $encrypted);
 
# Encrypt a password 
sub encrypt_password {
    my $password = shift;
 
    # Generate a salt if one is not passed
    my $salt = shift || salt(); 
 
    # Set the cost to 8 and append a NUL
    my $settings = '$2a$08$'.$salt;
 
    # Encrypt it
    return Crypt::Eksblowfish::Bcrypt::bcrypt($password, $settings);
}
 
# Check if the passwords match
sub check_password {
    my ($plain_password, $hashed_password) = @_;
 
    # Regex to extract the salt
    if ($hashed_password =~ m!^\$2a\$\d{2}\$([A-Za-z0-9+\\.]{22})!) {
        return encrypt_password($plain_password, $1) eq $hashed_password;
    } else {
        return 0;
    }
}
 
# Return a random salt
sub salt {
    return Crypt::Eksblowfish::Bcrypt::en_base64(Crypt::Random::makerandom_octet(Length=>16));
}

Perl Solutions


Solution 1 - Perl

You're HASHING, not ENCRYPTING!

What's the difference?

The difference is that hashing is a one way function, where encryption is a two-way function.

So, how do you ascertain that the password is right?

Therefore, when a user submits a password, you don't decrypt your stored hash, instead you perform the same bcrypt operation on the user input and compare the hashes. If they're identical, you accept the authentication.

Should you hash or encrypt passwords?

What you're doing now -- hashing the passwords -- is correct. If you were to simply encrypt passwords, a breach of security of your application could allow a malicious user to trivially learn all user passwords. If you hash (or better, salt and hash) passwords, the user needs to crack passwords (which is computationally expensive on bcrypt) to gain that knowledge.

As your users probably use their passwords in more than one place, this will help to protect them.

Solution 2 - Perl

To answer the original posters question.... to 'decrypt' the password, you have to do what a password cracker would do.

In other words, you'd run a program to read from a large list of potential passwords (a password dictionary) and you'd hash each one using bcrypt and the salt and complexity from the password you're trying to decipher. If you're lucky you'll find a match, but if the password is a strong one then you likely won't find a match.

Bcrypt has the added security characteristic of being a slow hash. If your password had been hashed with md5 (terrible choice) then you'd be able to check billions of passwords per second, but since it's hashed using bcrypt you will be able to check far fewer per second.

The fact that bcrypt is slow to hash and salted is what makes it a good choice for password storage even today. That being said I believe NIST recommends the PBKDF2 for password hashing.

Solution 3 - Perl

You simply can't.

bcrypt uses salting, of different rounds, I use 10 usually.

bcrypt.hash(req.body.password,10,function(error,response){ }

This 10 is salting random string into your password.

Solution 4 - Perl

You can't decrypt but you can BRUTEFORCE IT...

I.E: iterate a password list and check if one of them match with stored hash.

script from github: https://github.com/BREAKTEAM/Debcrypt

Solution 5 - Perl

Maybe you search this? For example in my case I use Symfony 4.4 (PHP). If you want to update User, you need to insert the User password encrypted and test with the current Password not encrypted to verify if it's the same User.

For example :

public function updateUser(Request $req)
      {
         $entityManager = $this->getDoctrine()->getManager();
         $repository = $entityManager->getRepository(User::class);
         $user = $repository->find($req->get(id)); // get User from your DB

         if($user == null){
            throw  $this->createNotFoundException('User doesn\'t exist!!', $user);
         }
         $password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
         $passwordToUpdate = $req->get('password'); // not encrypted yet from request.

         $passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);

         // VERIFY IF IT'S THE SAME PASSWORD
         $isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );

         if($isPass === false){ // failure
            throw  $this->createNotFoundException('Your password is not valid', null);
         }

        return $isPass; // true!! it's the same password !!!
    
      }

Solution 6 - Perl

You can use the password_verify function with the PHP. It verifies that a password matches with the hash

password_verify ( string $password , string $hash ) : bool

more details: https://www.php.net/manual/en/function.password-verify.php

Solution 7 - Perl

import (
    "fmt"
    "golang.org/x/crypto/bcrypt"
)

// Save password in hash
func HashPassword(password string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
    return string(bytes), err
}

// check password in hash
func CheckPasswordHash(password, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}

func main() {
    password := "password"
    hash, _ := HashPassword(password) // ignore error for the sake of simplicity

    fmt.Println("Password:", password)
    fmt.Println("Hash:    ", hash)

    match := CheckPasswordHash(password, hash)
    fmt.Println("Password match or not:", match) // It will return true or false
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBluGeniView Question on Stackoverflow
Solution 1 - PerlGlitch DesireView Answer on Stackoverflow
Solution 2 - PerlstackhouseView Answer on Stackoverflow
Solution 3 - PerlSourabhView Answer on Stackoverflow
Solution 4 - PerlMike D3ViD TysonView Answer on Stackoverflow
Solution 5 - PerlMarco PavonView Answer on Stackoverflow
Solution 6 - PerlRajitha GamgageView Answer on Stackoverflow
Solution 7 - PerlVidhi PatelView Answer on Stackoverflow