Home > Backend Development > Golang > How to Generate Secure Random Integers and Tokens Using 'crypto/rand'?

How to Generate Secure Random Integers and Tokens Using 'crypto/rand'?

DDD
Release: 2024-11-23 09:09:17
Original
989 people have browsed it

How to Generate Secure Random Integers and Tokens Using

Random Int Generation using "crypto/rand.Int"

Within the "crypto/rand" package lies the necessity to generate secure random integers. An example of how to achieve this between the range of 0 to 27 is below:

package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
)

func main() {
    nBig, err := rand.Int(rand.Reader, big.NewInt(27))
    if err != nil {
        panic(err)
    }
    n := nBig.Int64()
    fmt.Printf("Random int in [0,27): %d\n", n)
}
Copy after login

This function utilizes the "rand.Reader" and the "big.Int" type from "math/big" library to achieve cryptographic randomness beyond the int range.

Secure Token Generation

However, in the context of generating secure tokens, an alternative and more appropriate approach is recommended:

package main

import (
    "crypto/rand"
    "encoding/base32"
    "fmt"
)

func main() {
    token := getToken(10)
    fmt.Printf("Secure token: %s\n", token)
}

func getToken(length int) string {
    randomBytes := make([]byte, 32)
    _, err := rand.Read(randomBytes)
    if err != nil {
        panic(err)
    }
    return base32.StdEncoding.EncodeToString(randomBytes)[:length]
}
Copy after login

In this scenario, random bytes are generated, then encoded using "base32" to create a token. This approach is deemed sufficient for secure token generation.

The above is the detailed content of How to Generate Secure Random Integers and Tokens Using 'crypto/rand'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template