~john-koepi/ubuntu/trusty/golang/default

« back to all changes in this revision

Viewing changes to src/pkg/crypto/rand/rand_windows.go

  • Committer: Bazaar Package Importer
  • Author(s): Ondřej Surý
  • Date: 2011-04-20 17:36:48 UTC
  • Revision ID: james.westby@ubuntu.com-20110420173648-ifergoxyrm832trd
Tags: upstream-2011.03.07.1
Import upstream version 2011.03.07.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2010 The Go Authors.  All rights reserved.
 
2
// Use of this source code is governed by a BSD-style
 
3
// license that can be found in the LICENSE file.
 
4
 
 
5
// Windows cryptographically secure pseudorandom number
 
6
// generator.
 
7
 
 
8
package rand
 
9
 
 
10
import (
 
11
        "os"
 
12
        "sync"
 
13
        "syscall"
 
14
)
 
15
 
 
16
// Implemented by using Windows CryptoAPI 2.0.
 
17
 
 
18
func init() { Reader = &rngReader{} }
 
19
 
 
20
// A rngReader satisfies reads by reading from the Windows CryptGenRandom API.
 
21
type rngReader struct {
 
22
        prov uint32
 
23
        mu   sync.Mutex
 
24
}
 
25
 
 
26
func (r *rngReader) Read(b []byte) (n int, err os.Error) {
 
27
        r.mu.Lock()
 
28
        if r.prov == 0 {
 
29
                const provType = syscall.PROV_RSA_FULL
 
30
                const flags = syscall.CRYPT_VERIFYCONTEXT | syscall.CRYPT_SILENT
 
31
                errno := syscall.CryptAcquireContext(&r.prov, nil, nil, provType, flags)
 
32
                if errno != 0 {
 
33
                        r.mu.Unlock()
 
34
                        return 0, os.NewSyscallError("CryptAcquireContext", errno)
 
35
                }
 
36
        }
 
37
        r.mu.Unlock()
 
38
        errno := syscall.CryptGenRandom(r.prov, uint32(len(b)), &b[0])
 
39
        if errno != 0 {
 
40
                return 0, os.NewSyscallError("CryptGenRandom", errno)
 
41
        }
 
42
        return len(b), nil
 
43
}