日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Golang如何構造最佳隨機密碼詳解_Golang

作者:夢想畫家 ? 更新時間: 2023-02-12 編程語言

為了保護系統(tǒng)或數(shù)據(jù)安全,我們需要最佳隨機密碼。這里使用unix系統(tǒng)定義的文件設備/dev/random,從中獲取隨機數(shù)生成器的種子。

需求說明

定義程序goodPass.go,程序需要一個可選命令行參數(shù),指定生成密碼的長度,缺省長度為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函數(shù)生成一定范圍內(nèi)的,Intn()結果不包括末端數(shù)值。下面實現(xiàn)main函數(shù),處理命令行參數(shù),并從隨機文件設備中獲取隨機種子:

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)
}

首先處理命令行參數(shù),如果沒有指定長度,則取默認值10,否則解析命令行參數(shù)。

然后打開/dev/random 設備進行讀取,這里使用binary.Read是需要指定字節(jié)順序(binary.LittleEndian),這是為了構建int64類型,而不是獲得一串字節(jié)。這里為了展示如何從二進制文件讀內(nèi)容至Go類型。

binary.Read(f, binary.LittleEndian, &seed) 函數(shù)的源碼注釋為:

// 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字符。因此需要轉換整數(shù)值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

欄目分類
最近更新