Documentation
¶
Overview ¶
randパッケージは、暗号学的に安全な乱数生成器を実装しています。
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var Reader io.Reader = rand.Reader
Readerは暗号学的に安全な乱数生成器のグローバルで共有されたインスタンスです。 並行使用に対して安全です。
- Linux、FreeBSD、Dragonfly、およびSolarisでは、Readerはgetrandom(2)を使用します。
- レガシーLinux(< 3.17)では、Readerは初回使用時に/dev/urandomを開きます。
- macOS、iOS、およびOpenBSDでは、Readerはarc4random_buf(3)を使用します。
- NetBSDでは、Readerはkern.arandom sysctlを使用します。
- Windowsでは、ReaderはProcessPrng APIを使用します。
- js/wasmでは、ReaderはWeb Crypto APIを使用します。
- wasip1/wasmでは、Readerはrandom_getを使用します。
FIPS 140-3モードでは、出力はSP 800-90A Rev. 1の 決定論的ランダムビット生成器(DRBG)を通過します。
Functions ¶
func Int ¶
Intは[0, max)の範囲の一様乱数値を返します。max <= 0の場合はパニックし、 rand.Readがエラーを返した場合はエラーを返します。
Example ¶
ExampleIntは0から99までの範囲(境界値を含む)で暗号学的に安全な擬似乱数を1つ出力します。
package main
import (
"github.com/shogo82148/std/crypto/rand"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/math/big"
)
func main() {
// rand.Readerを使用する場合、Intはエラーを返すことができません。
a, _ := rand.Int(rand.Reader, big.NewInt(100))
fmt.Println(a.Int64())
}
Output:
func Prime ¶
Primeは、指定されたビット長で高い確率で素数である数値を返します。 Primeは、rand.Readが返すエラーまたはbits < 2の場合にエラーを返します。
Go 1.26以降、安全なランダムバイトソースが常に使用され、GODEBUG=cryptocustomrand=1が 設定されない限りReaderは無視されます。この設定は将来のGoリリースで削除されます。 代わりに testing/cryptotest.SetGlobalRandom を使用してください。
Example ¶
ExamplePrimeは暗号学的に安全な擬似乱数64ビット素数を出力します。
package main
import (
"github.com/shogo82148/std/crypto/rand"
"github.com/shogo82148/std/fmt"
)
func main() {
// rand.Readerを使用し、bits >= 2の場合、Primeはエラーを返すことができません。
a, _ := rand.Prime(rand.Reader, 64)
fmt.Println(a.Int64())
}
Output:
func Read ¶
Readは暗号学的に安全な乱数バイトでbを埋めます。エラーを返すことはなく、 常にbを完全に埋めます。
Readは Reader に対して io.ReadFull を呼び出し、エラーが返された場合は プログラムを回復不可能にクラッシュさせます。デフォルトのReaderは、 レガシーLinuxシステム以外では決してエラーを返さないと文書化されているオペレーティングシステムAPIを使用します。
Example ¶
ExampleReadは暗号学的に安全な擬似乱数32バイトキーを出力します。
package main
import (
"github.com/shogo82148/std/crypto/rand"
"github.com/shogo82148/std/fmt"
)
func main() {
// Readは常に成功するため、エラーハンドリングは不要であることに注意してください。
key := make([]byte, 32)
rand.Read(key)
// キーは任意のバイト値を含む可能性があるため、キーを16進数で出力します。
fmt.Printf("% x\n", key)
}
Output:
func Text ¶ added in v1.25.0
func Text() string
Text returns a cryptographically random string using the standard RFC 4648 base32 alphabet for use when a secret string, token, password, or other text is needed. The result contains at least 128 bits of randomness, enough to prevent brute force guessing attacks and to make the likelihood of collisions vanishingly small. A future version may return longer texts as needed to maintain those properties.
Example ¶
ExampleTextはbase32でエンコードされたランダムキーを出力します。
package main
import (
"github.com/shogo82148/std/crypto/rand"
"github.com/shogo82148/std/fmt"
)
func main() {
key := rand.Text()
// キーはbase32で、表示しても安全です。
fmt.Println(key)
}
Output:
Types ¶
This section is empty.