Golang : Bcrypting password
From my past tutorial on salting password, a reader pointed out that there is a better way to handle/protect users passwords in case hackers managed to get the database plaintext data dump. The method he suggested is to use bcrypt algorithm...which automagically handle the salting part well.
The code below is my own experiment with the bcrypt package for Golang and see if it can be useful to you.
UPDATE: Fixed errata cipherText := saltedCipherText[23:]
to cipherText := saltedCipherText[22:]
Thanks Steve Sharp for pointing out.
Here you go!
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
"strings"
)
func main() {
passwd := []byte("password")
hashedPassword, err := bcrypt.GenerateFromPassword(passwd, 10)
if err != nil {
panic(err)
}
fmt.Printf("The hashed password is : %s\n", string(hashedPassword))
fmt.Printf("%q\n", strings.SplitN(string(hashedPassword), "$", 4))
parts := strings.SplitN(string(hashedPassword), "$", 4)
algorithm := parts[1]
costFactor := parts[2] // number of iterations. Higher cost will increase brute force difficulty
saltedCipherText := parts[3]
fmt.Println("Algorithm : ", algorithm)
fmt.Println("Cost Factor : ", costFactor)
fmt.Println("Salt + Cipher Text : ", saltedCipherText)
// in case you still want to store the salt separately in your database
salt := saltedCipherText[0:22]
fmt.Println("Salt : ", salt)
cipherText := saltedCipherText[22:]
fmt.Println("Cipher Text : ", cipherText)
}
Sample output :
The hashed password is : $2a$10$qevL45Hnebe0SlbTKT36kuX87fq/sWDjzozJ/4OMh1hPcOo/SASqO
["" "2a" "10" "qevL45Hnebe0SlbTKT36kuX87fq/sWDjzozJ/4OMh1hPcOo/SASqO"]
Algorithm : 2a
Cost Factor : 10
Salt + Cipher Text : qevL45Hnebe0SlbTKT36kuX87fq/sWDjzozJ/4OMh1hPcOo/SASqO
Salt : qevL45Hnebe0SlbTKT36ku
Cipher Text : X87fq/sWDjzozJ/4OMh1hPcOo/SASqO
References :
https://github.com/golang/crypto/blob/master/bcrypt/bcrypt_test.go
See also : Golang : Securing password with salt
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+39.2k Golang : Remove dashes(or any character) from string
+11.2k Golang : Generate DSA private, public key and PEM files example
+9.8k Golang : Edge detection with Sobel method
+10.8k Golang : Web routing/multiplex example
+8.5k Golang : Gorilla web tool kit schema example
+28.9k Golang : Record voice(audio) from microphone to .WAV file
+9.5k Golang : Resumable upload to Google Drive(RESTful) example
+4.4k Linux : sudo yum updates not working
+13.4k Golang : Tutorial on loading GOB and PEM files
+50.4k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+9.8k Golang : Check a web page existence with HEAD request example
+7.2k Golang : How to handle file size larger than available memory panic issue