Go - 关于crypto / rand的示例 [英] Go - Example about crypto/rand
问题描述
可以举一个使用 crypto / rand
[1]的例子吗?
Could put a little example about the use of crypto/rand
[1]?
函数 Read
具有作为参数的字节数组。为什么?如果它访问 / dev / urandom 以获取随机数据。
The function Read
has as parameter an array of bytes. Why? If it access to /dev/urandom to get the random data.
func Read(b []byte) (n int, err os.Error)
[1] http://golang.org/pkg/crypto/rand/
推荐答案
func Read(b []byte) (n int, err os.Error)
读取
是一个帮助函数,调用 Reader.Read
。
Reader
定义为: var Reader io.Reader
。
Read
is a helper function that calls Reader.Read
. Reader
is defined as: var Reader io.Reader
.
io.Reader
是包装基本方法的接口。
io.Reader
is the interface that wraps the basic Read
method.
读取
读取
len(p)
/ code>。它返回读取的字节数( 0 <= n <= len(p)
)和遇到的任何错误。即使 Read
返回 n < len(p)
,它可能在调用期间使用 p
的全部作为临时空格。如果一些数据可用但不是 len(p)
字节,则读
通常返回可用的,更多
Read
reads up to len(p)
bytes into p
. It returns the number of bytes read (0 <= n <= len(p)
) and any error encountered. Even if Read
returns n < len(p)
, it may use all of p
as scratch space during the call. If some data is available but not len(p)
bytes, Read
conventionally returns what is available rather than block waiting for more.
在输入流末尾, Read
返回 0,os。 EOF
。 读取
可能返回非零数字字节,并带有非 nil
错误。特别地,排空输入的读取
可以返回n> 0,os.EOF
。
At the end of the input stream, Read
returns 0, os.EOF
. Read
may return a non-zero number of bytes with a non-nil
err. In particular, a Read
that exhausts the input may return n > 0, os.EOF
.
type Reader interface {
Read(p []byte) (n int, err os.Error)
}
例如,要读取前16个随机字节,
For example, to read the first 16 random bytes,
package main
import (
"fmt"
"crypto/rand"
)
func main() {
b := make([]byte, 16)
n, err := rand.Read(b)
fmt.Println(n, err, b)
}
使用包 init()
函数, crypto / rand
默认使用 / dev / urandom
。
Using a package init()
function, crypto/rand
defaults to using /dev/urandom
.
// Easy implementation: read from /dev/urandom.
// This is sufficient on Linux, OS X, and FreeBSD.
func init() { Reader = &devReader{name: "/dev/urandom"} }
$ b b
这篇关于Go - 关于crypto / rand的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!