不少系统都是将密码进行一次 MD5 或 SHA1 Hash后存入数据库中。这样的密码抵挡不住字典攻击。所谓字典攻击,就是将经常使用密码进行Hash后作成一个字典,破解的时候,只须要查字典就能知道对应的明文密码。golang
为了抵御字典攻击,推荐的作法是使用 密码 + 盐(一串随机数) 再Hash的方式。每一个密码对应一个不一样的随机数。这个方法,其实是将密码人为地拓展了N位,致使密码长度大增,使得攻击者没法构造这么大的一个字典。正则表达式
Go语言提供了一种较为安全的加密方式,使用GoLang golang.org/x/crypto/bcrypt 模块,经过该模块能够快速实现密码的存储处理。数据库
package main import ( "fmt" "golang.org/x/crypto/bcrypt" ) type User struct { Name string `json:"name"` Password string `json:"password"` } func main() { fmt.Println("====模拟注册====") u0 := User{} u0.Password = "pwd" //模拟注册是传递的密码 hash, err := bcrypt.GenerateFromPassword([]byte(u0.Password), bcrypt.DefaultCost) //加密处理 if err != nil { fmt.Println(err) } encodePWD := string(hash) // 保存在数据库的密码,虽然每次生成都不一样,只需保存一份便可 fmt.Println(encodePWD) fmt.Println("====模拟登陆====") u1:=User{} u1.Password=encodePWD //模拟从数据库中读取到的 通过bcrypt.GenerateFromPassword处理的密码值 loginPwd:="pwd" //用户登陆时输入的密码 // 密码验证 err = bcrypt.CompareHashAndPassword([]byte(u1.Password), []byte(loginPwd)) //验证(对比) if err != nil { fmt.Println("pwd wrong") } else { fmt.Println("pwd ok") } }
运行效果:json
第一次运行:安全
第二次运行:加密
说明:每次运行,计算的密码值都不一样。所以使用GoLang golang.org/x/crypto/bcrypt 模块对密码进行处理,能够避免字典攻击。spa
附:密码强弱的判断
方法1:正则表达式判断(长度、大小写、特殊字符)code
方法2:创建一个若密码表,依据表中的密码判断是否为若密码blog
注:以上2种方法能够结合使用string