You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
9 Hrs
48 Min
38 Seg

Cifrado de contraseña

24/38
Resources

How to secure passwords in databases?

Secure storage of passwords is a vital practice for maintaining the integrity and security of web applications. One of the most common challenges is storing passwords in such a way that they are inaccessible if someone unauthorized gains access to the database. Here's how you can use the Bcrypt library to securely encrypt passwords.

What is Bcrypt and how does it work?

Bcrypt is a widely used library for encrypting passwords. The main advantage is that it converts a text string, such as "Password123", into a 32-character encrypted string with no direct relation to the original text. This means that even if someone can access the encrypted data, they will not be able to reverse the process or use it to authenticate users.

  1. Encrypted string: transforms a password into a long, unbreakable set of characters.
  2. Advanced security: although there are methods to try to decrypt these strings, they are complex and time-consuming.

How to implement Bcrypt in an application?

The following guide shows how you can encrypt your users' passwords using Bcrypt. We recommend you to follow these steps in your code:

// Import the Bcrypt libraryconst bcrypt = require('bcrypt');
// Set the 'salt' level, or encryption complexityconst saltRounds = 10;
// Store a password securelyasync function storePassword(password) { try { // Generate a hash for the password const hashedPassword = await bcrypt.hash(password, saltRounds); // We save the hash to the database instead of the password in cleartext // Database.saveUser({ password: hashedPassword }); } catch (error) { console.error('Error encrypting password:', error); } }}
// Example of usingstorePassword('Password123');

What is the 'salt' in the encryption process?

The term 'salt' refers to an additional value that is added to the encryption process to increase security. The idea is to avoid dictionary-based attacks and Rainbow tables, which compare previously encrypted hash outputs. By varying the 'salt', we make it more difficult for two of the same passwords to generate the same hash.

  • Seasoning: think of the 'salt' as a seasoning that, when mixed with the "food" (the original password), changes its flavor (or in this case, its hash).
  • Salt setting: in the above example const saltRounds = 10;, this line determines the level of security applied to the hash. The higher the number, the more robust the resulting hash will be, but also the more processing and time it will require.

How to correct errors when encrypting passwords?

During development, it is common to face situations where the system has configuration or implementation errors. Here is a common error and how to fix it:

  1. Storage error: it is possible that after encrypting the password, it is incorrectly saved in the database.
// Storage solution// Instead of creating a separate field, directly update the database field with the generated hash:function updateUserWithHash(hashPassword) { // Assuming the original database field is named 'password' database.updateUser({ password: hashPassword });}

Proper implementation and understanding of these concepts will not only ensure that your application protects user credentials from unauthorized access, but will also give you peace of mind that you are following industry best practices. Keep learning and exploring ways to improve the security of your applications!

Contributions 4

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

¿Todo esto no sobra si usamos el atributo encrypt en el modelo ?
https://sailsjs.com/documentation/concepts/models-and-orm/attributes#encryption-at-rest

Sails tiene algo parecido a las señales de Django que permite implementar acciones antes o después de que se guarde un usuario. Es decir, podríamos guardar la contraseña en texto plano y sails automáticamente se encarga de hashearla en el momento justo antes de guardarla en la base de datos. Dejo aquí el enlace a la documentación https://sailsjs.com/documentation/concepts/models-and-orm/lifecycle-callbacks#example

Yo recomendaría crear un helper:

const bcrypt = require('bcrypt');

module.exports = {
    friendlyName: 'Generate password',
    description: 'Generate password',

    inputs: {
      password: {
        type: 'string',
        required: true
      }
    },
  
    exits: {},
  
    fn: async function (inputs, exits) {
      const hash = bcrypt.hashSync(inputs.password, 10);
      return exits.success(hash);
    }
  
  };

Y en tu controller:

module.exports = async function signup (req, res) {
    const email = req.param('email');
    const pass = req.param('password');
    
    // No olvides tus validaciones...

    const hash = await sails.helpers.generatePassword(pass);
  
    var user = await User.create({
      email: email, password: hash
    }).fetch();
  
    return res.status(201).send("OK");
  };