Go – 加密/随机数的示例

huangapple go评论88阅读模式
英文:

Go - Example about crypto/rand

问题

可以给一个关于crypto/rand的使用的小例子吗?

函数Read的参数是一个字节数组。为什么?因为它访问*/dev/urandom*来获取随机数据。

func Read(b []byte) (n int, err os.Error)

1 http://golang.org/pkg/crypto/rand/

英文:

Could put a little example about the use of crypto/rand 1?

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/

答案1

得分: 6

Read是一个调用Reader.Read的辅助函数。Reader被定义为:var Reader io.Reader

crypto/rand/

io.Reader是包装基本Read方法的接口。

Read将最多len(p)个字节读入到p中。它返回读取的字节数(0 <= n <= len(p))和任何遇到的错误。即使Read返回n < len(p),在调用期间它也可能使用p的所有空间作为临时空间。如果有一些数据可用但不足len(p)个字节,Read通常会返回可用的数据而不是阻塞等待更多数据。

在输入流的末尾,Read返回0, os.EOFRead可能返回一个非零的字节数和一个非nil的错误。特别地,用尽输入的Read可能返回n > 0, os.EOF

type Reader interface {
    Read(p []byte) (n int, err os.Error)
}

io/#Reader

例如,要读取前16个随机字节:

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

// 简单实现:从/dev/urandom读取。
// 这在Linux、OS X和FreeBSD上足够使用。
func init() { Reader = &devReader{name: "/dev/urandom"} }

crypto/rand/rand.go

英文:
func Read(b []byte) (n int, err os.Error)

Read is a helper function that calls Reader.Read. Reader is defined as: var Reader io.Reader.

crypto/rand/

io.Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 &lt;= n &lt;= len(p)) and any error encountered. Even if Read returns n &lt; 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.

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)
}

io/#Reader

For example, to read the first 16 random bytes,

package main

import (
	&quot;fmt&quot;
	&quot;crypto/rand&quot;
)

func main() {
	b := make([]byte, 16)
	n, err := rand.Read(b)
	fmt.Println(n, err, b)
}

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 = &amp;devReader{name: &quot;/dev/urandom&quot;} }

crypto/rand/rand.go

huangapple
  • 本文由 发表于 2010年4月18日 22:45:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/2662591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定