github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbfs/kbfscrypto/rand.go (about)

     1  // Copyright 2016 Keybase Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD
     3  // license that can be found in the LICENSE file.
     4  
     5  package kbfscrypto
     6  
     7  import (
     8  	"crypto/rand"
     9  
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  // UnexpectedShortCryptoRandRead indicates that fewer bytes were read
    14  // from crypto.rand.Read() than expected.
    15  type UnexpectedShortCryptoRandRead struct {
    16  }
    17  
    18  // Error implements the error interface for UnexpectedShortRandRead.
    19  func (e UnexpectedShortCryptoRandRead) Error() string {
    20  	return "Unexpected short read from crypto.rand.Read()"
    21  }
    22  
    23  // RandRead is a belt-and-suspenders wrapper around
    24  // crypto.rand.Read().
    25  func RandRead(buf []byte) error {
    26  	n, err := rand.Read(buf)
    27  	if err != nil {
    28  		return errors.WithStack(err)
    29  	}
    30  	// This is truly unexpected, as rand.Read() is supposed to
    31  	// return an error on a short read already!
    32  	if n != len(buf) {
    33  		return errors.WithStack(UnexpectedShortCryptoRandRead{})
    34  	}
    35  	return nil
    36  }