2020-05-08 11:36:28 -04:00
|
|
|
package db
|
|
|
|
|
|
|
|
|
|
import (
|
2021-03-16 11:19:10 -04:00
|
|
|
"bytes"
|
2020-05-08 11:36:28 -04:00
|
|
|
"fmt"
|
2021-03-16 11:19:10 -04:00
|
|
|
"strings"
|
2020-05-08 11:36:28 -04:00
|
|
|
|
2020-11-05 16:54:03 -05:00
|
|
|
"github.com/hashicorp/boundary/internal/errors"
|
2021-07-14 17:31:58 -07:00
|
|
|
"github.com/hashicorp/go-secure-stdlib/base62"
|
2021-03-16 11:19:10 -04:00
|
|
|
"golang.org/x/crypto/blake2b"
|
2020-05-08 11:36:28 -04:00
|
|
|
)
|
|
|
|
|
|
2021-03-16 11:19:10 -04:00
|
|
|
func NewPrivateId(prefix string, opt ...Option) (string, error) {
|
|
|
|
|
return newId(prefix, opt...)
|
2020-06-29 08:18:57 -04:00
|
|
|
}
|
|
|
|
|
|
2020-05-08 11:36:28 -04:00
|
|
|
// NewPublicId creates a new public id with the prefix
|
2021-03-16 11:19:10 -04:00
|
|
|
func NewPublicId(prefix string, opt ...Option) (string, error) {
|
|
|
|
|
return newId(prefix, opt...)
|
2020-06-29 08:18:57 -04:00
|
|
|
}
|
|
|
|
|
|
2021-03-16 11:19:10 -04:00
|
|
|
func newId(prefix string, opt ...Option) (string, error) {
|
2020-12-09 10:11:38 -08:00
|
|
|
const op = "db.newId"
|
2020-05-08 11:36:28 -04:00
|
|
|
if prefix == "" {
|
2020-12-09 10:11:38 -08:00
|
|
|
return "", errors.New(errors.InvalidParameter, op, "missing prefix")
|
2020-05-08 11:36:28 -04:00
|
|
|
}
|
2021-03-16 11:19:10 -04:00
|
|
|
var publicId string
|
|
|
|
|
var err error
|
|
|
|
|
opts := GetOpts(opt...)
|
|
|
|
|
if len(opts.withPrngValues) > 0 {
|
|
|
|
|
sum := blake2b.Sum256([]byte(strings.Join(opts.withPrngValues, "|")))
|
|
|
|
|
reader := bytes.NewReader(sum[0:])
|
|
|
|
|
publicId, err = base62.RandomWithReader(10, reader)
|
|
|
|
|
} else {
|
|
|
|
|
publicId, err = base62.Random(10)
|
|
|
|
|
}
|
2020-05-08 11:36:28 -04:00
|
|
|
if err != nil {
|
2021-02-11 13:32:45 -06:00
|
|
|
return "", errors.Wrap(err, op, errors.WithMsg("unable to generate id"), errors.WithCode(errors.Io))
|
2020-05-08 11:36:28 -04:00
|
|
|
}
|
|
|
|
|
return fmt.Sprintf("%s_%s", prefix, publicId), nil
|
|
|
|
|
}
|