2024-09-23 23:44:21 +05:30
|
|
|
import bcrypt from "bcrypt";
|
2024-10-05 15:42:06 +05:30
|
|
|
import crypto from 'crypto';
|
2024-09-23 23:44:21 +05:30
|
|
|
|
2024-09-25 18:43:43 +05:30
|
|
|
export const hashPassword = (password: string): Promise<string> => {
|
2024-09-23 23:44:21 +05:30
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
bcrypt.genSalt(12, (err, salt) => {
|
|
|
|
|
if (err) {
|
|
|
|
|
reject(err)
|
|
|
|
|
}
|
|
|
|
|
bcrypt.hash(password, salt, (err, hash) => {
|
|
|
|
|
if (err) {
|
|
|
|
|
reject(err)
|
|
|
|
|
}
|
|
|
|
|
resolve(hash)
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// password from frontend and hash from database
|
2024-09-25 19:19:06 +05:30
|
|
|
export const comparePassword = (password: string, hash: string): Promise<boolean> => {
|
2024-09-23 23:44:21 +05:30
|
|
|
return bcrypt.compare(password, hash)
|
2024-10-05 15:42:06 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const encrypt = (text: string): string => {
|
2024-10-05 15:48:11 +05:30
|
|
|
const iv = crypto.randomBytes(process.env.IV_LENGTH);
|
|
|
|
|
const cipher = crypto.createCipheriv(process.env.ALGORITHM, Buffer.from(process.env.ENCRYPTION_KEY), iv);
|
2024-10-05 15:42:06 +05:30
|
|
|
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
|
|
|
encrypted += cipher.final('hex');
|
|
|
|
|
return `${iv.toString('hex')}:${encrypted}`;
|
2024-10-05 15:42:32 +05:30
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const decrypt = (encryptedText: string): string => {
|
|
|
|
|
const [iv, encrypted] = encryptedText.split(':');
|
2024-10-05 15:48:11 +05:30
|
|
|
const decipher = crypto.createDecipheriv(process.env.ALGORITHM, Buffer.from(process.env.ENCRYPTION_KEY), Buffer.from(iv, 'hex'));
|
2024-10-05 15:42:32 +05:30
|
|
|
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
|
|
|
|
|
decrypted += decipher.final('utf8');
|
|
|
|
|
return decrypted;
|
2024-10-05 15:42:06 +05:30
|
|
|
};
|