Skip to main content

Command Palette

Search for a command to run...

Generate OTP's in GO

Using crypto/rand (for Cryptographic Security)

Updated
2 min read
Generate OTP's in GO
D

A Full Stack Developer with a knack for creating engaging web experiences. Currently tinkering with GO.

package main

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

func generateSecureOTP() (int, error) {
    // Generate a random number in [1000, 9999]
    n, err := rand.Int(rand.Reader, big.NewInt(9000))
    if err != nil {
        return 0, err
    }
    return int(n.Int64()) + 1000, nil
}

func main() {
    otp, err := generateSecureOTP()
    if err != nil {
        fmt.Println("Error generating OTP:", err)
        return
    }
    fmt.Printf("Generated Secure OTP: %04d\n", otp)
}

Explanation of the Code

  1. rand.Int(rand.Reader, big.NewInt(9000)):

    • Generates a random number in the range [0, 8999]. Using 9000 ensures the number can go up to 8999.
  2. int(n.Int64()) + 1000:

    • Adds 1000 to shift the range from [0, 8999] to [1000, 9999], resulting in a secure 4-digit OTP.

Using math/rand

One simple way to generate a 6-digit OTP is by using the math/rand package, which provides basic random number generation. However, for true randomness (e.g., in production), it’s usually recommended to use crypto/rand, as it provides cryptographically secure random numbers.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func generateOTP() int {
    rand.Seed(time.Now().UnixNano()) // Seed with current time
    return 1000 + rand.Intn(9000) // Generate a random number in [1000, 9999]
}

func main() {
    otp := generateOTP()
    fmt.Printf("Generated OTP: %04d\n", otp)
}

Note: Starting with Go 1.20, rand.Seed() has been deprecated for cryptographic purposes due to its predictability and the availability of better, more secure options. Instead, for non-cryptographic random numbers, you should now create a new instance of math/rand using rand.New() with a source that’s properly seeded, or switch entirely to crypto/rand for security-sensitive applications.

If you generate OTPs using math/rand, an attacker could potentially guess the sequence if they know the seed, especially if it’s based on something predictable like the current timestamp. However, crypto/rand is resistant to this kind of attack because it pulls from sources that are practically unpredictable.

THE END

More from this blog

D

Dushyanth

18 posts