When writing web applications that store passwords for your users, it is never a good idea to store them as plain text in your database, whether that be NoSQL or RDBMS. Last year I wrote about using BCrypt with Node.js and Couchbase as well as using BCrypt with Java and Couchbase. What if we wanted to take this to Golang?

We’re going to see how to hash passwords in a Golang application using BCrypt to safely store them in Couchbase.

To set the record straight, we’re interested in password hashing, not password encryption because encryption implies that decryption is possible. Hashing is a one way process.

The great thing about Go is that there is a a BCrypt package built in. When using this package or doing anything related to BCrypt, you’re going to focus on two functions. The generation of a hash and the comparison or validation of a hash.

In Go, you could generate a new hash based on your password string like the following:

Using the GenerateFromPassword function, you pass in a string as well as a cost value. The higher the cost value, the slower the function because the cost value is how many times the hash is applied.

If you ever wanted to see if a plaintext password matches a hashed password, you could execute the following:

If there is no error, then the passwords matched.

So how might you use this password hashing functionality with Couchbase?

Take the following for example:

The above is a very crude example, but it gets the point across on how you might store the BCrypt password and how to compare against it.

Conclusion

You just saw how to use BCrypt in a Golang application. It is critical that sensitive information like passwords be hashed before they end up in your database, whether that be NoSQL or something else.

For more information on using Couchbase with Golang, check out the Couchbase Developer Portal.

Author

Posted by Nic Raboy, Developer Advocate, Couchbase

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Leave a reply