Last active
April 5, 2019 16:12
-
-
Save ppetko/b40a6279055ea3d27f053777f141c7bd to your computer and use it in GitHub Desktop.
Random String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Sources of randomness from the environment include inter-keyboard | |
timings, inter-interrupt timings from some interrupts, and other | |
events which are both non-deterministic and hard for an | |
outside observer to measure. Randomness from these sources are | |
added to an entropy pool, which is mixed using a CRC-like function. | |
As random bytes are mixed into the entropy pool, the routines keep | |
an estimate of how many bits of randomness have been stored into | |
the random number generator internal state. | |
*/ | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"os/exec" | |
"strconv" | |
) | |
const ( | |
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
Numerals = "1234567890" | |
specialChars = "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:`" | |
) | |
var ( | |
//Seed function to initialize the default Source if different behavior is required for each run. | |
seededRand *rand.Rand = rand.New(rand.NewSource(getCPUNoise())) | |
pool = Alphabet + Numerals + specialChars | |
) | |
// Gather interrupts and CPU context switches from vmstat | |
func getCPUNoise() int64 { | |
cmd := "vmstat -s | egrep '(interrupts| CPU context switches)' | awk '{print $1}'| xargs | tr -d ' \n'" | |
out, err := exec.Command("bash", "-c", cmd).Output() | |
if err != nil { | |
panic(err) | |
} | |
str2 := string(out) | |
randomDigit, err := strconv.ParseInt(str2, 10, 64) | |
return randomDigit | |
} | |
// Generate a random string of A-Z chars with len = l | |
func randomString(l int) string { | |
bytes := make([]byte, l) | |
for i := 0; i < l; i++ { | |
bytes[i] = pool[seededRand.Intn(len(pool))] | |
} | |
return string(bytes) | |
} | |
func main() { | |
fmt.Println(randomString(64)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment