fix xsrf and added nonce

This commit is contained in:
ston1th 2025-10-15 22:51:08 +02:00
commit 809627b538
208 changed files with 7166 additions and 4278 deletions

View file

@ -69,6 +69,13 @@ func main() {
}
```
If you have Go 1.23 or better, you can iterate over the set bits like so:
```go
for i := range b.EachSet() {}
```
Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc
@ -157,3 +164,13 @@ Before committing the code, please check if it passes tests, has adequate covera
go test
go test -cover
```
## Stars
[![Star History Chart](https://api.star-history.com/svg?repos=bits-and-blooms/bitset&type=Date)](https://www.star-history.com/#bits-and-blooms/bitset&Date)
## Further reading
<p>Mastering Programming: From Testing to Performance in Go</p>
<div><a href="https://www.amazon.com/dp/B0FMPGSWR5"><img style="margin-left: auto; margin-right: auto;" src="https://m.media-amazon.com/images/I/61feneHS7kL._SL1499_.jpg" alt="" width="250px" /></a></div>

View file

@ -905,7 +905,9 @@ func (b *BitSet) DifferenceCardinality(compare *BitSet) uint {
l = b.wordCount()
}
cnt := uint64(0)
cnt += popcntMaskSlice(b.set[:l], compare.set[:l])
if l > 0 {
cnt += popcntMaskSlice(b.set[:l], compare.set[:l])
}
cnt += popcntSlice(b.set[l:])
return uint(cnt)
}
@ -960,6 +962,9 @@ func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) {
func (b *BitSet) IntersectionCardinality(compare *BitSet) uint {
panicIfNull(b)
panicIfNull(compare)
if b.length == 0 || compare.length == 0 {
return 0
}
b, compare = sortByLength(b, compare)
cnt := popcntAndSlice(b.set, compare.set)
return uint(cnt)
@ -1016,7 +1021,10 @@ func (b *BitSet) UnionCardinality(compare *BitSet) uint {
panicIfNull(b)
panicIfNull(compare)
b, compare = sortByLength(b, compare)
cnt := popcntOrSlice(b.set, compare.set)
cnt := uint64(0)
if len(b.set) > 0 {
cnt += popcntOrSlice(b.set, compare.set)
}
if len(compare.set) > len(b.set) {
cnt += popcntSlice(compare.set[len(b.set):])
}
@ -1071,7 +1079,10 @@ func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint {
panicIfNull(b)
panicIfNull(compare)
b, compare = sortByLength(b, compare)
cnt := popcntXorSlice(b.set, compare.set)
cnt := uint64(0)
if len(b.set) > 0 {
cnt += popcntXorSlice(b.set, compare.set)
}
if len(compare.set) > len(b.set) {
cnt += popcntSlice(compare.set[len(b.set):])
}
@ -1385,16 +1396,36 @@ func (b *BitSet) UnmarshalJSON(data []byte) error {
// Rank returns the number of set bits up to and including the index
// that are set in the bitset.
// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics
func (b *BitSet) Rank(index uint) uint {
if index >= b.length {
return b.Count()
func (b *BitSet) Rank(index uint) (rank uint) {
index++ // Rank is up to and including
// needed more than once
length := len(b.set)
// TODO: built-in min requires go1.21 or later
// idx := min(int(index>>6), len(b.set))
idx := int(index >> 6)
if idx > length {
idx = length
}
leftover := (index + 1) & 63
answer := uint(popcntSlice(b.set[:(index+1)>>6]))
if leftover != 0 {
answer += uint(bits.OnesCount64(b.set[(index+1)>>6] << (64 - leftover)))
// sum up the popcounts until idx ...
// TODO: cannot range over idx (...): requires go1.22 or later
// for j := range idx {
for j := 0; j < idx; j++ {
if w := b.set[j]; w != 0 {
rank += uint(bits.OnesCount64(w))
}
}
return answer
// ... plus partial word at idx,
// make Rank inlineable and faster in the end
// don't test index&63 != 0, just add, less branching
if idx < length {
rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63)))
}
return
}
// Select returns the index of the jth set bit, where j is the argument.
@ -1418,18 +1449,13 @@ func (b *BitSet) Select(index uint) uint {
// top detects the top bit set
func (b *BitSet) top() (uint, bool) {
panicIfNull(b)
idx := len(b.set) - 1
for ; idx >= 0 && b.set[idx] == 0; idx-- {
for idx := len(b.set) - 1; idx >= 0; idx-- {
if word := b.set[idx]; word != 0 {
return uint(idx<<log2WordSize+bits.Len64(word)) - 1, true
}
}
// no set bits
if idx < 0 {
return 0, false
}
return uint(idx*wordSize+bits.Len64(b.set[idx])) - 1, true
return 0, false
}
// ShiftLeft shifts the bitset like << operation would do.
@ -1458,7 +1484,7 @@ func (b *BitSet) ShiftLeft(bits uint) {
dst := b.set
// not using extendSet() to avoid unneeded data copying
nsize := wordsNeeded(top + bits)
nsize := wordsNeeded(top + bits + 1)
if len(b.set) < nsize {
dst = make([]uint64, nsize)
}
@ -1505,7 +1531,7 @@ func (b *BitSet) ShiftRight(bits uint) {
return
}
if bits >= top {
if bits > top {
b.set = make([]uint64, wordsNeeded(b.length))
return
}

View file

@ -0,0 +1,23 @@
//go:build go1.23
// +build go1.23
package bitset
import (
"iter"
"math/bits"
)
func (b *BitSet) EachSet() iter.Seq[uint] {
return func(yield func(uint) bool) {
for wordIndex, word := range b.set {
idx := 0
for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) {
if !yield(uint(wordIndex<<log2WordSize + idx + trail)) {
return
}
idx += trail + 1
}
}
}
}

View file

@ -2,58 +2,51 @@ package bitset
import "math/bits"
func popcntSlice(s []uint64) uint64 {
var cnt int
func popcntSlice(s []uint64) (cnt uint64) {
for _, x := range s {
cnt += bits.OnesCount64(x)
cnt += uint64(bits.OnesCount64(x))
}
return uint64(cnt)
return
}
func popcntMaskSlice(s, m []uint64) uint64 {
var cnt int
// this explicit check eliminates a bounds check in the loop
if len(m) < len(s) {
panic("mask slice is too short")
}
func popcntMaskSlice(s, m []uint64) (cnt uint64) {
// The next line is to help the bounds checker, it matters!
_ = m[len(s)-1] // BCE
for i := range s {
cnt += bits.OnesCount64(s[i] &^ m[i])
cnt += uint64(bits.OnesCount64(s[i] &^ m[i]))
}
return uint64(cnt)
return
}
func popcntAndSlice(s, m []uint64) uint64 {
var cnt int
// this explicit check eliminates a bounds check in the loop
if len(m) < len(s) {
panic("mask slice is too short")
}
// popcntAndSlice computes the population count of the AND of two slices.
// It assumes that len(m) >= len(s) > 0.
func popcntAndSlice(s, m []uint64) (cnt uint64) {
// The next line is to help the bounds checker, it matters!
_ = m[len(s)-1] // BCE
for i := range s {
cnt += bits.OnesCount64(s[i] & m[i])
cnt += uint64(bits.OnesCount64(s[i] & m[i]))
}
return uint64(cnt)
return
}
func popcntOrSlice(s, m []uint64) uint64 {
var cnt int
// this explicit check eliminates a bounds check in the loop
if len(m) < len(s) {
panic("mask slice is too short")
}
// popcntOrSlice computes the population count of the OR of two slices.
// It assumes that len(m) >= len(s) > 0.
func popcntOrSlice(s, m []uint64) (cnt uint64) {
// The next line is to help the bounds checker, it matters!
_ = m[len(s)-1] // BCE
for i := range s {
cnt += bits.OnesCount64(s[i] | m[i])
cnt += uint64(bits.OnesCount64(s[i] | m[i]))
}
return uint64(cnt)
return
}
func popcntXorSlice(s, m []uint64) uint64 {
var cnt int
// this explicit check eliminates a bounds check in the loop
if len(m) < len(s) {
panic("mask slice is too short")
}
// popcntXorSlice computes the population count of the XOR of two slices.
// It assumes that len(m) >= len(s) > 0.
func popcntXorSlice(s, m []uint64) (cnt uint64) {
// The next line is to help the bounds checker, it matters!
_ = m[len(s)-1] // BCE
for i := range s {
cnt += bits.OnesCount64(s[i] ^ m[i])
cnt += uint64(bits.OnesCount64(s[i] ^ m[i]))
}
return uint64(cnt)
return
}

View file

@ -1,6 +1,8 @@
package barcode
import "image"
import (
"image"
)
const (
TypeAztec = "Aztec"
@ -40,3 +42,7 @@ type BarcodeIntCS interface {
Barcode
CheckSum() int
}
type BarcodeColor interface {
ColorScheme() ColorScheme
}

39
vendor/github.com/boombuler/barcode/color_scheme.go generated vendored Normal file
View file

@ -0,0 +1,39 @@
package barcode
import "image/color"
// ColorScheme defines a structure for color schemes used in barcode rendering.
// It includes the color model, background color, and foreground color.
type ColorScheme struct {
Model color.Model // Color model to be used (e.g., grayscale, RGB, RGBA)
Background color.Color // Color of the background
Foreground color.Color // Color of the foreground (e.g., bars in a barcode)
}
// ColorScheme8 represents a color scheme with 8-bit grayscale colors.
var ColorScheme8 = ColorScheme{
Model: color.GrayModel,
Background: color.Gray{Y: 255},
Foreground: color.Gray{Y: 0},
}
// ColorScheme16 represents a color scheme with 16-bit grayscale colors.
var ColorScheme16 = ColorScheme{
Model: color.Gray16Model,
Background: color.White,
Foreground: color.Black,
}
// ColorScheme24 represents a color scheme with 24-bit RGB colors.
var ColorScheme24 = ColorScheme{
Model: color.RGBAModel,
Background: color.RGBA{255, 255, 255, 255},
Foreground: color.RGBA{0, 0, 0, 255},
}
// ColorScheme32 represents a color scheme with 32-bit RGBA colors, which is similar to ColorScheme24 but typically includes alpha for transparency.
var ColorScheme32 = ColorScheme{
Model: color.RGBAModel,
Background: color.RGBA{255, 255, 255, 255},
Foreground: color.RGBA{0, 0, 0, 255},
}

View file

@ -54,8 +54,8 @@ func (e Encoding) String() string {
return ""
}
// Encode returns a QR barcode with the given content, error correction level and uses the given encoding
func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) {
// Encode returns a QR barcode with the given content and color scheme, error correction level and uses the given encoding
func EncodeWithColor(content string, level ErrorCorrectionLevel, mode Encoding, color barcode.ColorScheme) (barcode.Barcode, error) {
bits, vi, err := mode.getEncoder()(content, level)
if err != nil {
return nil, err
@ -63,19 +63,23 @@ func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.
blocks := splitToBlocks(bits.IterateBytes(), vi)
data := blocks.interleave(vi)
result := render(data, vi)
result := render(data, vi, color)
result.content = content
return result, nil
}
func render(data []byte, vi *versionInfo) *qrcode {
func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) {
return EncodeWithColor(content, level, mode, barcode.ColorScheme16)
}
func render(data []byte, vi *versionInfo, color barcode.ColorScheme) *qrcode {
dim := vi.modulWidth()
results := make([]*qrcode, 8)
for i := 0; i < 8; i++ {
results[i] = newBarcode(dim)
results[i] = newBarCodeWithColor(dim, color)
}
occupied := newBarcode(dim)
occupied := newBarCodeWithColor(dim, color)
setAll := func(x int, y int, val bool) {
occupied.Set(x, y, true)

View file

@ -13,6 +13,7 @@ type qrcode struct {
dimension int
data *utils.BitList
content string
color barcode.ColorScheme
}
func (qr *qrcode) Content() string {
@ -24,7 +25,11 @@ func (qr *qrcode) Metadata() barcode.Metadata {
}
func (qr *qrcode) ColorModel() color.Model {
return color.Gray16Model
return qr.color.Model
}
func (c *qrcode) ColorScheme() barcode.ColorScheme {
return c.color
}
func (qr *qrcode) Bounds() image.Rectangle {
@ -33,9 +38,9 @@ func (qr *qrcode) Bounds() image.Rectangle {
func (qr *qrcode) At(x, y int) color.Color {
if qr.Get(x, y) {
return color.Black
return qr.color.Foreground
}
return color.White
return qr.color.Background
}
func (qr *qrcode) Get(x, y int) bool {
@ -158,9 +163,14 @@ func (qr *qrcode) calcPenaltyRule4() uint {
return uint(math.Min(floor, ceil) * 10)
}
func newBarcode(dim int) *qrcode {
func newBarCodeWithColor(dim int, color barcode.ColorScheme) *qrcode {
res := new(qrcode)
res.dimension = dim
res.data = utils.NewBitList(dim * dim)
res.color = color
return res
}
func newBarcode(dim int) *qrcode {
return newBarCodeWithColor(dim, barcode.ColorScheme16)
}

View file

@ -49,11 +49,22 @@ func (bc *intCSscaledBC) CheckSum() int {
// Scale returns a resized barcode with the given width and height.
func Scale(bc Barcode, width, height int) (Barcode, error) {
var fill color.Color
if v, ok := bc.(BarcodeColor); ok {
fill = v.ColorScheme().Background
} else {
fill = color.White
}
return ScaleWithFill(bc, width, height, fill)
}
// Scale returns a resized barcode with the given width, height and fill color.
func ScaleWithFill(bc Barcode, width, height int, fill color.Color) (Barcode, error) {
switch bc.Metadata().Dimensions {
case 1:
return scale1DCode(bc, width, height)
return scale1DCode(bc, width, height, fill)
case 2:
return scale2DCode(bc, width, height)
return scale2DCode(bc, width, height, fill)
}
return nil, errors.New("unsupported barcode format")
@ -72,7 +83,7 @@ func newScaledBC(wrapped Barcode, wrapperFunc wrapFunc, rect image.Rectangle) Ba
return result
}
func scale2DCode(bc Barcode, width, height int) (Barcode, error) {
func scale2DCode(bc Barcode, width, height int, fill color.Color) (Barcode, error) {
orgBounds := bc.Bounds()
orgWidth := orgBounds.Max.X - orgBounds.Min.X
orgHeight := orgBounds.Max.Y - orgBounds.Min.Y
@ -87,12 +98,12 @@ func scale2DCode(bc Barcode, width, height int) (Barcode, error) {
wrap := func(x, y int) color.Color {
if x < offsetX || y < offsetY {
return color.White
return fill
}
x = (x - offsetX) / factor
y = (y - offsetY) / factor
if x >= orgWidth || y >= orgHeight {
return color.White
return fill
}
return bc.At(x, y)
}
@ -104,7 +115,7 @@ func scale2DCode(bc Barcode, width, height int) (Barcode, error) {
), nil
}
func scale1DCode(bc Barcode, width, height int) (Barcode, error) {
func scale1DCode(bc Barcode, width, height int, fill color.Color) (Barcode, error) {
orgBounds := bc.Bounds()
orgWidth := orgBounds.Max.X - orgBounds.Min.X
factor := int(float64(width) / float64(orgWidth))
@ -116,12 +127,12 @@ func scale1DCode(bc Barcode, width, height int) (Barcode, error) {
wrap := func(x, y int) color.Color {
if x < offsetX {
return color.White
return fill
}
x = (x - offsetX) / factor
if x >= orgWidth {
return color.White
return fill
}
return bc.At(x, 0)
}

View file

@ -12,6 +12,7 @@ type base1DCode struct {
*BitList
kind string
content string
color barcode.ColorScheme
}
type base1DCodeIntCS struct {
@ -28,7 +29,11 @@ func (c *base1DCode) Metadata() barcode.Metadata {
}
func (c *base1DCode) ColorModel() color.Model {
return color.Gray16Model
return c.color.Model
}
func (c *base1DCode) ColorScheme() barcode.ColorScheme {
return c.color
}
func (c *base1DCode) Bounds() image.Rectangle {
@ -37,9 +42,9 @@ func (c *base1DCode) Bounds() image.Rectangle {
func (c *base1DCode) At(x, y int) color.Color {
if c.GetBit(x) {
return color.Black
return c.color.Foreground
}
return color.White
return c.color.Background
}
func (c *base1DCodeIntCS) CheckSum() int {
@ -48,10 +53,20 @@ func (c *base1DCodeIntCS) CheckSum() int {
// New1DCodeIntCheckSum creates a new 1D barcode where the bars are represented by the bits in the bars BitList
func New1DCodeIntCheckSum(codeKind, content string, bars *BitList, checksum int) barcode.BarcodeIntCS {
return &base1DCodeIntCS{base1DCode{bars, codeKind, content}, checksum}
return &base1DCodeIntCS{base1DCode{bars, codeKind, content, barcode.ColorScheme16}, checksum}
}
// New1DCodeIntCheckSum creates a new 1D barcode where the bars are represented by the bits in the bars BitList
func New1DCodeIntCheckSumWithColor(codeKind, content string, bars *BitList, checksum int, color barcode.ColorScheme) barcode.BarcodeIntCS {
return &base1DCodeIntCS{base1DCode{bars, codeKind, content, color}, checksum}
}
// New1DCode creates a new 1D barcode where the bars are represented by the bits in the bars BitList
func New1DCode(codeKind, content string, bars *BitList) barcode.Barcode {
return &base1DCode{bars, codeKind, content}
return &base1DCode{bars, codeKind, content, barcode.ColorScheme16}
}
// New1DCode creates a new 1D barcode where the bars are represented by the bits in the bars BitList
func New1DCodeWithColor(codeKind, content string, bars *BitList, color barcode.ColorScheme) barcode.Barcode {
return &base1DCode{bars, codeKind, content, color}
}

View file

@ -1,3 +1,4 @@
// Package md2man aims in converting markdown into roff (man pages).
package md2man
import (

View file

@ -47,13 +47,13 @@ const (
tableStart = "\n.TS\nallbox;\n"
tableEnd = ".TE\n"
tableCellStart = "T{\n"
tableCellEnd = "\nT}\n"
tableCellEnd = "\nT}"
tablePreprocessor = `'\" t`
)
// NewRoffRenderer creates a new blackfriday Renderer for generating roff documents
// from markdown
func NewRoffRenderer() *roffRenderer { // nolint: golint
func NewRoffRenderer() *roffRenderer {
return &roffRenderer{}
}
@ -316,9 +316,8 @@ func (r *roffRenderer) handleTableCell(w io.Writer, node *blackfriday.Node, ente
} else if nodeLiteralSize(node) > 30 {
end = tableCellEnd
}
if node.Next == nil && end != tableCellEnd {
// Last cell: need to carriage return if we are at the end of the
// header row and content isn't wrapped in a "tablecell"
if node.Next == nil {
// Last cell: need to carriage return if we are at the end of the header row.
end += crTag
}
out(w, end)
@ -356,7 +355,7 @@ func countColumns(node *blackfriday.Node) int {
}
func out(w io.Writer, output string) {
io.WriteString(w, output) // nolint: errcheck
io.WriteString(w, output) //nolint:errcheck
}
func escapeSpecialChars(w io.Writer, text []byte) {
@ -395,7 +394,7 @@ func escapeSpecialCharsLine(w io.Writer, text []byte) {
i++
}
if i > org {
w.Write(text[org:i]) // nolint: errcheck
w.Write(text[org:i]) //nolint:errcheck
}
// escape a character
@ -403,7 +402,7 @@ func escapeSpecialCharsLine(w io.Writer, text []byte) {
break
}
w.Write([]byte{'\\', text[i]}) // nolint: errcheck
w.Write([]byte{'\\', text[i]}) //nolint:errcheck
}
}

View file

@ -1,26 +1,28 @@
version: "2"
run:
timeout: 1m
tests: true
linters:
disable-all: true
enable:
default: none
enable: # please keep this alphabetized
- asasalint
- asciicheck
- copyloopvar
- dupl
- errcheck
- forcetypeassert
- goconst
- gocritic
- gofmt
- goimports
- gosimple
- govet
- ineffassign
- misspell
- musttag
- revive
- staticcheck
- typecheck
- unused
issues:
exclude-use-default: false
max-issues-per-linter: 0
max-same-issues: 10

View file

@ -1,8 +1,13 @@
The Snappy compression format in the Go programming language.
To download and install from source:
To use as a library:
$ go get github.com/golang/snappy
To use as a binary:
$ go install github.com/golang/snappy/cmd/snappytool@latest
$ cat decoded | ~/go/bin/snappytool -e > encoded
$ cat encoded | ~/go/bin/snappytool -d > decoded
Unless otherwise noted, the Snappy-Go source files are distributed
under the BSD-style license found in the LICENSE file.

View file

@ -27,7 +27,7 @@
// The unusual register allocation of local variables, such as R10 for the
// source pointer, matches the allocation used at the call site in encodeBlock,
// which makes it easier to manually inline this function.
TEXT ·emitLiteral(SB), NOSPLIT, $32-56
TEXT ·emitLiteral(SB), NOSPLIT, $40-56
MOVD dst_base+0(FP), R8
MOVD lit_base+24(FP), R10
MOVD lit_len+32(FP), R3
@ -261,7 +261,7 @@ extendMatchEnd:
// "var table [maxTableSize]uint16" takes up 32768 bytes of stack space. An
// extra 64 bytes, to call other functions, and an extra 64 bytes, to spill
// local variables (registers) during calls gives 32768 + 64 + 64 = 32896.
TEXT ·encodeBlock(SB), 0, $32896-56
TEXT ·encodeBlock(SB), 0, $32904-56
MOVD dst_base+0(FP), R8
MOVD src_base+24(FP), R7
MOVD src_len+32(FP), R14

View file

@ -57,6 +57,8 @@ type ValidateOpts struct {
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
// Encoder to use for output code.
Encoder otp.Encoder
}
// GenerateCode creates a HOTP passcode given a counter and secret.
@ -112,15 +114,34 @@ func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passc
(int(sum[offset+3]) & 0xff))
l := opts.Digits.Length()
mod := int32(value % int64(math.Pow10(l)))
switch opts.Encoder {
case otp.EncoderDefault:
mod := int32(value % int64(math.Pow10(l)))
if debug {
fmt.Printf("offset=%v\n", offset)
fmt.Printf("value=%v\n", value)
fmt.Printf("mod'ed=%v\n", mod)
if debug {
fmt.Printf("offset=%v\n", offset)
fmt.Printf("value=%v\n", value)
fmt.Printf("mod'ed=%v\n", mod)
}
passcode = opts.Digits.Format(mod)
case otp.EncoderSteam:
// Define the character set used by Steam Guard codes.
alphabet := []byte{
'2', '3', '4', '5', '6', '7', '8', '9', 'B', 'C',
'D', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q',
'R', 'T', 'V', 'W', 'X', 'Y',
}
radix := int64(len(alphabet))
for i := 0; i < l; i++ {
digit := value % radix
value /= radix
c := alphabet[digit]
passcode += string(c)
}
}
return opts.Digits.Format(mod), nil
return
}
// ValidateCustom validates an HOTP with customizable options. Most users should
@ -194,7 +215,7 @@ func Generate(opts GenerateOpts) (*otp.Key, error) {
v.Set("secret", b32NoPadding.EncodeToString(opts.Secret))
} else {
secret := make([]byte, opts.SecretSize)
_, err := opts.Rand.Read(secret)
_, err := io.ReadFull(opts.Rand, secret)
if err != nil {
return nil, err
}

27
vendor/github.com/pquerna/otp/otp.go generated vendored
View file

@ -154,12 +154,7 @@ func (k *Key) Digits() Digits {
q := k.url.Query()
if u, err := strconv.ParseUint(q.Get("digits"), 10, 64); err == nil {
switch u {
case 8:
return DigitsEight
default:
return DigitsSix
}
return Digits(u)
}
// Six is the most common value.
@ -183,6 +178,19 @@ func (k *Key) Algorithm() Algorithm {
}
}
// Encoder returns the encoder used or the default ("")
func (k *Key) Encoder() Encoder {
q := k.url.Query()
a := strings.ToLower(q.Get("encoder"))
switch a {
case "steam":
return EncoderSteam
default:
return EncoderDefault
}
}
// URL returns the OTP URL as a string
func (k *Key) URL() string {
return k.url.String()
@ -253,3 +261,10 @@ func (d Digits) Length() int {
func (d Digits) String() string {
return fmt.Sprintf("%d", d)
}
type Encoder string
const (
EncoderDefault Encoder = ""
EncoderSteam Encoder = "steam"
)

View file

@ -73,6 +73,8 @@ type ValidateOpts struct {
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
// Encoder to use for output code.
Encoder otp.Encoder
}
// GenerateCodeCustom takes a timepoint and produces a passcode using a
@ -86,6 +88,7 @@ func GenerateCodeCustom(secret string, t time.Time, opts ValidateOpts) (passcode
passcode, err = hotp.GenerateCodeCustom(secret, counter, hotp.ValidateOpts{
Digits: opts.Digits,
Algorithm: opts.Algorithm,
Encoder: opts.Encoder,
})
if err != nil {
return "", err
@ -113,8 +116,8 @@ func ValidateCustom(passcode string, secret string, t time.Time, opts ValidateOp
rv, err := hotp.ValidateCustom(passcode, counter, secret, hotp.ValidateOpts{
Digits: opts.Digits,
Algorithm: opts.Algorithm,
Encoder: opts.Encoder,
})
if err != nil {
return false, err
}
@ -184,7 +187,7 @@ func Generate(opts GenerateOpts) (*otp.Key, error) {
v.Set("secret", b32NoPadding.EncodeToString(opts.Secret))
} else {
secret := make([]byte, opts.SecretSize)
_, err := opts.Rand.Read(secret)
_, err := io.ReadFull(opts.Rand, secret)
if err != nil {
return nil, err
}