~juju-qa/ubuntu/trusty/juju/juju-1.25.8

« back to all changes in this revision

Viewing changes to src/golang.org/x/crypto/hkdf/example_test.go

  • Committer: Nicholas Skaggs
  • Date: 2016-12-02 18:01:10 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161202180110-dl1helep8qfebmhx
ImportĀ upstreamĀ 1.25.6

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2014 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
package hkdf_test
 
6
 
 
7
import (
 
8
        "bytes"
 
9
        "crypto/rand"
 
10
        "crypto/sha256"
 
11
        "fmt"
 
12
        "golang.org/x/crypto/hkdf"
 
13
        "io"
 
14
)
 
15
 
 
16
// Usage example that expands one master key into three other cryptographically
 
17
// secure keys.
 
18
func Example_usage() {
 
19
        // Underlying hash function to use
 
20
        hash := sha256.New
 
21
 
 
22
        // Cryptographically secure master key.
 
23
        master := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this.
 
24
 
 
25
        // Non secret salt, optional (can be nil)
 
26
        // Recommended: hash-length sized random
 
27
        salt := make([]byte, hash().Size())
 
28
        n, err := io.ReadFull(rand.Reader, salt)
 
29
        if n != len(salt) || err != nil {
 
30
                fmt.Println("error:", err)
 
31
                return
 
32
        }
 
33
 
 
34
        // Non secret context specific info, optional (can be nil).
 
35
        // Note, independent from the master key.
 
36
        info := []byte{0x03, 0x14, 0x15, 0x92, 0x65}
 
37
 
 
38
        // Create the key derivation function
 
39
        hkdf := hkdf.New(hash, master, salt, info)
 
40
 
 
41
        // Generate the required keys
 
42
        keys := make([][]byte, 3)
 
43
        for i := 0; i < len(keys); i++ {
 
44
                keys[i] = make([]byte, 24)
 
45
                n, err := io.ReadFull(hkdf, keys[i])
 
46
                if n != len(keys[i]) || err != nil {
 
47
                        fmt.Println("error:", err)
 
48
                        return
 
49
                }
 
50
        }
 
51
 
 
52
        // Keys should contain 192 bit random keys
 
53
        for i := 1; i <= len(keys); i++ {
 
54
                fmt.Printf("Key #%d: %v\n", i, !bytes.Equal(keys[i-1], make([]byte, 24)))
 
55
        }
 
56
 
 
57
        // Output:
 
58
        // Key #1: true
 
59
        // Key #2: true
 
60
        // Key #3: true
 
61
}