diff --git a/unikraft/export/v0/ukrandom/library.go b/unikraft/export/v0/ukrandom/library.go new file mode 100644 index 000000000..d9af3212d --- /dev/null +++ b/unikraft/export/v0/ukrandom/library.go @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2024, Unikraft GmbH and The KraftKit Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. +package ukrandom + +const LibraryName = "ukrandom" diff --git a/unikraft/export/v0/ukrandom/params.go b/unikraft/export/v0/ukrandom/params.go new file mode 100644 index 000000000..bf477e44d --- /dev/null +++ b/unikraft/export/v0/ukrandom/params.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2024, Unikraft GmbH and The KraftKit Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. +package ukrandom + +import ( + "crypto/rand" + "fmt" + "strings" + + "kraftkit.sh/unikraft/export/v0/ukargparse" +) + +var ParamRandomSeed = ukargparse.NewParamStrSlice("random", "seed", nil) + +// ExportedParams returns the parameters available by this exported library. +func ExportedParams() []ukargparse.Param { + return []ukargparse.Param{ + ParamRandomSeed, + } +} + +// RandomSeed are the 10 bytes that are required by the ukrandom library. +type RandomSeed [10]byte + +// NewRandomSeed generates a new set of true random bytes or nothing if error. +func NewRandomSeed() RandomSeed { + randomBytes := make([]byte, 10) + _, err := rand.Read(randomBytes) + if err != nil { + return RandomSeed{} + } + + var random RandomSeed + for i := 0; i < 10; i++ { + random[i] = randomBytes[i] + } + + return random +} + +// String implements fmt.Stringer and returns a valid set of random bytes. +func (rng RandomSeed) String() string { + var sb strings.Builder + + sb.WriteString("[ ") + for i := 0; i < 10; i++ { + sb.WriteString(fmt.Sprintf("%02x ", rng[i])) + } + sb.WriteString("]") + + return sb.String() +}