# Generate OTP's in GO

```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`](http://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.Int`](http://n.Int)`64()) + 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.

```go
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`](http://rand.New)`()` with a source that’s properly seeded, or switch entirely to `crypto/rand` for security-sensitive applications.

%[https://blog.dushyanth.in/randseed-deprecated-way-forward] 

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
