Home > Blog
Data: February 22, 2022 Categorie: software engineering Tag: tech programming go

Generazione di codici OTP in GO

Molti apprezzano Python per l’ampia disponibilità di librerie con le quali si riesce a fare un po’ di tutto. In realtà anche Go non se la passa male in quanto a disponibilità di strumenti che ci supportano nella programmazione.

In questo esempio potete vedere come generare dei codici OTP da utilizzarsi in un sistema di autenticazione a due fattori. Il programma crea un codice segreto con il quale inizializzare il generatore di codici e poi restituisce un codice OTP di esempio con la relativa durata residua (quella massima è di 30 secondi).

Il sistema genera sia un URL che un codice QR che possono essere importati in Google Authenticator in modo da generare codici in sincronia con quelli prodotti da un software come questo se dovesse riutilizzare sempre la stessa chiave segreta generata.

Roba semplice? Sì ma utile 😉

package main

import (
	"crypto/sha1"
	"fmt"
	"os"

	"github.com/aaronarduino/goqrsvg"
	svg "github.com/ajstarks/svgo"
	"github.com/boombuler/barcode/qr"
	"gopkg.in/jcmturner/gootp.v1"
)

func main() {
	// Generate a secret key of 20 bytes to initialize the OTP generator
	secret, err := gootp.GenerateOTPSecret(20)
	if err != nil {
		fmt.Println("Error generating OTP secret:", err)
		return
	}

	// Create the OTP code for the current datetime with its remaining time
	sha1Func := sha1.New
	otp, timeRemaining, err := gootp.TOTPNow(secret, sha1Func, 6)

	if err != nil {
		fmt.Println("Error generating OTP code:", err)
		return
	}

	// Define a result URI to be imported in Google Authenticator
	uri := "otpauth://totp/Demo:fabrizio@fgiamma.org?secret=" + secret + "&issuer=Fabrizio"

	// Create a svg test file
	f, err := os.Create("test.svg")
	if err != nil {
		fmt.Println("Error opening file")
		return
	}

	s := svg.New(f)

	// Create the barcode
	qrCode, _ := qr.Encode(uri, qr.M, qr.Auto)

	// Write QR code to SVG
	qs := goqrsvg.NewQrSVG(qrCode, 5)
	qs.StartQrSVG(s)
	qs.WriteQrSVG(s)

	s.End()

	fmt.Println("OTP Secret code:", secret)
	fmt.Println("Generated OTP:", otp)
	fmt.Println("Remaining time:", timeRemaining, "seconds")
	fmt.Println("Google Authenticator URI:", uri)

	fmt.Println("The generated SVG file contains a barcode ready to be imported in Google Authenticator")
}

Commenti

comments powered by Disqus