密码进行加盐哈希 using CSharp,Python,Go,Java

 CSharp,

https://github.com/BcryptNet/bcrypt.net
Install-Package BCrypt.Net-Next

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BCrypt.Net;


namespace Common
{

    /// <summary>
    /// 加盐哈希
    /// BCrypt.Net
    /// https://github.com/BcryptNet/bcrypt.net
    /// </summary>
    public class BcryptConverter
    {

        /// <summary>
        /// 生成加盐哈希密码
        /// </summary>
        /// <param name="password">原始密码</param>
        /// <returns>加盐哈希后的密码字符串</returns>
        public static string HashPassword(string password)
        {
            
            // 生成随机盐并哈希
            return BCrypt.Net.BCrypt.HashPassword(password);
        }

        /// <summary>
        /// 验证密码是否匹配哈希
        /// </summary>
        /// <param name="password">原始密码</param>
        /// <param name="hashedPassword">存储的哈希密码</param>
        /// <returns>是否匹配</returns>
        public static bool VerifyPassword(string password, string hashedPassword)
        {
            // 校验密码与哈希是否匹配
            return BCrypt.Net.BCrypt.Verify(password, hashedPassword);
        }

    }
}

  

调用:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;

namespace HighCharts
{

    /// <summary>
    /// 
    /// </summary>
    public partial class BCryptdemo : System.Web.UI.Page
    {


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string pwd = "123456";
            string hashed = BcryptConverter.HashPassword(pwd);

            if (BcryptConverter.VerifyPassword("123456", hashed))
            {
                Response.Write("ok"); 
            }
            else 
            {
                Response.Write("erro");
            }
            hashed = "$2a$10$i.W7bLRgHZMjVpLADHzmaOk/jde00EhOVCRIKyY2BnPUFvS4ZvTC2";
            if (BcryptConverter.VerifyPassword("123456", hashed))
            {
                Response.Write("ok2");
            }
            else
            {
                Response.Write("erro2");
            }

        }
    }
}

  

 

Python,

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:pip install bcrypt  https://github.com/pyca/bcrypt
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j  $2a$10$i.W7bLRgHZMjVpLADHzmaOk/jde00EhOVCRIKyY2BnPUFvS4ZvTC2
# Datetime  : 2026/4/17 22:26 
# User      :  geovindu
# Product   : PyCharm
# Project   : Pysimple
# File      : Bcrypt.py

import bcrypt
from typing import cast

class BcryptConverter(object):
    """
    BCrypt 密码哈希工具(与 C# 版本功能一致)
    """
    @staticmethod
    def hash_password2(password: str) -> str:
        """
        生成加盐哈希密码
        :param password: 明文密码字符串
        :return: 哈希后的字符串(可直接存数据库)
        """
        # 自动转 bytes,生成盐并哈希
        password_bytes = password.encode('utf-8')
        salt = bcrypt.gensalt()  # 自动生成随机盐
        hashed_bytes = bcrypt.hashpw(password_bytes, salt)
        return hashed_bytes.decode('utf-8')  # 返回字符串

    @staticmethod
    def verify_password2(password: str, hashed_password: str) -> bool:
        """

        :param password:
        :param hashed_password:
        :return:
        """
        if not (hashed_password.startswith("$2b$") and len(hashed_password) == 60):
            return cast(bool, False)  # 显式断言类型

        try:
            password_bytes = password.encode('utf-8')
            hashed_bytes = hashed_password.encode('utf-8')
            return cast(bool, bcrypt.checkpw(password_bytes, hashed_bytes))
        except Exception:
            return cast(bool, False)

    @staticmethod
    def HashPassword(password: str) -> str:
        """
        (与 C# 版本功能一致)
        :param password:
        :return:
        """
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')   #$2b$12$QLXVeM0B57EmPZqFYSbhxOtnGhY/b.oB3pH7srxh/42OUp9TVdrOW

    @staticmethod
    def VerifyPassword(password:str, hashedPassword:str) -> bool:
        """
        (与 C# 版本功能一致)
        :param password:
        :param hashedPassword:
        :return:
        """

        return bcrypt.checkpw(password.encode('utf-8'), hashedPassword.encode('utf-8'))

  

调用:

if __name__ == "__main__":
    br = BcryptConverter()
    # 1. 哈希密码
    pwd = "123456"
    hashed = br.HashPassword(pwd)
    print("哈希结果:", hashed)

    # 2. 验证正确密码
    print(br.VerifyPassword("123456", hashed))  # True
    hashed="$2a$10$i.W7bLRgHZMjVpLADHzmaOk/jde00EhOVCRIKyY2BnPUFvS4ZvTC2"
    # 3. 验证错误密码
    print(br.VerifyPassword("1234567", hashed))  # False
    print(br.verify_password2("123456", hashed)) #True

  

 

Go,


https://pkg.go.dev/golang.org/x/crypto/bcrypt
https://github.com/golang/crypto
go get golang.org/x/crypto/bcrypt

/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:  go get golang.org/x/crypto/bcrypt
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/17 22:39
# User      :  geovindu
# Product   : GoLand
# Project   : mysqldemol
# File      : BcryptConverter.go
*/
package common

import "golang.org/x/crypto/bcrypt"

type BcryptConverter struct{}

// HashPassword 生成加盐哈希密码
// password: 原始明文密码
// return: 哈希后的字符串 / 错误
func (BcryptConverter) HashPassword(password string) (string, error) {
	// bcrypt.DefaultCost = 10(和C# BCrypt.Net默认一致)
	hashBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(hashBytes), err
}

// VerifyPassword 验证密码是否匹配哈希
// password: 明文密码
// hashedPassword: 数据库存储的哈希串
// return: 匹配返回true,失败/错误返回false
func (BcryptConverter) VerifyPassword(password, hashedPassword string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
	return err == nil
}

  

调用

func main() {

	var converter common.BcryptConverter

	// 1. 哈希密码
	rawPwd := "123456"
	hashedPwd, errs := converter.HashPassword(rawPwd)
	if errs != nil {
		panic("哈希失败:" + errs.Error())
	}
	println("原始密码:", rawPwd)
	println("哈希结果:", hashedPwd)

	// 2. 验证正确密码
	match1 := converter.VerifyPassword(rawPwd, hashedPwd)
	println("正确密码验证结果:", match1) // true

	// 3. 验证错误密码
	match2 := converter.VerifyPassword("wrongpwd", hashedPwd)
	println("错误密码验证结果:", match2) // false

  

Java

/**
 * encoding: utf-8
 * 版权所有 2026 ©涂聚文有限公司 ®
 * 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 * 描述:https://github.com/djmdjm/jBCrypt   https://www.mindrot.org/projects/jBCrypt/
 * Author    : geovindu,Geovin Du 涂聚文.
 * IDE       : IntelliJ IDEA 2024.3.6 Java 17
 * # database  : Oracle21c,MySQL 9.0,SQL Server 2019,PostgreSQL 17.1 Neo4j
 * # OS        : window10
 * Datetime  : 2026 - 2026/4/17 - 22:07
 * User      : geovindu
 * Product   : IntelliJ IDEA
 * Project   : sutdyjava
 * File      : BcryptConverter.java
 * explain   : 学习  类
 **/

package Common;

import org.mindrot.jbcrypt.BCrypt;


/**
 * 加盐哈希
 */
public class BcryptConverter {


    /**
     * 生成加盐哈希密码
     * @param password 原始密码
     * @return 加盐哈希后的密码字符串
     */
    public static String HashPassword(String password)
    {
        // 生成随机盐并哈希
        return BCrypt.hashpw(password, BCrypt.gensalt());
    }
    /**
     * 验证密码是否匹配哈希
     * @param password 原始密码
     * @param hashedPassword 存储的哈希密码
     * @return 是否匹配
     */
    public static Boolean VerifyPassword(String password, String hashedPassword)
    {
        // 校验密码与哈希是否匹配
        return BCrypt.checkpw(password, hashedPassword);
    }

}

  

调用::

 public static void main(String[] args)
    {


        String pwd = "123456";
        String hashed = BcryptConverter.HashPassword(pwd);
        System.out.println(hashed);
        if(BcryptConverter.VerifyPassword(pwd,hashed))
        {
            System.out.println("Password verified");
        }
        else
        {
            System.out.println("Password not verified");
        }
        hashed="$2a$10$i.W7bLRgHZMjVpLADHzmaOk/jde00EhOVCRIKyY2BnPUFvS4ZvTC2";
        if(BcryptConverter.VerifyPassword(pwd,hashed))
        {
            System.out.println("Password verified2");
        }
        else
        {
            System.out.println("Password not verified2");
        }

        for(int i=0;i<5;i++) {
            for(int j=0;j<5;j++) {
                Car car = new Car("中国东风", "i:"+i, j);
                car.accelerate(20);
                car.displayStatus();
            }

        }

        System.out.println("Hello, World!");
    }
}

  

 

posted @ 2026-04-17 23:58  ®Geovin Du Dream Park™  阅读(9)  评论(0)    收藏  举报