Home >Backend Development >Golang >How to Hash Passwords with Bcrypt in Golang for Node.js Compatibility?

How to Hash Passwords with Bcrypt in Golang for Node.js Compatibility?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 12:33:18964browse

How to Hash Passwords with Bcrypt in Golang for Node.js Compatibility?

Hashing Passwords with Bcrypt in Golang (Node.js Compatibility)

Migrating from Node.js and Passport to Golang for user authentication can present challenges, especially when handling encrypted passwords stored in the database. This guide explores how to create bcrypt hashed strings in Golang that are compatible with Node.js.

Node.js Encryption Code

var bcrypt = require('bcrypt');

bcrypt.genSalt(10, function(err, salt) {
    if(err) return next(err);

    bcrypt.hash(user.password, salt, function(err, hash) {
        if(err) return next(err);
        user.password = hash;
        next();
    });
});

Golang Equivalent

To achieve the same hashing results in Golang, use the golang.org/x/crypto/bcrypt package.

hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)

Working Example

package main

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

func main() {
    password := []byte("MyDarkSecret")

    // Hashing the password with the default cost of 10
    hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(hashedPassword))

    // Comparing the password with the hash
    err = bcrypt.CompareHashAndPassword(hashedPassword, password)
    fmt.Println(err) // nil means it is a match
}

This example demonstrates the use of bcrypt in Golang to generate a hashed password equivalent to the one created in Node.js, allowing for seamless migration of encrypted passwords during the transition to Golang.

The above is the detailed content of How to Hash Passwords with Bcrypt in Golang for Node.js Compatibility?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn