Skip to content

Instantly share code, notes, and snippets.

@Goodnessuc
Last active November 10, 2023 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Goodnessuc/481aee389c62cda7776e8e01933963f1 to your computer and use it in GitHub Desktop.
Save Goodnessuc/481aee389c62cda7776e8e01933963f1 to your computer and use it in GitHub Desktop.
Generate Cryptographically secure random values of any type in Go
// In this script, we'll create a function to generate secure random strings.
// First, define the function that generates the random string.
func generateRandomString(chars string, length int) string {
// Create an array of bytes with the specified length.
bytes := make([]byte, length)
// Use crypto/rand to fill the byte array with secure random bytes.
_, err := rand.Read(bytes)
if err != nil {
// If an error occurs, handle it appropriately.
fmt.Println("Error generating random string:", err)
}
// Now, let's create the random string character by character.
for index, element := range bytes {
// Calculate a random index within the character set range.
randomIndex := int(element) % len(chars)
// Replace the byte with a character from the character set.
bytes[index] = chars[randomIndex]
}
// Convert the byte array to a string and return the result.
return string(bytes)
}
// Example usage:
func main() {
// Define the character set to choose from.
characterSet := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// Specify the length of the random string.
randomStringLength := 16
// Generate a random string using our function.
randomString := generateRandomString(characterSet, randomStringLength)
// Display the generated random string.
fmt.Println("Generated Random String:", randomString)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment