Skip to content

Instantly share code, notes, and snippets.

@kalafut
Last active December 21, 2018 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalafut/6c360f22c8fa5cf824019e4abf0048a1 to your computer and use it in GitHub Desktop.
Save kalafut/6c360f22c8fa5cf824019e4abf0048a1 to your computer and use it in GitHub Desktop.
Go Snippets

Helpers that are meant to be copied, pasted and modified... not imported.

Cryptography

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
}

Randomness

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]
}

Strings

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment