Encrypt passwords with Go

Go already has many helpful packages from the start. One of them is the bcrypt package with which e.g. will encrypt passwords securely.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"golang.org/x/crypto/bcrypt"
)

func main() {
	pw := "SecretPassword"
	bs, err := bcrypt.GenerateFromPassword([]byte(pw), 2)
	
	//let's look at the encrypted password
	fmt.Printf("encryption result: %s\n", string(bs))
	
	err = bcrypt.CompareHashAndPassword(bs, []byte(pw))
	if err != nil {
		fmt.Println("Wrong! Wrong! Wrong!")
	} 
}

Try it out

We pass our password to the function GenerateFromPassword([]byte(pw), 2) as a slice of byte. The second argument is the cost for the encryption as an integer. The higher the costs the longer the encryption will take. The encryption will also be more secure if calculated with a higher cost value. If we pass a 0 bcrypt will use a standard value for the cost.

Pretty easy so far 😊

0%