惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
Vulnerabilities – Threatpost
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
H
Heimdal Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LINUX DO - 最新话题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Cloudflare Blog
美团技术团队
Recorded Future
Recorded Future
T
Tailwind CSS Blog
Latest news
Latest news
Security Archives - TechRepublic
Security Archives - TechRepublic
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
Cloudbric
Cloudbric
Schneier on Security
Schneier on Security
I
Intezer
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
云风的 BLOG
云风的 BLOG
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
Attack and Defense Labs
Attack and Defense Labs
人人都是产品经理
人人都是产品经理
L
LangChain Blog
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
W
WeLiveSecurity
C
Cybersecurity and Infrastructure Security Agency CISA
S
Securelist
SecWiki News
SecWiki News
V2EX - 技术
V2EX - 技术
IT之家
IT之家
Cyberwarzone
Cyberwarzone
F
Full Disclosure
Spread Privacy
Spread Privacy
阮一峰的网络日志
阮一峰的网络日志

博客园 - ®Geovin Du Dream Park™

go: Functional Options Pattern go:Timing Functions Pattern python: Timing Functions Pattern go: Steady-State Pattern python: Steady-State Pattern go: Handshaking Pattern python: Handshaking Pattern go: Fail-Fast Pattern python: Fail-Fast Pattern I go: Deadline Pattern python: Deadline Pattern go: Circuit-Breaker Pattern python: Circuit-Breaker Pattern go: Bulkheads Pattern python: Bulkheads Pattern go: Push & Pull Pattern python: Push & Pull Pattern python: Publish/Subscribe Pattern II go: Publish/Subscribe Pattern python: Publish/Subscribe Pattern go: Futures & Promises Pattern python: Futures & Promises Pattern go: Worker Pool Pattern go:Pipeline Pattern python: Worker Pool Pattern python: Pipeline Pattern go: Fan-Out Pattern python: Fan-Out Pattern go: Fan-In Pattern python: Fan-In Pattern Fan-In go: Producer Consumer  Pattern python: Producer Consumer Pattern go: Parallelism Pattern python: Parallelism Pattern go: Reactor Pattern python: Reactor Pattern go: Generators Pattern python: speech to text offline python: Generators Pattern go: Coroutines Pattern python:Coroutines Pattern go: Broadcast Pattern python: Broadcast Pattern python: Bounded Parallelism Pattern go: Bounded Parallelism Pattern python: N-Barrier Pattern go: N-Barrier Pattern python: Semaphore Pattern go: Semaphore Pattern python: Read-Write Lock Pattern go: Read-Write Lock Pattern python: Monitor Pattern go: Monitor Pattern python: Mutex Pattern go: Lock/Mutex Pattern Python: Condition Variable Pattern go:Condition Variable Pattern python: Registry Pattern python: Interpreter Pattern go: Interpreter Pattern go: Registry Pattern go: Memento Pattern go: Command Pattern go: State Pattern go:Template Method Pattern go: Strategy Pattern go: Visitor Pattern go: Observer Pattern go: Mediator Pattern go: Iterator Pattern go: Chain of Responsibility Pattern go: Proxy Pattern go:Decorator Pattern go: Facade Pattern go: Flyweight Pattern go: Composite Pattern go: Singleton Pattern go: Prototype Pattern go: Bridge Pattern go: Adapter Pattern go: Builder Pattern go: Abstract Factory Pattern go: Model,Interface,DAL ,Factory,BLL using mysql go: Simple Factory Pattern go: Factory Method Pattern go: goLang 在Windows环境搭建Go语言开发环境 CSharp: Parallel Extensions cpp: class python: 蝴蝶跟随鼠标 javascript: 中国历史人物热力分布图using echart javascript: 中国历史人物热力图 python: 初养龙虾微信纯文字自动回复using workBuddy python: object 入门 python: Factory Method Pattern python: Simple Factory Pattern python: Abstract Factory Pattern 区域化 代码 python: Null Object Pattern python: Builder Pattern python: Adapter Pattern
密码进行加盐哈希 using CSharp,Python,Go,Java
®Geovin Du Dream Park™ · 2026-04-17 · via 博客园 - ®Geovin Du Dream Park™

 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!");
    }
}

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)