summaryrefslogtreecommitdiff
path: root/vendor/mellium.im/sasl/nonce.go
blob: 8e8666fd2f962abf90fe0ad197408660612ed2a6 (plain)
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
// Copyright 2016 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

package sasl

import (
	"encoding/base64"
	"io"
)

// Generates a nonce with n random bytes base64 encoded to ensure that it meets
// the criteria for inclusion in a SCRAM message.
func nonce(n int, r io.Reader) []byte {
	if n < 1 {
		panic("Cannot generate zero or negative length nonce")
	}
	b := make([]byte, n)
	n2, err := r.Read(b)
	switch {
	case err != nil:
		panic(err)
	case n2 != n:
		panic("Could not read enough randomness to generate nonce")
	}
	val := make([]byte, base64.RawStdEncoding.EncodedLen(n))
	base64.RawStdEncoding.Encode(val, b)

	return val
}