One-time password (OTP) implementation in Shell, Python and Go
Introduction
One-time password (OTP) is a security mechanism that generates a unique password for each login attempt. It adds an extra layer of security to user accounts as the passwords expire immediately after use. OTP implementation can be done in different programming languages, including Shell, Python, and Go. In this article, we will discuss how OTP can be implemented in these languages.
OTP Implementation in Python
install pyotp
pip install pyotp
demo python code
import pyotp
totp = pyotp.TOTP('XXXXXXXX')
print(totp.now())
OTP Implementation in Go
install go-otp
go get -u github.com/hgfischer/go-otp
demo go code
package main
import (
"flag"
"fmt"
"strings"
"github.com/hgfischer/go-otp"
)
var (
length = flag.Uint("length", otp.DefaultLength, "OTP length")
period = flag.Uint("period", otp.DefaultPeriod, "Period in seconds")
)
func main() {
tokenMap := make(map[string]string)
tokenMap["OTP token"] = "XXXXXXXXX"
for keyName, keyToken := range tokenMap {
totp := &otp.TOTP{
Secret: strings.ToUpper(keyToken),
Length: uint8(*length),
Period: uint8(*period),
IsBase32Secret: true,
}
fmt.Printf("%s: %s\n", keyName, totp.Get())
}
}
OTP Implementation in Shell
install oathtool
## Debian & Ubuntu
apt install oathtool
## CentOS
sudo yum -y install oathtool
sudo dnf -y install oathtool
## Mac
brew install oathtool
demo command
oathtool -b --totp XXXXXXXXX
Conclusion
OTP is a simple and effective security mechanism that can be implemented in different programming languages. In this article, we discussed how OTP can be implemented in Shell, Python, and Go. While the implementation may vary, the basic principle remains the same: generating a unique password that expires immediately after use.