(NestJS-8)Use bcrypt to encrypt password before storing it in a database
In this article, we will explore encryption techniques to protect sensitive data before inserting it into a database in a NestJS application. Encrypting data helps safeguard it from unauthorized access, ensuring confidentiality and compliance with data protection regulations.
Prerequisites
Before we begin, ensure you have the following:
- NestJS Project Setup: A basic NestJS project. If you don’t have one, refer to the Getting Started with NestJS article.
- TypeORM and Database: Installed and configured in your project, refer to the TypeORM Configuration article.
- CRUD Operations: Basic CRUD operations defined for your entities. If you’re unfamiliar with this, you can check out our article on NestJS CRUD Operations using TypeORM.
1. Why Encryption?
When handling sensitive information such as passwords, personal data, or financial information, encryption ensures that this data is stored securely in your database. Even if an unauthorized party gains access to your database, the encrypted data will remain protected.
2. Why Bcrypt
Bcrypt (like most hashing algorithms) is designed to securely store passwords, but it’s not intended for encryption and decryption. When you use bcrypt to hash a phone number (or any other data), you cannot retrieve the original data back from the hash because bcrypt intentionally adds randomization (salting) to prevent reverse-engineering.
3. Install Required Dependencies
To implement encryption in your NestJS application, we will use the bcrypt
library for hashing passwords. You can install it using npm:
npm install bcrypt
4. Hashing Passwords
The most common use case for encryption in web applications is password hashing. Here’s how to hash passwords before saving them in the database.
We will create methods that handle hashing and validation. Open the user.service.ts
file and update the following methods in the UserService
class:
import * as bcrypt from 'bcrypt';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
@InjectRepository(Profile)
private profileRepository: Repository<Profile>,
) { }
private async hashString(str: string): Promise<string> {
const saltRounds = 10; // Define the cost factor for hashing
return await bcrypt.hash(str, saltRounds);
}
async create(createUserDto: CreateUserDto) {
// Create a new User instance
const user = new User();
user.name = createUserDto.name;
user.password = await this.hashString(createUserDto.password); //encrypt password before insert in database
user.email = createUserDto.email;
const new_user = await this.userRepository.save(user);
const profile = new Profile();
profile.address = createUserDto.address;
profile.phone_number = createUserDto.phoneno;
profile.bio = createUserDto.bio;
profile.dob = createUserDto.dob;
profile.user = new_user; // we can use {user_id:new_user.user_id } as User;
await this.profileRepository.insert(profile)
// Save the profile and assign it to the user
return { message: "User Created Successfully", user_Id: new_user.user_id };
}
/* other methods if any */
}
In this article, we focused on hashing password using hashPassword
method. In the next article, we will implement method to Validate User password during login.
5. Comparing Hashed Passwords
When a user attempts to log in, you must compare the submitted password with the stored hash. bcrypt provides a method called bcrypt.compare()
to perform this comparison securely.
Example Code: Comparing Passwords
async compareWithHashString(plainStr: string, hashedStr: string): Promise<boolean> {
const isMatch = await bcrypt.compare(plainStr, hashedStr);
return isMatch;
}
This function will return true
if the hashed version of the input password matches the stored hash. If the passwords don’t match, the function returns false
.
Conclusion
In this guide, we’ve walked through how to use bcrypt in NestJS to securely hash and compare passwords. The key steps include:
- Hashing passwords before storing them in the database.
- Comparing a plain text password with a stored hash during authentication.
By implementing bcrypt correctly, you ensure that user passwords are never exposed and that your application remains secure against attacks. Whether you’re building a small app or a large-scale application, securing user credentials is a critical step toward ensuring privacy and safety.
Stay tuned for our next article, where we’ll dive into Authentication with JWT.
GitHub Repository:
You can find the complete code for this implementation on GitHub: bhargavachary123
Contribution
If you like my Article, please, consider donating through Buy Me a Coffee: https://buymeacoffee.com/bhargavachary
If you found this article useful, please consider leaving a clap (👏) and a comment. Happy coding! ⚔️