前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【翻译】使用Go生成一个随机字符串(密码)

【翻译】使用Go生成一个随机字符串(密码)

作者头像
Regan Yue
发布2023-03-30 15:42:51
1.1K0
发布2023-03-30 15:42:51
举报
文章被收录于专栏:ReganYue's Blog

来源: Generate a random string (password) · YourBasic Go https://yourbasic.org/golang/generate-random-string/

image.png
image.png

Random string 随机字符串

This code generates a random string of numbers and characters from the Swedish alphabet (which includes the non-ASCII characters å, ä and ö). 该代码从瑞典字母表中随机生成一串数字和字符(其中包括非ASCII字符å、ä和ö)。

代码语言:javascript
复制
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ" +
    "abcdefghijklmnopqrstuvwxyzåäö" +
    "0123456789")
length := 8
var b strings.Builder
for i := 0; i < length; i++ {
    b.WriteRune(chars[rand.Intn(len(chars))])
}
str := b.String() // E.g. "ExcbsVQs"

Warning: To generate a password, you should use cryptographically secure pseudorandom numbers. See User-friendly access to crypto/rand.

警告:为了生成密码,你应该使用加密安全的伪随机数。请User-friendly access to crypto/rand

Random string with restrictions 有限制的随机字符串

This code generates a random ASCII string with at least one digit and one special character. 该代码生成一个随机的ASCII字符串,其中至少有一个数字和一个特殊字符。

代码语言:javascript
复制
rand.Seed(time.Now().UnixNano())
digits := "0123456789"
specials := "~=+%^*/()[]{}/!@#$?|"
all := "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
    "abcdefghijklmnopqrstuvwxyz" +
    digits + specials
length := 8
buf := make([]byte, length)
buf[0] = digits[rand.Intn(len(digits))]
buf[1] = specials[rand.Intn(len(specials))]
for i := 2; i < length; i++ {
    buf[i] = all[rand.Intn(len(all))]
}
rand.Shuffle(len(buf), func(i, j int) {
    buf[i], buf[j] = buf[j], buf[i]
})
str := string(buf) // E.g. "3i[g0|)z"

Before Go 1.10 在Go 1.10 之前

In code before Go 1.10, replace the call to rand.Shuffle with this code: 在Go 1.10之前的代码中,用这段代码替换对rand.Shuffle的调用。

代码语言:javascript
复制
for i := len(buf) - 1; i > 0; i-- { // Fisher–Yates shuffle
    j := rand.Intn(i + 1)
    buf[i], buf[j] = buf[j], buf[i]
}

Further reading 延展阅读

image.png
image.png

Generate random numbers, characters and slice elements 生成随机数字、字符和切片元素

https://yourbasic.org/golang/generate-number-random-range/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-03-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Random string 随机字符串
  • Random string with restrictions 有限制的随机字符串
  • Before Go 1.10 在Go 1.10 之前
  • Further reading 延展阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档