Search code examples
javaspringencryptionbcrypt

BCrypt: Is there a way to insert already encrypted passwords in a database?


I'm building a web app with Spring Framework (-> Java). For testing reasons I've created one user (via SQL statement). Currently I'm working on password encryption, for which I'm using BCyrptPasswordEncoder. I'm wondering, if it's possible, to create this first user with the encoded password.

In other words: can I create a new user via SQL statement using an encrypted password as input? If so, how do I input the encoded password?

I've tried {Bcyrpt}[hash], which I read on some website, but that didn't seem to work...

INSERT INTO USER(USERNAME, PASSWORD) VALUES ('admin', 'passwd')


Solution

  • First a quick clarification on the terminology. The passwords are "hashed" with bcrypt not "encrypted". This means it's a one-way algorithm (you can't un-hash the value).

    The value stored in the database is the hashed value (eg. $2a$10$Iewuj5kQFVnUaNbb6M0sAu6a1qbc5bqXAuyc.9fF4cR8xxIOhD0Da) and not the plain text password.

    So all you need to do for your test user is generate a bcrypt hash to put into the INSERT statement. Either run it through BCryptPasswordEncoder or use an online bcrypt generator.

    For example:

    INSERT INTO USER(USERNAME, PASSWORD) VALUES ('admin', '$2a$10$Iewuj5kQFVnUaNbb6M0sAu6a1qbc5bqXAuyc.9fF4cR8xxIOhD0Da')