Hướng dẫn sử dụng random trong golang
Nhưng sau đây là function đầy đủ mà bạn có thể tham khảo
Generating a Secure Random String in Go: Step-by-Step Guide
In many applications, whether it’s generating API keys, secure tokens, or simply creating unique identifiers, the need for a random string generator is common. In this blog post, we’ll walk through a Go function that generates secure random strings of a specified length using characters from a predefined set. We will also explain each part of the code for easy understanding.
Overview of the Function
The randomString
function generates a string of random characters by selecting from a predefined set of characters. It uses Go’s crypto/rand
package, which provides cryptographically secure random numbers, making this function ideal for security-sensitive applications.
Here’s the function we’ll be covering:
package main import ( "crypto/rand" "fmt" "math/big" ) const randomStringSource = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321_+=" // Function to generate a random string of length n func randomString(n int) string { // Slice to hold the generated runes result := make([]rune, n) // Convert randomStringSource to a slice of runes sourceRunes := []rune(randomStringSource) // Get the length of the source runes sourceLen := big.NewInt(int64(len(sourceRunes))) // Loop to generate each random character for i := range result { // Generate a random index within the bounds of sourceRunes randomIndex, err := rand.Int(rand.Reader, sourceLen) if err != nil { panic(err) // Handle error, it shouldn't happen often } // Assign the random rune to the result result[i] = sourceRunes[randomIndex.Int64()] } // Return the generated string return string(result) } func main() { // Generate and print a random string of length 20 fmt.Println(randomString(20)) }
Now, let’s break it down.
Step 1: Character Set
We start by defining the character set from which the random string will be generated. In this case, it’s a combination of lowercase letters, uppercase letters, digits, and some special characters:
const randomStringSource = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321_+="
This randomStringSource
is a string of allowed characters, and later, we’ll randomly pick characters from this set to form our random string.
Step 2: Convert the Character Set to Runes
Go strings are made up of bytes, but since we’re dealing with potentially multi-byte characters (even though we only use single-byte characters here), we convert our randomStringSource
into a slice of runes:
sourceRunes := []rune(randomStringSource)
Runes in Go are a representation of Unicode characters, and by converting our string to a slice of runes, we ensure that we handle each character correctly, even if it’s multi-byte.
Step 3: Generate a Random Index
To generate a random string, we need to randomly select characters from the sourceRunes
. For this, we generate random indices in the range of the length of sourceRunes
. We use crypto/rand.Int
to securely generate these random indices:
sourceLen := big.NewInt(int64(len(sourceRunes)))
This line stores the length of our sourceRunes
as a *big.Int
(since rand.Int
requires that type). Then, in a loop, we generate random numbers to use as indices:
randomIndex, err := rand.Int(rand.Reader, sourceLen)
This line generates a random *big.Int
in the range [0, len(sourceRunes)-1]
. The rand.Reader
is used here because it provides cryptographically secure random numbers.
Step 4: Build the Random String
Once we have the random index, we use it to select a character from the sourceRunes
. We repeat this process for the desired length of the random string:
result[i] = sourceRunes[randomIndex.Int64()]
This assigns a random character to the current position in the result
slice.
Step 5: Return the Random String
After the loop is done, we convert the result
slice (which holds the random runes) back to a string and return it:
return string(result)
Step 6: Handling Errors
If for some reason the random number generation fails (which is rare when using rand.Reader
), we panic. This ensures that our program doesn’t silently fail:
if err != nil { panic(err) }
While panic
may not be ideal in production code, it’s acceptable here because we are writing a utility function where failure is highly unlikely and should be caught early.
Step 7: Using the Function
To use the randomString
function, we simply call it with the desired string length. For example, to generate a random string of length 20:
fmt.Println(randomString(20))
This will print a secure random string like Yz23FgB1_cHkXpT2Q+=A
.
Conclusion
This randomString
function is an excellent tool for generating cryptographically secure random strings in Go. It can be used in a variety of scenarios where unique, unpredictable strings are needed, such as generating passwords, tokens, or unique identifiers.
Key Takeaways:
- We used Go’s
crypto/rand
package for secure random number generation. - The character set is customizable, allowing for flexibility in the types of strings you want to generate.
- The function is simple and efficient while maintaining security standards.
What’s Next?
You could extend this function to:
- Allow for custom character sets.
- Add error handling to gracefully handle cases where random number generation fails.
- Adjust the random string length for specific use cases.
This function can be a crucial part of security mechanisms in your Go applications, ensuring that random strings are both unpredictable and secure.
Happy coding!