Golang 构造最佳随机密码
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
为了保护系统或数据安全我们需要最佳随机密码。这里使用unix系统定义的文件设备/dev/random
从中获取随机数生成器的种子。
需求说明
定义程序goodPass.go程序需要一个可选命令行参数指定生成密码的长度缺省长度为10. 另外生成密码的ASCII从!
到z
,对应ascii码为33到122。
程序第一部分是导入相应的包
package main
import (
"encoding/binary"
"fmt"
"math/rand"
"os"
"path/filepath"
"strconv"
)
var MAX = 90
var MIN = 0
// Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n)
// from the default Source.
// It panics if n <= 0.
func random(min, max int) int {
return rand.Intn(max-min) + min
}
这里radmon函数生成一定范围内的Intn()结果不包括末端数值。下面实现main函数处理命令行参数并从随机文件设备中获取随机种子
func main() {
var LENGTH int64 = 10
if len(os.Args) != 2 {
fmt.Printf("usage: %s length\n", filepath.Base(os.Args[0]))
//os.Exit(1)
fmt.Printf("Default length is %d\n", LENGTH)
} else {
LENGTH, _ = strconv.ParseInt(os.Args[1], 10, 64)
}
f, _ := os.Open("/dev/random")
var seed int64
_ = binary.Read(f, binary.LittleEndian, &seed)
_ = f.Close()
rand.Seed(seed)
fmt.Println("Seed:", seed)
GenPass(LENGTH)
}
首先处理命令行参数如果没有指定长度则取默认值10否则解析命令行参数。
然后打开/dev/random
设备进行读取这里使用binary.Read
是需要指定字节顺序(binary.LittleEndian),这是为了构建int64类型而不是获得一串字节。这里为了展示如何从二进制文件读内容至Go类型。
binary.Read(f, binary.LittleEndian, &seed) 函数的源码注释为
// Read reads structured binary data from r into data.
// Data must be a pointer to a fixed-size value or a slice of fixed-size values.
// Bytes read from r are decoded using the specified byte order and written to successive fields of the data.
// When decoding boolean values, a zero byte is decoded as false, and any other non-zero byte is decoded as true.
最后一部分代码为
func GenPass(LENGTH int64) {
startChar := "!"
var i int64
for i = 0; i < LENGTH; i++ {
anInt := random(MIN, MAX)
newChar := string(startChar[0] + byte(anInt))
if newChar == " " {
i = i - i
continue
}
fmt.Print(newChar)
}
fmt.Println()
}
我们看到Go处理Ascii字符有点奇怪这是因为Go默认支持Unicode字符。因此需要转换整数值ascii字符对应代码为
newChar := string(startChar[0] + byte(anInt))
运行程序生成下列输出
$ go run goodPass.go 1
Seed: -5195038511418503382
b
$ go run goodPass.go 10
Seed: 8492864627151568776
k43Ve`+YD)
$ go run goodPass.go 50
Seed: -4276736612056007162
!=Gy+;XV>6eviuR=ST\u:Mk4Q875Y4YZiZhq&q_4Ih/]''`2:x