File: tokens.go

package info (click to toggle)
kitty 0.42.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 28,564 kB
  • sloc: ansic: 82,787; python: 55,191; objc: 5,122; sh: 1,295; xml: 364; makefile: 143; javascript: 78
file content (42 lines) | stat: -rw-r--r-- 790 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>

package secrets

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"fmt"
)

var _ = fmt.Print

const DEFAULT_NUM_OF_BYTES_FOR_TOKEN = 32

func TokenBytes(nbytes ...int) ([]byte, error) {
	if len(nbytes) == 0 {
		nbytes = []int{DEFAULT_NUM_OF_BYTES_FOR_TOKEN}
	}
	buf := make([]byte, nbytes[0])
	_, err := rand.Read(buf)
	if err != nil {
		return nil, err
	}
	return buf, nil
}

func TokenHex(nbytes ...int) (string, error) {
	b, err := TokenBytes(nbytes...)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(b), nil
}

func TokenBase64(nbytes ...int) (string, error) {
	b, err := TokenBytes(nbytes...)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(b), nil
}