Home > Backend Development > Golang > How Can I Ensure Bcrypt Password Hashing Compatibility Between Go and Node.js?

How Can I Ensure Bcrypt Password Hashing Compatibility Between Go and Node.js?

Linda Hamilton
Release: 2024-12-03 07:30:10
Original
641 people have browsed it

How Can I Ensure Bcrypt Password Hashing Compatibility Between Go and Node.js?

Bcrypt Password Hashing Compatibility between Go and Node.js

In migrating from Node.js to Go, it is essential to maintain backward compatibility with user passwords stored in the database. This requires replicating Node.js's bcrypt password hashing functionality in Go.

In Node.js, the bcrypt encryption code utilizes the bcrypt library to generate a salted hash from a user's password. The equivalent code in Go, using the golang.org/x/crypto/bcrypt package, is:

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

This function produces a hashed password string compatible with the output generated by the Node.js code.

The following working Go example demonstrates the bcrypt password hashing process:

package main

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

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

    hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(hashedPassword))

    err = bcrypt.CompareHashAndPassword(hashedPassword, password)
    if err == nil {
        fmt.Println("Password matches hash.")
    } else {
        fmt.Println("Password does not match hash.")
    }
}
Copy after login

The above is the detailed content of How Can I Ensure Bcrypt Password Hashing Compatibility Between Go and Node.js?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template