Thursday, 10 August, 2017 UTC


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:
hash, err := bcrypt.GenerateFromPassword([]byte("my-password"), 10)
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:
err = bcrypt.CompareHashAndPassword([]byte("hashed-password"), []byte("plaintext-password"))
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:
type Account struct {
	Type     string `json:"type,omitempty"`
	Email    string `json:"email,omitempty"`
	Password string `json:"password,omitempty"`

func main() {
    cluster, _ := gocb.Connect("couchbase://localhost")
    bucket, _ := cluster.OpenBucket("default", "")
    email := "[email protected]"
    pass := "my-password"
    hash, _ := bcrypt.GenerateFromPassword([]byte(pass), 10)
    account := Account{
        Type:     "account",
        Email:    email,
        Password: string(hash),
    bucket.Insert(email, account, 0)
    account = Account{}
    bucket.Get(email, &account)
	err := bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(pass))
	if err != nil {
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.
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.
The post Securely Storing Password Data in Couchbase with Golang and BCrypt appeared first on The Couchbase Blog.