Helpers that are meant to be copied, pasted and modified... not imported.
The secretbox library is intended to minimize the number of ways to screw things up, but using it still requires some setup.
func Seal(data, key []byte) []byte {
if len(key) != 32 {
panic("invalid key length")
}
var secretKey [32]byte
var nonce [24]byte
copy(secretKey[:], key)
copy(nonce[:], RandBytes(24))
return secretbox.Seal(nonce[:], []byte(data), &nonce, &secretKey)
}
func Unseal(data, key []byte) ([]byte, error) {
if len(key) != 32 {
panic("invalid key length")
}
var secretKey [32]byte
var nonce [24]byte
copy(secretKey[:], key)
copy(nonce[:], data[:24])
decrypted, ok := secretbox.Open(nil, data[24:], &nonce, &secretKey)
if !ok {
return nil, errors.New("decryption failure")
}
return decrypted, nil
}
func RandBytes(len int) []byte {
d := make([]byte, len)
if _, err := io.ReadFull(rand.Reader, d); err != nil {
panic(err)
}
return d
}
func RandString(length int) string {
r := RandBytes((length/4 + 1) * 3)
encoded := base64.RawURLEncoding.EncodeToString(r)
return encoded[0:length]
}
func Dedupe(list []string) []string {
result := make([]string, 0, len(list))
m := make(map[string]struct{})
for _, el := range list {
if _, ok := m[el]; !ok {
result = append(result, el)
m[el] = struct{}{}
}
}
return result
}