Home >Backend Development >Golang >How to implement TOTP algorithm using Golang

How to implement TOTP algorithm using Golang

PHPz
PHPzOriginal
2023-04-10 09:03:481558browse

TOTP is a time-based one-time password, an authentication method proposed to enhance security. It uses server and client clocks to generate short-term, one-time passwords, thereby avoiding the risk of passwords being intercepted during network transmission. Through the TOTP algorithm, both the client and the server can calculate the same token value, thus effectively ensuring the security of the system. This article will introduce how to use Golang to implement the TOTP algorithm.

TOTP algorithm introduction

TOTP (Time-Based One-Time Password) algorithm is actually an improved version of the HOTP algorithm. It originates from the RFC 6238 specification and is a one-time password technology based on time synchronization. The basic principle of the TOTP algorithm is to generate a one-time OTP response code based on the preset key, current time and other parameters.

The basic process of the entire algorithm is: the client generates a new OTP every once in a while, and the server can also generate the same OTP through the same algorithm. If the OTP calculated by the client and the server are consistent, the verification passes, otherwise the verification fails.

The security of the TOTP algorithm depends on the randomness of the preset key and the current time. Therefore, when the key and time are random, the TOTP algorithm can provide high security.

Golang implements TOTP algorithm

To implement the TOTP algorithm in Golang, you need to use the HMAC function in the crypto package and the hash function in the sha1 package. Golang provides many commonly used hash functions, such as SHA1, SHA256, etc., so you can choose the corresponding hash function according to actual needs. This article uses the SHA1 algorithm as an example to demonstrate how to implement the TOTP algorithm.

func TOTPToken(secret string) string {
    key, _ := base32.StdEncoding.DecodeString(secret)
    hash := hmac.New(sha1.New, key)
    hash.Write([]byte(time.Now().UTC().Format("2006-01-02 15:04:05")))
    hmacValue := hash.Sum(nil)

    offset := int(hmacValue[len(hmacValue)-1] & 0xf)
    truncatedHash := hmacValue[offset : offset+4]
    truncatedHash[0] = truncatedHash[0] & 0x7f
    token := fmt.Sprintf("%06d", binary.BigEndian.Uint32(truncatedHash))

    return token
}

In the above code, the secret parameter is the default key and needs to be a standard base32 encoded string. In the TOTPToken function, first decode the key into a byte array key, then use the hmac.New function to generate an hmac object, pass the current UTC time to the Write method in string format, and calculate the hash value. Subsequently, a 4-byte fragment is intercepted from the hash value and used to generate the OTP response code (truncatedHash). Finally, the truncatedHash is decoded into a 32-bit unsigned integer and converted into a 6-bit string (token) as the response result of the TOTP algorithm.

Testing the TOTP algorithm

Before using the TOTP algorithm, the user needs to be assigned a key, which is the same as the key on the server. You can use a third-party library (such as Google Authenticator) to generate a key and print it out as a QR code so that users can scan the QR code to obtain the key when using it.

The following is a simple example, including client and server side code.

Client code:

package main

import (
    "fmt"
)

func main() {
    secret := "MZXW6YTBOI======"
    token := TOTPToken(secret)
    fmt.Println(token)
}

Server code:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    secret := "MZXW6YTBOI======"
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(TOTPToken(secret)))
    })

    fmt.Println("Server started at http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

In the above code, we built a simple web server using the API provided by the "http" package, The current TOTP response code can be obtained by requesting http://localhost:8080/totp. In addition, we provide a client program so that you can test whether the algorithm is correct while debugging.

Summary

TOTP is a one-time password technology that improves authentication security. This article focuses on how to implement the TOTP algorithm using Golang and provides a test example. By mastering this algorithm, we can enhance the security of our applications and avoid the risk of password interception.

The above is the detailed content of How to implement TOTP algorithm using Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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