Skip to content

Commit

Permalink
No home-grown cryptography
Browse files Browse the repository at this point in the history
  • Loading branch information
majst01 committed Sep 13, 2024
1 parent 185a1aa commit 596d0e7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 28 deletions.
44 changes: 16 additions & 28 deletions mac.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ package security

import (
"crypto/hmac"
crand "crypto/rand"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"math/rand"
"math/big"
"net/http"
"strings"
"time"
Expand Down Expand Up @@ -218,33 +217,22 @@ var randByteString = randomByteString
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func randomByteString(n int) []byte {
b := make([]byte, n)
for i := range b {
// FIXME convert to rand/v2 rand.N()
b[i] = letterBytes[secureRand.Intn(len(letterBytes))]
}
return b
}
ret := make([]byte, n)
i := 0
for {

// create a math/random with a secure source to get real random numbers
//
//nolint:gosec
var secureRand = rand.New(src)
var src cryptoSource
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes))))
if err != nil {
continue
}

type cryptoSource struct{}
ret[i] = letterBytes[num.Int64()]

func (s cryptoSource) Seed(seed int64) {
// crypto/rand does not need a seed
}
func (s cryptoSource) Int63() int64 {
return int64(s.Uint64() & ^uint64(1<<63))
}

func (s cryptoSource) Uint64() (v uint64) {
err := binary.Read(crand.Reader, binary.BigEndian, &v)
if err != nil {
panic(fmt.Sprintf("crypto/rand is unavailable, read failed with: %v", err))
i++
if i == n {
break
}
}
return v

return ret
}
3 changes: 3 additions & 0 deletions mac_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,4 +287,7 @@ func TestMacCalc2(t *testing.T) {
func Test_randomByteString(t *testing.T) {
// make sure that we dont rely on pseudo-random-numbers
require.NotEqual(t, "XVlBzgbaiCMRAjWwhTHctcuA", string(randomByteString(24)))
require.Len(t, randomByteString(24), 24)
require.Len(t, randomByteString(32), 32)

}

0 comments on commit 596d0e7

Please sign in to comment.