otp

package
v0.1.81 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2025 License: BSD-3-Clause Imports: 13 Imported by: 0

README

otp: Go / Golang 一次性密码实用程序

为什么要使用一次密码?

一次性密码(OTP)是一种可以仅通过密码来提高安全性的机制。当基于时间的OTP(TOTP)存储在用户的电话上,并与用户知道的内容(密码)结合使用时,您就可以轻松进行[多因素身份验证](http:en.wikipedia.orgwikiMulti- factor_authentication),而无需添加对SMS提供程序的依赖关系。许多流行的网站(包括Google,Github,Facebook,Salesforce等)都使用此密码和TOTP组合。

otp库使您可以轻松地将TOTP添加到自己的应用程序中,从而提高用户的安全性,以防止大规模密码泄露和恶意软件。

TOTP是标准化的并且被广泛部署,所以有很多 mobile clients and software implementations.

otp 支持/特性:

  • 生成QR Code图像以方便用户注册。
  • 基于时间的一次性密码算法(TOTP)(RFC 6238):基于时间的OTP,这是最常用的方法。
  • 基于HMAC的一次性密码算法(HOTP)(RFC 4226):TOTP所基于的基于计数器的OTP。
  • 两种算法的代码生成和验证。

应用程序中实现TOTP:

用户注册

有关工作注册工作流程的示例 Github has documented theirs:

  1. 为用户生成新的TOTP密钥。key,_ := totp.Generate(...).
  2. 为用户显示密钥的密文和QR码。 key.Secret()key.Image(...).
  3. 测试用户可以成功使用其TOTP。totp.Validate(...).
  4. 在您的后端中为用户存储TOTP 密钥。 key.Secret()
  5. 向用户提供“恢复码”。 (参见下面的恢复代码)
代码生成
  • TOTPHOTP情况下,都可以使用GenerateCode函数和一个计数器或time.Time结构来生成与大多数实现兼容的有效代码。
  • 对于不常见或自定义的设置,或捕获不太可能的错误,请在任一模块中使用GenerateCodeCustom
验证
  1. 正常提示和验证用户密码。
  2. 如果用户启用了TOTP,提示请输入TOTP密码。
  3. 从您的后端检索用户的TOTP密钥。
  4. 验证用户的密码。totp.Validate(...)
恢复码

当用户无法访问其TOTP设备时,他们将再也无法访问其帐户。因为TOTP通常配置在可能丢失,被盗或损坏的移动设备上,所以这是一个普遍的问题。因此,许多提供商将其“备份代码”或“恢复代码”提供给其用户。这些是一组一次性使用的代码,可以代替TOTP使用。这些可以只是存储在后端中的随机生成的字符串。 Github's documentation provides an overview of the user experience.

Documentation

Overview

Package otp implements both HOTP and TOTP based one time passcodes in a Google Authenticator compatible manner.

When adding a TOTP for a user, you must store the "secret" value persistently. It is recommend to store the secret in an encrypted field in your datastore. Due to how TOTP works, it is not possible to store a hash for the secret value like you would a password.

To enroll a user, you must first generate an OTP for them. Google Authenticator supports using a QR code as an enrollment method:

import (
	"gitee.com/xingnan/toolbox/otp/totp"

	"bytes"
	"image/png"
)

key, err := totp.Generate(totp.GenerateOpts{
		Issuer: "Example.com",
		AccountName: "alice@example.com",
})

// Convert TOTP key into a QR code encoded as a PNG image.
var buf bytes.Buffer
img, err := key.Image(200, 200)
png.Encode(&buf, img)

// display the QR code to the user.
display(buf.Bytes())

// Now Validate that the user's successfully added the passcode.
passcode := promptForPasscode()
valid := totp.Validate(passcode, key.Secret())

if valid {
	// User successfully used their TOTP, save it to your backend!
	storeSecret("alice@example.com", key.Secret())
}

Validating a TOTP passcode is very easy, just prompt the user for a passcode and retrieve the associated user's previously stored secret.

import "gitee.com/xingnan/toolbox/otp/totp"

passcode := promptForPasscode()
secret := getSecret("alice@example.com")

valid := totp.Validate(passcode, secret)

if valid {
	// Success! continue login process.
}

Index

Constants

This section is empty.

Variables

View Source
var ErrGenerateMissingAccountName = errors.New("AccountName must be set")

When generating a Key, the Account Name must be set.

View Source
var ErrGenerateMissingIssuer = errors.New("Issuer must be set")

When generating a Key, the Issuer must be set.

View Source
var ErrValidateInputInvalidLength = errors.New("Input length unexpected")

The user provided passcode length was not expected.

View Source
var ErrValidateSecretInvalidBase32 = errors.New("Decoding of secret as base32 failed.")

Error when attempting to convert the secret from base32 to raw bytes.

Functions

This section is empty.

Types

type Algorithm

type Algorithm int

Algorithm represents the hashing function to use in the HMAC operation needed for OTPs.

const (
	// AlgorithmSHA1 should be used for compatibility with Google Authenticator.
	//
	// See https://github.com/pquerna/otp/issues/55 for additional details.
	AlgorithmSHA1 Algorithm = iota
	AlgorithmSHA256
	AlgorithmSHA512
	AlgorithmMD5
)

func (Algorithm) Hash

func (a Algorithm) Hash() hash.Hash

func (Algorithm) String

func (a Algorithm) String() string

type Digits

type Digits int

Digits represents the number of digits present in the user's OTP passcode. Six and Eight are the most common values.

const (
	DigitsSix   Digits = 6
	DigitsEight Digits = 8
)

func (Digits) Format

func (d Digits) Format(in int32) string

Format converts an integer into the zero-filled size for this Digits.

func (Digits) Length

func (d Digits) Length() int

Length returns the number of characters for this Digits.

func (Digits) String

func (d Digits) String() string

type Key

type Key struct {
	// contains filtered or unexported fields
}

Key represents an TOTP or HTOP key.

func NewKeyFromURL

func NewKeyFromURL(orig string) (*Key, error)

NewKeyFromURL creates a new Key from an TOTP or HOTP url.

The URL format is documented here:

https://github.com/google/google-authenticator/wiki/Key-Uri-Format

func (*Key) AccountName

func (k *Key) AccountName() string

AccountName returns the name of the user's account.

func (*Key) Image

func (k *Key) Image(width int, height int) (image.Image, error)

Image returns an QR-Code image of the specified width and height, suitable for use by many clients like Google-Authenricator to enroll a user's TOTP/HOTP key.

func (*Key) Issuer

func (k *Key) Issuer() string

Issuer returns the name of the issuing organization.

func (*Key) Period

func (k *Key) Period() uint64

Period returns a tiny int representing the rotation time in seconds.

func (*Key) Secret

func (k *Key) Secret() string

Secret returns the opaque secret for this Key.

func (*Key) String

func (k *Key) String() string

func (*Key) Type

func (k *Key) Type() string

Type returns "hotp" or "totp".

func (*Key) URL

func (k *Key) URL() string

URL returns the OTP URL as a string

Directories

Path Synopsis
interop module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL