Simple password hashing in Go.
Note: If you have the choice, just use bcrypt.
package main
import (
"fmt"
"github.com/yhat/phash"
)
func main() {
hash := phash.Gen("password123")
fmt.Println(hash) // sha1$nJ1m4Cc3$1$eb0e7337ef98fc602be128a53648f4c8d736c1f4
fmt.Println(phash.Verify("password123", hash)) // true
fmt.Println(phash.Verify("not my pass", hash)) // false
}
Fully compatible with Node.js' password-hash
This package was initially developed so we (the Yhat Dev Team) could migrate apps from Node.js to Go without losing user password data. As a result phash will correctly verify hashes generated by the password-hash library and vice versa.
var passwordHash = require('password-hash');
var hash = "sha1$nJ1m4Cc3$1$eb0e7337ef98fc602be128a53648f4c8d736c1f4";
console.log(passwordHash.verify("password123", hash)); // true
console.log(passwordHash.verify("not my pass", hash)); // false
Thanks to jfrazelle for figuring this out a while back.
By default, phash only compiles with sha1 (the default hash). To use other
algorithms, you must register the hash with Go's crypto
package by importing it.
phash.Generate()
also lets you specify the salt length and number of iterations
(the defaults are 8 and 1 respectively).
package main
import (
_ "crypto/md5" // This will register md5 with crypto and phash
"fmt"
"github.com/yhat/phash"
)
func main() {
saltLength := uint(6)
iterations := uint(2)
// error caused by unknown hash ignored
hash, _ := phash.Generate("password123", "md5", saltLength, iterations)
fmt.Println(hash) // md5$WEOJX6$2$089e13e498615a4f1b88bd64e8d713f5
}
As a caveat phash.Verify()
will return false if the needed hash algorithm is not imported.