网络编程
位置:首页>> 网络编程>> Go语言>> Golang如何构造最佳随机密码详解

Golang如何构造最佳随机密码详解

作者:梦想画家  发布时间:2024-05-05 09:29:37 

标签:golang,随机,密码

为了保护系统或数据安全,我们需要最佳随机密码。这里使用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

来源:https://blog.csdn.net/neweastsun/article/details/128493527

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com